how use "append" in tensorflow loop without python collections?

Viewed 98

i want this layer in keras. but in outside tf.loop, i used "list.append(values)" that it is wrong. becuase i can't use Python collections in there and i get error. What should I use? flat_cp shape=(1,3^16) and CP shape should be (200,1,3^16).thanks!

class WeightedLayer(Layer):
  def __init__(self, n_input, n_memb, **kwargs):
    super(WeightedLayer, self).__init__( **kwargs)
    self.n = n_input   # 16 features
    self.m = n_memb    # 3

  def build(self, batch_input_shape):
    super(WeightedLayer, self).build(batch_input_shape)

  def call(self, input_):
    CP = []
    self.batch_size = tf.shape(input_)[0]
    for batch in tf.range(self.batch_size):
        xd_shape = [self.m]
        c_shape = [1]
        cp=input_[batch,0,:]            
        for d in range(1,self.n):
            c_shape.insert(0,self.m)
            xd_shape.insert(0,1)
            xd = tf.reshape(input_[batch,d,:], (xd_shape))
            c = tf.reshape(cp,(c_shape))
            cp = tf.matmul(c , xd)
        flat_cp = tf.reshape(cp,(1, self.m**self.n))
        CP.append(flat_cp)     #________________error___________________
    c=tf.stack(CP)
    return tf.reshape(c, (self.batch_size, self.m**self.n))

def compute_output_shape(self, batch_input_shape):
    return tf.TensorShape([self.batch_size, self.m ** self.n])

X_train = np.random.uniform(0, 1, (200, 16, 3))
X_test = np.random.uniform(0, 1, (200, 16, 3))
y_train = np.random.uniform(0, 1, (200,))
y_test = np.random.uniform(0, 1, (200,))

Model = keras.models.Sequential()
Model.add(WeightedLayer(n_input=16, n_memb=3,input_shape=(16, 3)))
Model.compile(loss='mean_squared_error', optimizer='adam')
Model.fit(X_train, y_train,epochs=20,batch_size=10,validation_data=(X_test, y_test))
1 Answers

i should use tf.TensorArray with dynamic size,not CP=[].because we can't use python collections in there and tensorArray should be used. then for end be used CP.stack(),not tf.stack(CP).

Related