tensorflow--稀疏张量--4--tf.SparseTensor

例子

tf.SparseTensor(values=[‘en’,‘fr’,‘zh’],indices=[[0,0],[0,1],[2,0]],shape=[3,2])

1.shape=[3,2] ,生成3*2的数组

[[0,0]
[0,0]
[0,0]
]

2.indices=[[0,0],[0,1],[2,0]],说明上面数组的这些下标的位置是有值的

3、values=[‘en’,‘fr’,‘zh’]

就是与values给的这些值相对应,最终表示的矩阵为:

[['en' 'fr'] 
['0' '0'] 
['zh' '0']]

coo_matrix构建SparseTensorValue

sparse_input = tf.sparse_placeholder(dtype=tf.float32, shape=[100, 100])
# ...
train_op = ...

coo_matrix = scipy.sparse.coo_matrix(...)

# Wrap `coo_matrix` in the `tf.SparseTensorValue` form that TensorFlow expects.
# SciPy stores the row and column coordinates as separate vectors, so we must 
# stack and transpose them to make an indices matrix of the appropriate shape.
tf_coo_matrix = tf.SparseTensorValue(
    indices=np.array([coo_matrix.rows, coo_matrix.cols]).T,
    values=coo_matrix.data,
    dense_shape=coo_matrix.shape)

sess.run(train_op, feed_dict={sparse_input: tf_coo_matrix})

参考资料

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn