2016-05-06 124 views
6

由於在使用Tensorflow來訓練模型之前需要爲數據編寫一些預處理,因此需要對tensor進行一些修改。但是,我不知道如何修改tensor中的值,例如使用numpy的方式。Tensorflow:如何修改張量中的值

這樣做的最好方法是可以直接修改tensor。然而,在當前版本的Tensorflow中似乎不可能。另一種方法是將tensor更改爲ndarray,然後使用tf.convert_to_tensor進行更改。

關鍵是如何將tensor更改爲ndarray
1)tf.contrib.util.make_ndarray(tensor)https://www.tensorflow.org/versions/r0.8/api_docs/python/contrib.util.html#make_ndarray
它似乎是最簡單的方法,但我無法在當前版本的Tensorflow中找到此功能。其次,它的輸入是TensorProto而不是tensor
2)使用a.eval()a複製到另一個ndarray
但是,它只在筆記本中使用tf.InteractiveSession()

帶代碼的簡單情況如下所示。該代碼的目的是使得tfc在處理後具有與npc相同的輸出。

提示
你應該把那tfcnpc是相互獨立的。這符合這樣的情況,首先檢索的訓練數據是tensor格式,其格式爲tf.placeholder()


源代碼

import numpy as np 
import tensorflow as tf 
tf.InteractiveSession() 

tfc = tf.constant([[1.,2.],[3.,4.]]) 
npc = np.array([[1.,2.],[3.,4.]]) 
row = np.array([[.1,.2]]) 
print('tfc:\n', tfc.eval()) 
print('npc:\n', npc) 
for i in range(2): 
    for j in range(2): 
     npc[i,j] += row[0,j] 

print('modified tfc:\n', tfc.eval()) 
print('modified npc:\n', npc) 

輸出:

TFC:
[[1. 2.]
[3. 4.]]
npc:
[[1. 2.]
[3. 4.]]
改性TFC:
[[1. 2.]
[3. 4.]]
改性NPC:
[[ 1.1 2.2]
[3.1 4.2]]

回答

4

使用分配和eval(或sess.run)的分配:

import numpy as np 
import tensorflow as tf 

npc = np.array([[1.,2.],[3.,4.]]) 
tfc = tf.Variable(npc) # Use variable 

row = np.array([[.1,.2]]) 

with tf.Session() as sess: 
    tf.initialize_all_variables().run() # need to initialize all variables 

    print('tfc:\n', tfc.eval()) 
    print('npc:\n', npc) 
    for i in range(2): 
     for j in range(2): 
      npc[i,j] += row[0,j] 
    tfc.assign(npc).eval() # assign_sub/assign_add is also available. 
    print('modified tfc:\n', tfc.eval()) 
    print('modified npc:\n', npc) 

它輸出:

tfc: 
[[ 1. 2.] 
[ 3. 4.]] 
npc: 
[[ 1. 2.] 
[ 3. 4.]] 
modified tfc: 
[[ 1.1 2.2] 
[ 3.1 4.2]] 
modified npc: 
[[ 1.1 2.2] 
[ 3.1 4.2]] 
+0

謝謝!我認爲你的想法是假設'tfc'在開始時與'npc'共享相同的值,所以你可以先對'npc'進行處理,然後把'tfc'分配給'tfc'。但情況並非如此。 在實際情況中,您唯一的數據是'tfc',這表明您需要處理'npc'在開始時不存在。所以關鍵在於如何處理'tfc'中的數據。 – user3030046

+0

@ user3030046取決於操作。如果它們是簡單的add/sub,則使用assign_sub/assign_add。其他人,我們有很多其他的方法。你想更新tf.Tensor中的元素嗎?如果你給我一個用例,我會看看我能做什麼。 –

+0

我的情況是我正在嘗試實現CBOW(這裏是最後一個單元格)(https://github.com/tensorflow/tensorflow/blob/e39d8feebb9666a331345cd8d960f5ade4652bba/tensorflow/examples/udacity/5_word2vec.ipynb)。需要對所有附近跳過的向量求和以進行預測,具體來說,就像在10乘3的矩陣上使用逐行和,並輸出一個10乘1的向量,這個卷積操作將重複10 100個矩陣,它會產生一個相同大小的輸出矩陣,你有什麼想法嗎? – user3030046