with tf.variable_scope('forward'):
cell_img_fwd = tf.nn.rnn_cell.GRUCell(hidden_state_size, hidden_state_size)
img_init_state_fwd = rnn_img_mapped[:, 0, :]
img_init_state_fwd = tf.multiply(
img_init_state_fwd,
tf.zeros([batch_size, hidden_state_size]))
rnn_outputs2, final_state2 = tf.nn.dynamic_rnn(
cell_img_fwd,
rnn_img_mapped,
initial_state=img_init_state_fwd,
dtype=tf.float32)
Run Code Online (Sandbox Code Playgroud)
这是我用于输入维度100x196x50的GRU的代码,它应该沿第二维(即196)解压缩.hidden_state_size是50,batch_size是100.但是我收到以下错误:
ValueError: The two structures don't have the same number of elements.
First structure: Tensor("backward/Tile:0", shape=(100, 50), dtype=float32),
second structure:
(<tf.Tensor 'backward/bwd_states/while/GRUCell/add:0' shape=(100, 50) dtype=float32>,
<tf.Tensor 'backward/bwd_states/while/GRUCell/add:0' shape=(100, 50) dtype=float32>).
Run Code Online (Sandbox Code Playgroud)
有任何线索如何解决这个问题?
我正在尝试RNN的可变长度多变量序列分类问题.
我已经定义了以下函数来获取序列的输出(即,从序列的最终输入被馈送后RNN单元的输出)
def get_sequence_output(x_sequence, initial_hidden_state):
previous_hidden_state = initial_hidden_state
for x_single in x_sequence:
hidden_state = gru_unit(previous_hidden_state, x_single)
previous_hidden_state = hidden_state
final_hidden_state = hidden_state
return final_hidden_state
Run Code Online (Sandbox Code Playgroud)
这x_sequence是(?, ?, 10)第一个形状的张量?是批量大小和第二?用于序列长度,每个输入元素的长度为10. gru函数采用先前的隐藏状态和当前输入,并吐出下一个隐藏状态(标准门控循环单元).
我收到一个错误:'Tensor' object is not iterable.
如何以序列方式迭代Tensor(一次读取单个元素)?
我的目标是为gru序列中的每个输入应用函数并获得最终的隐藏状态.
python tensorflow recurrent-neural-network gated-recurrent-unit
是否有规范的方法来维持Tensorflow服务的有状态LSTM等?
直接使用Tensorflow API这很简单 - 但我不确定在将模型导出到Serving之后如何最好地在调用之间实现持久的LSTM状态.
有什么例子可以实现上述目标吗?回购中的样品非常基本.
有没有人能够在Tensorflow中混合前馈层和重复层?
例如:input-> conv-> GRU-> linear-> output
我可以想象一个人可以用前馈层定义他自己的单元格而没有可以使用MultiRNNCell函数堆叠的状态,如:
cell = tf.nn.rnn_cell.MultiRNNCell([conv_cell,GRU_cell,linear_cell])
这会让生活变得更轻松......
python tensorflow recurrent-neural-network gated-recurrent-unit
我有一个具有以下结构的神经网络:
class myNetwork(nn.Module):
def __init__(self):
super(myNetwork, self).__init__()
self.bigru = nn.GRU(input_size=2, hidden_size=100, batch_first=True, bidirectional=True)
self.fc1 = nn.Linear(200, 32)
torch.nn.init.xavier_uniform_(self.fc1.weight)
self.fc2 = nn.Linear(32, 2)
torch.nn.init.xavier_uniform_(self.fc2.weight)
Run Code Online (Sandbox Code Playgroud)
我需要通过重置神经网络的参数来将模型恢复到未学习的状态。nn.Linear我可以使用以下方法对图层执行此操作:
def reset_weights(self):
torch.nn.init.xavier_uniform_(self.fc1.weight)
torch.nn.init.xavier_uniform_(self.fc2.weight)
Run Code Online (Sandbox Code Playgroud)
但是,要重置图层的权重nn.GRU,我找不到任何此类片段。
我的问题是如何重置图层nn.GRU?重置网络的任何其他方法也可以。任何帮助表示赞赏。
我使用以下循环创建了一个堆叠的 keras 解码器模型:
# Create the encoder
# Define an input sequence.
encoder_inputs = keras.layers.Input(shape=(None, num_input_features))
# Create a list of RNN Cells, these are then concatenated into a single layer with the RNN layer.
encoder_cells = []
for hidden_neurons in hparams['encoder_hidden_layers']:
encoder_cells.append(keras.layers.GRUCell(hidden_neurons,
kernel_regularizer=regulariser,
recurrent_regularizer=regulariser,
bias_regularizer=regulariser))
encoder = keras.layers.RNN(encoder_cells, return_state=True)
encoder_outputs_and_states = encoder(encoder_inputs)
# Discard encoder outputs and only keep the states. The outputs are of no interest to us, the encoder's job is to create
# a state describing …Run Code Online (Sandbox Code Playgroud) python keras tensorflow recurrent-neural-network gated-recurrent-unit
为什么GRU层的参数个数是9600?
不应该是 ((16+32)*32 + 32) * 3 * 2 = 9,408 吗?
或者,重新排列,
32*(16 + 32 + 1)*3*2 = 9408
model = tf.keras.Sequential([
tf.keras.layers.Embedding(input_dim=4500, output_dim=16, input_length=200),
tf.keras.layers.Bidirectional(tf.keras.layers.GRU(32)),
tf.keras.layers.Dense(6, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
model.summary()
Run Code Online (Sandbox Code Playgroud)
下面的Tensorflow GRUCell单元代码显示了获取更新隐藏状态的典型操作,当前一个隐藏状态与序列中的当前输入一起提供时.
def __call__(self, inputs, state, scope=None):
"""Gated recurrent unit (GRU) with nunits cells."""
with vs.variable_scope(scope or type(self).__name__): # "GRUCell"
with vs.variable_scope("Gates"): # Reset gate and update gate.
# We start with bias of 1.0 to not reset and not update.
r, u = array_ops.split(1, 2, _linear([inputs, state],
2 * self._num_units, True, 1.0))
r, u = sigmoid(r), sigmoid(u)
with vs.variable_scope("Candidate"):
c = self._activation(_linear([inputs, r * state],
self._num_units, True))
new_h = u * state + (1 - u) * c …Run Code Online (Sandbox Code Playgroud) neural-network tensorflow recurrent-neural-network gated-recurrent-unit
我植入了 Keras 站点上的十分钟 LSTM 示例,并调整了网络以处理单词嵌入而不是字符嵌入(来自https://blog.keras.io/a-ten-month-introduction-to-sequence-to-序列学习in-keras.html)。效果很好。
但现在我很难使用 GRU 而不是 LSTM。调整变量后,编译和训练(拟合函数)起作用了。但是当我尝试使用网络通过自定义输入对其进行测试时,它会抛出:
尺寸必须相等,但“add”(操作:“Add”)的尺寸为 232 和 256,输入形状为:[1,?,?,232]、[?,256]
LSTM的相关工作代码为:
encoder_inputs = Input(shape=(None, num_encoder_tokens), name="Encoder_Input")
encoder = LSTM(latent_dim, return_state=True, name="Encoder_LSTM")
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
encoder_states = [state_h, state_c]
decoder_inputs = Input(shape=(None, num_decoder_tokens), name="Decoder_Input")
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True, name="Decoder_LSTM")
decoder_outputs, _, _ = decoder_lstm(decoder_inputs,
initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax', name="DecoderOutput")
decoder_outputs = decoder_dense(decoder_outputs)
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
result = model.fit([encoder_input_data, decoder_input_data], decoder_target_data,
batch_size=batch_size,
epochs=epochs,
validation_split=0.2)
encoder_model = Model(encoder_inputs, …Run Code Online (Sandbox Code Playgroud) 这是我正在查看的API,https://pytorch.org/docs/stable/nn.html#gru
它输出:
output 形状(seq_len,批处理,num_directions * hidden_size)h_n 形状(num_layers * num_directions,批处理,hidden_size)对于具有多个层的GRU,我想知道如何获取最后一层的隐藏状态,应该是h_n[0]还是h_n[-1]?
如果是双向的,该如何切片以获取两个方向上GRU的最后一个隐藏层状态?
deep-learning recurrent-neural-network gated-recurrent-unit pytorch tensor