问题描述
我一直在尝试为TensorFlow中的工作目的实现自定义的GRU单元。因此,我开始尝试构建自定义的简单GRU(不添加任何功能)。但是我遇到了很多问题。让我说出我所知道和尝试过的。我已经阅读了TensorFlow上的自定义图层文章,并开始构建它,但无法弄清楚。
我已经尽力了。需要关于如何实现定制GRU单元的更好建议。
目标:构建定制的GRU单元(最好在Tensorflow中)。解决张量形状误差
问题:
- 张量形状不兼容。
- 有关此问题的文档太少。 (如果我理解起来很复杂)
我对GRU单元的实现:
class GruIdn(tf.keras.layers.Layer):
def __init__(self,units,input_size=None,**kwargs):
self.units = units
self._input_size = units if input_size is None else input_size
super(GruIdn,self).__init__(**kwargs)
@property
def input_size(self):
return self._input_size
@property
def output_size(self):
return self.units
@property
def state_size(self):
return self.units
def build(self,input_shapes):
self.weight_1 = self.add_weight(
shape=(input_shapes[-1],3*self.units),initializer = keras.initializers.glorot_uniform(),trainable=True)
self.weight_2 = self.add_weight(
shape=(self.units,trainable=True)
def call(self,inputs,states):
x_mul_w = tf.linalg.matmul(inputs,self.weight_1)
h_prev_mul_w = tf.linalg.matmul(states[0],self.weight_2)
print(x_mul_w.shape,h_prev_mul_w.shape)
i_z,i_r,i_hnew = tf.split(x_mul_w,num_or_size_splits=3,axis=1)
h_z,h_r,h_hnew = tf.split(h_prev_mul_w,axis=1)
update_gate = tf.keras.activations.sigmoid(i_z+h_z)
reset_gate = tf.keras.activations.sigmoid(i_r+h_r)
h_new = tf.keras.activations.tanh(i_hnew+ tf.multiply(reset_gate,h_hnew))
output=newstates = tf.multiply(update_gate,states) + tf.multiply((1-update_gate),h_new)
return output,newstates
检查GRUcell的代码:
inputs = tf.random.normal([32,10,8])
rnn = tf.keras.layers.RNN(GruIdn(4))
print(inputs.shape)
output = rnn(inputs)
print(output.shape)
错误: Tensor shape error 我对此很陌生,因此可能存在编码错误。为此,请原谅我。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)