Tensorflow修改張量特定位置元素的值

張量和array一樣可以通過切片獲取,但是張量不可以直接修改某個值
可以理解爲張量具有“只讀”的模式

如果按照數組修改某個值的方式處理的話,會報錯:

import tensorflow as tf
tensor_1 = tf.constant([x for x in range(1,10)])
tensor_1[4] = 0    # TypeError: 'Tensor' object does not support item assignment

解決方法:
張量切片,再拼接。比如:

tensor_1 = tf.constant([x for x in range(1,10)])
# 切片
part1 = tensor_1[:4]
part2 = tf.constant([0])   # 要修改的元素
part3 = tensor_1[5:]
# 拼接
new_tensor = tf.concat([part1,part2,part3], axis=0)

值得注意的一點:如果在進行這樣的操作的時候代碼報錯,記得檢查每個 part 的維度,大概率是維度這裏出了問題。
牢記:原來張量是幾維,最後要拼成幾維。(比如你的張量是3維的,先要切分成三個2維的,再將二維張量切成1維,修改拼接成2維,再拼接成3維)

下面舉一個三維拼接的例子:

import tensorflow as tf
import numpy as np

class tttest():
    def __init__(self):
      self.tensor_1 = tf.placeholder(tf.int32, [None, 3])
      self.part1 = self.tensor_1[:3]
      self.part2 = self.tensor_1[3]
      self.part2_1 = self.part2[:1]
      self.part2_2 = tf.constant([10])
      self.part2_3 = self.part2[2:]
      self.part2 = tf.expand_dims(tf.concat([self.part2_1, self.part2_2, self.part2_3], axis=0),0)
      self.part3 = self.tensor_1[4:]
      self.t = tf.concat([self.part1, self.part2, self.part3], axis=0)            # 這樣寫是正確的
      # self.tensor_1 = tf.concat([self.part1, self.part2, self.part3], axis=0)   # 這樣會報錯
      
with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    fd = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]])
    a = tttest()
    print("tensor_1", sess.run(a.part1, {a.tensor_1:fd}))
    print("tensor_2", sess.run(a.part2, {a.tensor_1:fd}))
    print("tensor_3", sess.run(a.part3, {a.tensor_1:fd}))
    print("tensor_3", sess.run(a.t, {a.tensor_1: fd}))

其中,如果將修改後的值還是賦給 tensor_1 會報錯如下:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype int32 and shape [?,3]
  [[Node: Placeholder = Placeholder[dtype=DT_INT32, shape=[?,3], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

關於placeholder需要注意的是:不可以重新賦值給placeholder類型的,因爲這樣會使得 feedfic 的時候 tensorflow 找到兩個名字一樣但是一個是 placeholder 類型,一個不是,必然會報錯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章