+-

嗨,我正在关注一个神经网络教程,作者似乎在各处使用共享变量.据我了解,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()
问题是我不知道如何在常规函数输出调用中使用共享变量.我了解可以通过function([],.. update =(shared_var_1,upate_function))进行更新.但是,如何在常规功能中访问它们?
最佳答案
Theano的初学者在这里,所以我不确定我的答案会涵盖所有技术方面.
回答您的第一个问题:您需要声明theano函数而不是def函数,因为theano就像是python内部的一种“语言”并调用theano.function.您正在编译一些专门的C代码来在后台执行任务.这就是Theano快速发展的原因.
从documentation开始:
It is good to think of
theano.functionas the interface to a compiler which builds a callable object from a purely symbolic graph. One of Theano’s most important features is that theano.function can optimize a graph and even compile some or all of it into native machine instructions.
关于第二个问题,为了访问共享变量中存储的内容,您应该使用
shared_var.get_value()
查看these示例:
The value can be accessed and modified by the
.get_value()and
.set_value()methods.
这段代码:
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
点击查看更多相关文章
转载注明原文:python-在函数中使用共享变量 - 乐贴网