我想通過使用tf.matmul()執行稀疏矩陣乘法。如何使用tf.matmul執行高效的稀疏矩陣乘法?
然而,推理速度比密集矩陣乘法慢得多。
根據tf.sparse_matmul()的描述:
- 使用該對緻密矩陣乘法在一個平臺上爲30%,在稀疏矩陣的零值的盈虧平衡。
因此,我就與7/8零值的稀疏矩陣。
這裏是我的代碼:
import tensorflow as tf
import numpy as np
import time
a = tf.Variable(np.arange(1000).reshape(250,4) ,dtype=tf.float32) #dense matrix
b = tf.Variable(np.array([0,0,0,0,0,0,0,1],dtype=np.float32).reshape(4,2),dtype=tf.float32) # sparse matrix
c = tf.matmul(a,b,b_is_sparse=True) # do the sparse matrix multiplication
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
num_iteration = 5000
num_burnin = 50
duration = 0
for i in range(num_iteration+num_burnin):
startTime = time.time()
result = sess.run(c)
endTime = time.time()
if i > num_burnin :
duration+= endTime-startTime
print(" Average Inference Time = %.3f ms"%(duration*1000/num_iteration))
我設置「b_is_sparse =真」做一個稀疏矩陣乘法,它發生在我的GeForce GTX 960M約0.380毫秒。
但是,如果設置了「b_is_sparse =假」做一個密集的矩陣乘法,它需要大約0.280毫秒。
我試過使用tf.sparse_tensor_dense_matmul和tf.embedding_lookup_sparse來執行稀疏矩陣乘法,但推理速度仍然比密集矩陣乘法要慢。
在我的代碼或其他方式執行稀疏矩陣乘法有什麼問題嗎?
任何意見將不勝感激!