Theano 简明教程

Theano - Shared Variables

很多时候,您需要创建在不同方法之间以及在对同一方法的多次调用之间共享的变量。举个例子,在神经网络训练期间,您会创建权重向量,用于为每个正在考虑的特征分配权重。在网络训练期间的每次迭代中都会修改此向量。因此,它必须在对同一方法的多次调用期间全局可访问。因此,我们为此创建一个共享变量。通常,Theano 将此类共享变量移动到 GPU(如果可用)。这会加快计算速度。

Many a times, you would need to create variables which are shared between different functions and also between multiple calls to the same function. To cite an example, while training a neural network you create weights vector for assigning a weight to each feature under consideration. This vector is modified on every iteration during the network training. Thus, it has to be globally accessible across the multiple calls to the same function. So we create a shared variable for this purpose. Typically, Theano moves such shared variables to the GPU, provided one is available. This speeds up the computation.

Syntax

您使用以下语法创建一个共享变量 −

You create a shared variable you use the following syntax −

import numpy
W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), 'W')

Example

这里创建了一个包含四个浮点数的 NumPy 数组。要设置/获取 W 值,您将使用以下代码片段 −

Here the NumPy array consisting of four floating point numbers is created. To set/get the W value you would use the following code snippet −

import numpy
W = theano.shared(numpy.asarray([0.1, 0.25, 0.15, 0.3]), 'W')
print ("Original: ", W.get_value())
print ("Setting new values (0.5, 0.2, 0.4, 0.2)")
W.set_value([0.5, 0.2, 0.4, 0.2])
print ("After modifications:", W.get_value())

Output

Original: [0.1 0.25 0.15 0.3 ]
Setting new values (0.5, 0.2, 0.4, 0.2)
After modifications: [0.5 0.2 0.4 0.2]