2017-03-02 78 views
0

我在TensorFlow中做矩陣分解,我想從Spicy.sparse中使用coo_matrix,因爲它使用更少的內存,並且可以很容易地將所有數據放入我的矩陣中以獲得訓練數據。在TensorFlow中使用coo_matrix

可以使用coo_matrix初始化張量流變量嗎?

或者我必須創建一個會話,並使用sess.run()和feed_dict將數據輸入到tensorflow中。

我希望你能理解我的問題和我的問題,否則評論,我會盡力解決它。

回答

5

TensorFlow對scipy.sparse.coo_matrix最接近的是tf.SparseTensor,這是tf.Tensor的稀疏等價物。向您的程序中輸入coo_matrix可能是最簡單的。

tf.SparseTensor是COO矩陣的輕微概括,其中張量被表示爲3個密tf.Tensor對象:

  • indicestf.int64值的N X D矩陣,其中每一行代表的一個座標非零值。 N是非零數,D是等效稠密張量的等級(在矩陣的情況下是2)。
  • values:值,其中元件是i其座標上的indicesi行中給出的元素的值的長度 - 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_matrixtf.SparseTensorValue,可以喂sparse_inputtf.SparseTensorValue直接:

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

謝謝,日是我想要的。但你爲什麼要做 sparse_input = tf.sparse_placeholder(dtype = tf.float32,shape = [100,100]) –

+0

這只是一個創建'tf.SparseTensor'的例子。你不必使用特殊的'dtype'或'shape',你可以用你構造的'tf.SparseTensorValue'來提供任何'tf.SparseTensor'(只要它具有兼容的'dtype'和'shape' )。 – mrry

+0

感謝您的快速響應。 –

相關問題