Tensorflow 实现sparse matrix element-wise multiplication 即稀疏矩阵与稠密矩阵的multiply

这里的乘法不是指tensorflow中的tf.matmul 而是 tf.multiply。但是tf.multiply仅实现了两个稠密矩阵的乘法,如果需要计算稀疏矩阵与稠密矩阵的multiply,则可以采用以下的方法计算。

import numpy as np
import scipy.sparse as sp
import tensorflow as tf
def sparse_to_tuple(sparse_mx):
    def to_tuple(mx):
        if not sp.isspmatrix_coo(mx):
            mx = mx.tocoo()
        coords = np.vstack((mx.row, mx.col)).transpose()
        values = mx.data
        shape = mx.shape
        return coords, values, shape
    if isinstance(sparse_mx, list):
        for i in range(len(sparse_mx)):
            sparse_mx[i] = to_tuple(sparse_mx[i])
    else:
        sparse_mx = to_tuple(sparse_mx)
    return sparse_mx
    
    a = np.random.random((4, 4))
    b = np.random.randint(0, 2, (4, 4)).astype(np.float32)
    b2sp = sp.coo_matrix(b)
    sp_mat = tf.sparse_placeholder(tf.float32)
    elem = tf.placeholder(tf.float32, (4, 4))
    elementwise_result = sp_mat.__mul__(elem)
    sess = tf.Session()
    result = sess.run(tf.sparse_tensor_to_dense(elementwise_result),feed_dict={elem:a,sp_mat:sparse_to_tuple(b2sp)})
    print("Sparse Matrix:\n", result)
    print("contrast:\n", b2sp.multiply(a).toarray())

你可能感兴趣的:(machine,learning,deep,learning,ten)