我在TensorFlow中做矩陣分解,我想從Spicy.sparse中使用coo_matrix,因爲它使用更少的內存,並且可以很容易地將所有數據放入我的矩陣中以獲得訓練數據。在TensorFlow中使用coo_matrix
可以使用coo_matrix初始化張量流變量嗎?
或者我必須創建一個會話,並使用sess.run()和feed_dict將數據輸入到tensorflow中。
我希望你能理解我的問題和我的問題,否則評論,我會盡力解決它。
我在TensorFlow中做矩陣分解,我想從Spicy.sparse中使用coo_matrix,因爲它使用更少的內存,並且可以很容易地將所有數據放入我的矩陣中以獲得訓練數據。在TensorFlow中使用coo_matrix
可以使用coo_matrix初始化張量流變量嗎?
或者我必須創建一個會話,並使用sess.run()和feed_dict將數據輸入到tensorflow中。
我希望你能理解我的問題和我的問題,否則評論,我會盡力解決它。
TensorFlow對scipy.sparse.coo_matrix
最接近的是tf.SparseTensor
,這是tf.Tensor
的稀疏等價物。向您的程序中輸入coo_matrix
可能是最簡單的。
甲tf.SparseTensor
是COO矩陣的輕微概括,其中張量被表示爲3個密tf.Tensor
對象:
indices
:tf.int64
值的N
X D
矩陣,其中每一行代表的一個座標非零值。 N
是非零數,D
是等效稠密張量的等級(在矩陣的情況下是2)。values
:值,其中元件是i
其座標上的indices
i
行中給出的元素的值的長度 - N
矢量。dense_shape
:長度 - D
矢量tf.int64
,表示等效稠密張量的形狀。例如,可以使用下面的代碼,它使用tf.sparse_placeholder()
以限定tf.SparseTensor
可以飼料,和表示實際值被饋送一個tf.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)
一旦轉換您coo_matrix
到tf.SparseTensorValue
,可以喂sparse_input
與tf.SparseTensorValue
直接:
sess.run(train_op, feed_dict={sparse_input: tf_coo_matrix})
謝謝,日是我想要的。但你爲什麼要做 sparse_input = tf.sparse_placeholder(dtype = tf.float32,shape = [100,100]) –
這只是一個創建'tf.SparseTensor'的例子。你不必使用特殊的'dtype'或'shape',你可以用你構造的'tf.SparseTensorValue'來提供任何'tf.SparseTensor'(只要它具有兼容的'dtype'和'shape' )。 – mrry
感謝您的快速響應。 –