2017-06-23 116 views
0

我是Tensorflow的新手。我正在嘗試在使用Tensorflow的python中編寫一個函數,該函數在稀疏矩陣輸入上運行。通常我會定義一個tensorflow佔位符,但顯然沒有稀疏矩陣的佔位符。在Tensorflow函數中使用稀疏矩陣參數

定義一個在tensorflow中對稀疏數據進行操作並將值傳遞給它的函數的正確方法是什麼?

具體而言,我試圖重寫一個多層感知器的基本例子,在這裏找到https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/multilayer_perceptron.py,接受稀疏輸入,而不是密集。

作爲一個虛擬的例子,你將如何編寫一個看起來像這樣的函數?

import tensorflow as tf 


x = tf.placeholder("sparse") 
y = tf.placeholder("float", [None, n_classes]) 

# Create model 
def sparse_multiply(x, y): 

    outlayer = tf.sparse_tensor_dense_matmul(x, y) 

    return out_layer 

pred = multiply(x, y) 

# Launch the graph 
with tf.Session() as sess: 
    result = sess.run(pred, feed_dict={x: x_input, y: y_input}) 

有人在鏈路https://github.com/tensorflow/tensorflow/issues/342建議,作爲一種解決方法,傳入構造稀疏矩陣所需要的元素,然後創建該函數內的飛稀疏矩陣。這似乎有點冒失,當我試圖以這種方式構建它時,我會遇到錯誤。

任何幫助,特別是與代碼的答案,將不勝感激!

回答

0

我想我想通了。我建議的鏈接實際上確實有效,我只需要糾正所有輸入以獲得一致的類型。這裏是我列在問題中的虛擬示例,編碼正確:

import tensorflow as tf 

import sklearn.feature_extraction 
import numpy as np 


def convert_csr_to_sparse_tensor_inputs(X): 
    coo = X.tocoo() 
    indices = np.mat([coo.row, coo.col]).transpose() 
    return indices, coo.data, coo.shape 


X = ____ #Some sparse 2 x 8 csr matrix 

y_input = np.asarray([1, 1, 1, 1, 1, 1, 1, 1]) 
y_input.shape = (8,1) 


x_indices, x_values, x_shape = convert_csr_to_sparse_tensor_inputs(X) 

# tf Graph input 
y = tf.placeholder(tf.float64) 
values = tf.placeholder(tf.float64) 
indices = tf.placeholder(tf.int64) 
shape = tf.placeholder(tf.int64) 

# Create model 
def multiply(values, indices, shape, y): 

    x_tensor = tf.SparseTensor(indices, values, shape)  

    out_layer = tf.sparse_tensor_dense_matmul(x_tensor, y) 


    return out_layer 

pred = multiply(values, indices, shape, y) 

# Launch the graph 
with tf.Session() as sess: 
    result = sess.run(pred, feed_dict={values: x_values, indices: x_indices, shape: x_shape, y: y_input})