2017-05-28 97 views
0

我想要做的是爲我的神經網絡增加一個權重矩陣,它的大小會增加(即每次迭代都會添加一個神經元)。但是,我不想再次使用tf.Variable,因爲這會通過複製上一個矩陣中的值而不是擴展矩陣本身而浪費內存。如何放大張量流中的矩陣而不重複值?

我已經看到人們使用tf.assign與validate_shape設置爲False,但是,這並沒有改變正確的變量的形狀,我認爲這是一個錯誤,但張量流GitHub似乎並不同意(我不'不知道爲什麼從他們的reply)。

下面是該問題的簡單示例。 x是我想要擴展的矩陣,以便它可以添加到z中。如果有人知道什麼,我想在這裏實現我會很感激的解決方案=)

import tensorflow as tf 
import numpy as np 

# Initialise some variables 
sess = tf.Session() 
x = tf.Variable(tf.truncated_normal([2, 4], stddev = 0.04)) 
z = tf.Variable(tf.truncated_normal([3, 4], stddev = 0.04)) 
sess.run(tf.variables_initializer([x, z])) 

# Enlarge the matrix by assigning it a new set of values 
sess.run(tf.assign(x, tf.concat((x, tf.cast(tf.truncated_normal([1, 4], stddev = 0.04), tf.float32)), 0), validate_shape=False)) 

# Print shapes of matrices, notice that x's actual shape is different for the 
# shape tensorflow has recorded for it 
print(x.get_shape()) 
print(x.eval(session=sess).shape) 
print(z.get_shape()) 
print(z.eval(session=sess).shape) 

# Add two matrices with equal shapes 
print(tf.add(x, z).eval(session=sess)) 

注:我意識到,如果我初始化Z到形狀(2,4 ),然後用tf.assign擴展它(就像我用x做的那樣),上面的例子就可以工作。但由於另一個約束,我無法控制z的原始形狀。

回答

0

tensorflow中的張量是不可變的,所以你不能輕易地重新縮放它們。

可以嘗試墊與tf.gather()中的矩陣的0和然後訪問份作爲這裏How to select rows from a 3-D Tensor in TensorFlow?

所示較大填充基質中實現「子矩陣」。然而,這似乎並不是一個簡單或優雅的解決方案。

相關問題