tensorflow第二坑-矩阵向量相乘
Table of Contents
突然发现tensorflow的tf.matmul()只能进行矩阵之间相乘,不能进行矩阵和向量相乘!例如:
Ws = tf.get_variable('Ws', [hidden_size])
bias_s = tf.get_variable('bs', [1])
score_tensor = tf.matmul(hidden, Ws) + bias_s
* 1
* 2
* 3
会报错:
ValueError: Shape must be rank 2 but is rank 1 for ‘Model/MatMul_1’ (op:
‘MatMul’) with input shapes: [640,15], [15].
解决方法 :
先点乘再求和,因为tf.mul()是可以broadcast的。
代码:
u=tf.reshape(np.arange(0,6),[3,2])
v=tf.Variable(tf.random_uniform([2]))
mul=tf.reduce_sum(tf.mul(tf.cast(u,tf.float32),v),reduction_indices=1)
s=tf.Session()
s.run(tf.initialize_all_variables())
print s.run(mul)
* 1
* 2
* 3
* 4
* 5
* 6
output:
[ 0.81020808 4.1664238 7.52263975]
* 1
0 评论