Dr.*_*all 3 python pycuda theano
嗨,我正在关注一个神经网络教程,作者似乎在各处使用共享变量。据我了解,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()
Run Code Online (Sandbox Code Playgroud)
问题是我不知道如何在常规函数输出调用中使用共享变量。我了解可以通过function([],.. update =(shared_var_1,upate_function))进行更新。但是,如何在常规功能中访问它们?
Theano的初学者在这里,所以我不确定我的答案会涵盖所有技术方面。
回答您的第一个问题:您需要声明theano函数而不是def函数,因为theano就像python中的“语言”,并调用theano.function 您来编译一些专门的C代码,在后台执行您的任务。这就是Theano快速发展的原因。从文档中:
最好将其
theano.function视为编译器的接口,该编译器从纯符号图构建可调用对象。Theano最重要的功能之一是theano.function可以优化图形,甚至可以将其中的一些或全部编译为本地机器指令。
关于第二个问题,为了访问共享变量中存储的内容,您应该使用
shared_var.get_value()
Run Code Online (Sandbox Code Playgroud)
检查以下示例:
可以通过
.get_value()和.set_value()方法访问和修改该值。
这段代码:
a = np.array([[1,2],[3,4]], dtype=theano.config.floatX)
x = theano.shared(a)
print(x)
Run Code Online (Sandbox Code Playgroud)
将输出
<CudaNdarrayType(float32, matrix)>
Run Code Online (Sandbox Code Playgroud)
但是使用get_value():
print(x.get_value())
Run Code Online (Sandbox Code Playgroud)
它输出
[[ 1. 2.]
[ 3. 4.]]
Run Code Online (Sandbox Code Playgroud)
编辑:在函数中使用共享变量
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())
Run Code Online (Sandbox Code Playgroud)
将输出:
5
4
5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2563 次 |
| 最近记录: |