【问题标题】:adding broadcastble matrix in theano在 theano 中添加可广播矩阵
【发布时间】:2016-10-25 14:50:28
【问题描述】:

我有两个形状为 (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 更快吗?

【问题讨论】:

    标签: python theano


    【解决方案1】:

    经过几个小时的搜索和阅读,我找到了答案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 的原因。

    【讨论】:

      猜你喜欢
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多