tf.sparse_tensor_dense_matmul 是对稀疏张量和稠密张量做矩阵乘法的函数,但为什么我运算的结果与 numpy 运算结果不同?
import numpy as np
import tensorflow as tf
import scipy.sparse as sp
arr = np.array([[1.,2.,5.,2.],[3.,4.,1.,2.],[3.,5.,2.,6.],[4.,13.,2.,10.]]) # 4*4
arr = sp.coo_matrix(arr)
b = np.array([[1.],[2.],[3.],[4.]])
b = tf.convert_to_tensor(b, dtype=tf.float32)
if not sp.isspmatrix_coo(arr):
arr = arr.tocoo()
arr = arr.astype(np.float32)
indices = np.vstack((arr.col, arr.row)).transpose()
a_sp = tf.SparseTensor(indices=indices, values=arr.data, dense_shape=arr.shape)
with tf.Session() as sess:
m=tf.sparse_tensor_dense_matmul(a_sp, b)
print(sess.run(m))
结果:
[[32.]
[77.]
[21.]
[64.]]
numpy 下:
x = np.array([[1,2,5,2],[3,4,1,2],[3,5,2,6],[4,13,2,10]],dtype=np.float)
y = np.array([[1],[2],[3],[4]], dtype=np.float)
x @ y
结果:
array([[28.],
[22.],
[43.],
[76.]]