Skip to main content
 首页 » 编程设计

python之如何访问theano.tensor.var.TensorVariable

2025年05月04日14bhlsheji

假设我有一个大小为 (1152, 10) 的矩阵 w,如下所示:

>>> w.get_value(True) 
array([[-0.03824838, -0.02033614,  0.040734  , ...,  0.01585871, 
         0.04165901,  0.01058411], 
       [-0.00626427,  0.00891617,  0.01286055, ...,  0.00184506, 
        -0.01282589, -0.00209718], 
       [ 0.00457122, -0.01036582,  0.02780926, ...,  0.01269533, 
        -0.00953711, -0.00271188], 
       ...,  
       [ 0.00592541, -0.00267455,  0.02258315, ..., -0.00788802, 
         0.02260087, -0.01107418], 
       [-0.02363299,  0.02963436,  0.02735142, ..., -0.01933786, 
        -0.03731941,  0.02085613], 
       [-0.0079082 ,  0.01099584,  0.01910999, ...,  0.00122137, 
        -0.006866  , -0.01500945]]) 

我有一个大小为 (1152, 1) 的输入,如下所示:

>> input.get_value(True) 
array([ 0.,  0.,  0., ...,  0.,  0.,  0.]) 

现在我想像这样计算它们的点乘法:

>> result = theano.tensor.dot(image, w) 

它给了我:

>>> result 
dot.0 
>>> type(result) 
<class 'theano.tensor.var.TensorVariable'> 
>>> type(image) 
<class 'theano.tensor.sharedvar.TensorSharedVariable'> 
>>> type(classifier.W) 
<class 'theano.tensor.sharedvar.TensorSharedVariable'> 

theano.tensor.dot 是否返回符号表达式而不是值?

请您参考如下方法:

一言以蔽之:是的。

要查看操作结果,请使用 result.eval()

最小工作示例:

import numpy as np 
import theano 
from theano import tensor as T 
w_values = np.random.randn(1152, 10).astype(theano.config.floatX) 
input_values = np.random.randn(1152, 1).astype(theano.config.floatX) 
w = theano.shared(w_values, 'w') 
input = theano.shared(input_values, 'input') 
result = T.dot(input.T, w) 
print(result.eval())