在函数

时间:2015-08-02 02:47:25

标签: python theano pycuda

您好我正在关注神经网络教程,其中作者似乎在各处使用共享变量。根据我的理解,theanos中的共享变量只是内存中的空间,可以由gpu和cpu堆共享。无论如何,我有两个矩阵,我声明为共享变量,我想使用函数对它们执行一些操作。 (问题1)如果有人能够解释为什么函数对常规def函数有用,我会喜欢它。无论如何,我正在设置我的定义:

import theano
import theano.tensor as T
from theano import function
import numpy as np

class Transform:
    def __init__(self, dimg):
        dimg = dimg.astype(theano.config.floatX)
        self.in_t = theano.shared(dimg, name='dimg', borrow=True)

    def rotate(self, ox, oy, radians):
        value = np.zeros((2 * self.in_t.get_value().shape[0],
                          2 * self.in_t.get_value().shape[1]))
        out_t = theano.shared(value,
                              name='b',
                              dtype=theano.config.floatX),
                              borrow=True)    
        din = theano.tensor.dmatrix('a')
        dout = theano.tensor.dmatrix('b')

        def atest():
            y = x + y
            return y

        f = function(inputs=[],
                     givens={x: self.in_t,
                             y: self.out_t},
                     outputs=atest)    
        return f()

问题是我不知道如何在常规函数输出调用中使用共享变量。我知道我可以通过函数([],.. update =(shared_var_1,upate_function))进行更新。但是如何在常规功能中访问它们?

1 个答案:

答案 0 :(得分:4)

Theano初学者,所以我不确定我的答案将涵盖所有技术方面。

回答第一个问题:你需要声明theano函数而不是def函数,因为theano就像python中的“语言”并调用theano.function你正在编译一些广告 - 在底层执行任务的临时C代码。这就是使Theano快速的原因。 来自documentation

  

theano.function视为编译器的接口是很好的,该编译器从纯符号图构建可调用对象。 Theano最重要的功能之一是theano.function可以优化图形,甚至可以将其中的部分或全部编译为本机机器指令。

关于第二次排队,为了访问共享变量中存储的内容,您应该使用

shared_var.get_value()

检查these示例:

  

.get_value()和{}可以访问和修改该值   .set_value()方法。

此代码:

a = np.array([[1,2],[3,4]], dtype=theano.config.floatX)
x = theano.shared(a)
print(x)

将输出

<CudaNdarrayType(float32, matrix)>

但是使用get_value()

print(x.get_value())

输出

[[ 1.  2.]
 [ 3.  4.]]

修改以在函数中使用共享变量

import theano
import numpy
a = numpy.int64(2)
y = theano.tensor.scalar('y',dtype='int64')
z = theano.tensor.scalar('z',dtype='int64')
x = theano.shared(a)
plus = y + z
theano_sum = theano.function([y,z],plus)
# Using shared variable in a function
print(theano_sum(x.get_value(),3))
# Changing shared variable value using a function
x.set_value(theano_sum(2,2))
print(x.get_value())
# Update shared variable value
x.set_value(x.get_value(borrow=True)+1)
print(x.get_value())

将输出:

5
4
5