在theano中添加广播矩阵

时间:2016-10-23 03:40:20

标签: python theano

我有两个形状为(1,3)和(3,1)的矩阵 我想添加它们并输出一个矩阵(3,3) 在numpy中,它的工作原理如下:

import numpy as np
a = np.array([0,1,2])
b = a.reshape(3,1)
a+b

它输出:

array([0,1,2],
[1,2,3],
[2,3,4]]

现在我想使用theano做同样的事情,以加快代码。 我的代码如下所示:

label_vec1 = T.imatrix('label_vector')
label_vec2 = T.imatrix('label_vector')
alpha_matrix = T.add(label_vec1, label_vec2)
alpha_matrix_compute = theano.function([label_vec1,label_vec2],alpha_matrix)

a = numpy.array([[0,1,2]])
b = numpy.array([[0],[1],[2]])#
a1=theano.shared(numpy.asarray(a), broadcastable =(True,False))
b1 = theano.shared(numpy.asarray(b),broadcastable=(False, True))
c = alpha_matrix_compute(a1,b1)

但它输出

TypeError: ('Bad input argument to theano function at index 0(0-based)', 'Expected an array-like object, but found a Variable: maybe you are trying to call a function on a (possibly shared) variable instead of a numeric array?')

我很困惑,为什么会发生? 顺便说一下,使用带有GPU的theano比使用numpy更快吗?

1 个答案:

答案 0 :(得分:0)

经过一段时间的搜索和阅读后,我找到了答案here

将numpy数组定义为共享变量时,它变为符号变量,不再是数值数组。

要使用共享变量进行计算,应按以下方式修改代码:

a = numpy.array([[0,1,2]])
b = numpy.array([[0],[1],[2]])#
#b = a.reshape(a.shape[1],a.shape[0])
a1=theano.shared(numpy.asarray(a), broadcastable =(True,False), borrow =True)
b1 = theano.shared(numpy.asarray(b),broadcastable=(False, True),borrow = True)

alpha_matrix = T.add(a1, b1)
alpha_matrix_compute = theano.function([], alpha_matrix)

s_t_1 = timeit.default_timer()
for i in range(10000):
    c = alpha_matrix_compute()
e_t_1 = timeit.default_timer()
for i in range(10000):
    c = numpy.add(a,b)
e_t_2 = timeit.default_timer()
print('t1:',e_t_1-s_t_1)
print('t2:',e_t_2-e_t_1)

另外,我比较了使用theano和numpy的可广播矩阵添加的耗时。结果是

t1: 0.25077449798077067
t2: 0.022930744192201424

似乎numpy更快。事实上,GPU和CPU之间的数据传输花费了大量时间。这就是为什么t2比t1小得多的原因。