tensorflow2.0 中 tf稀疏矩阵张量 SparseTensor 的indices必须是排好序的否则可以打印,但转换成普通矩阵是就会报这个错误(我只学了tf2.0,1.x不清楚)
import tensorflow as tf
s = tf.SparseTensor(indices = [[0, 2], [0, 1], [2, 3]],
values = [1, 2., 3.],
dense_shape = [3, 4])
print(s)
# 转换成普通矩阵
print(tf.sparse.to_dense(5))
解决:用tf.sparse.reorder对SparseTensor的indices排一下序就行了:
import tensorflow as tf
s = tf.SparseTensor(indices = [[0, 2], [0, 1], [2, 3]],
values = [1, 2., 3.],
dense_shape = [3, 4])
print(s)
# tf稀疏矩阵索引排序
s_ordered = tf.sparse.reorder(s)
print(tf.sparse.to_dense(s_ordered))