我正在尝试实现基于LSTM的语音识别器.到目前为止,我可以通过遵循Merge层中的示例来设置双向LSTM(我认为它可以作为双向LSTM).现在我想用另一个双向LSTM层来尝试它,这使它成为一个深度双向LSTM.但我无法弄清楚如何将先前合并的两层的输出连接到第二组LSTM层.我不知道Keras是否有可能.希望有人可以帮助我.
我的单层双向LSTM的代码如下
left = Sequential()
left.add(LSTM(output_dim=hidden_units, init='uniform', inner_init='uniform',
forget_bias_init='one', return_sequences=True, activation='tanh',
inner_activation='sigmoid', input_shape=(99, 13)))
right = Sequential()
right.add(LSTM(output_dim=hidden_units, init='uniform', inner_init='uniform',
forget_bias_init='one', return_sequences=True, activation='tanh',
inner_activation='sigmoid', input_shape=(99, 13), go_backwards=True))
model = Sequential()
model.add(Merge([left, right], mode='sum'))
model.add(TimeDistributedDense(nb_classes))
model.add(Activation('softmax'))
sgd = SGD(lr=0.1, decay=1e-5, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd)
print("Train...")
model.fit([X_train, X_train], Y_train, batch_size=1, nb_epoch=nb_epoches, validation_data=([X_test, X_test], Y_test), verbose=1, show_accuracy=True)
Run Code Online (Sandbox Code Playgroud)
我的x和y值的尺寸如下.
(100, 'train sequences')
(20, 'test sequences')
('X_train shape:', (100, 99, 13))
('X_test shape:', (20, 99, 13))
('y_train shape:', (100, 99, 11))
('y_test shape:', (20, 99, …Run Code Online (Sandbox Code Playgroud) 我对神经网络比较陌生,所以请原谅我的无知.我正在尝试在这里调整keras BLSTM示例.这个例子中的文本读取和0或1.我想BLSTM,做的东西非常像词性标注,虽然喜欢lemmatizing或其他高级功能演员都没有neccessary它们分类,我只想要一个基本模型.我的数据是一个句子列表,每个单词都有一个1-8类.我想训练一个BLSTM,它可以使用这些数据来预测一个看不见的句子中每个单词的类别.
例如input = ['The','dog','is','red']给出输出= [2,4,3,7]
如果keras示例不是最佳路线,我会接受其他建议.
我目前有这个:
'''Train a Bidirectional LSTM.'''
from __future__ import print_function
import numpy as np
from keras.preprocessing import sequence
from keras.models import Model
from keras.layers import Dense, Dropout, Embedding, LSTM, Input, merge
from prep_nn import prep_scan
np.random.seed(1337) # for reproducibility
max_features = 20000
batch_size = 16
maxlen = 18
print('Loading data...')
(X_train, y_train), (X_test, y_test) = prep_scan(nb_words=max_features,
test_split=0.2)
print(len(X_train), 'train sequences')
print(len(X_test), 'test sequences')
print("Pad sequences (samples x time)")
# type issues here? …Run Code Online (Sandbox Code Playgroud) 我在Keras中有以下代码(基本上我正在修改此代码以供我使用)并且我收到此错误:
'ValueError:检查目标时出错:预期conv3d_3有5个维度,但得到的数组有形状(10,4096)'
码:
from keras.models import Sequential
from keras.layers.convolutional import Conv3D
from keras.layers.convolutional_recurrent import ConvLSTM2D
from keras.layers.normalization import BatchNormalization
import numpy as np
import pylab as plt
from keras import layers
# We create a layer which take as input movies of shape
# (n_frames, width, height, channels) and returns a movie
# of identical shape.
model = Sequential()
model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
input_shape=(None, 64, 64, 1),
padding='same', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
padding='same', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
padding='same', return_sequences=True)) …Run Code Online (Sandbox Code Playgroud) 我正在尝试用pytorch中的手动定义参数填充GRU/LSTM.
我有numpy数组用于参数的形状,如文档中所定义(https://pytorch.org/docs/stable/nn.html#torch.nn.GRU).
它似乎工作,但我不确定返回的值是否正确.
这是用numpy参数填充GRU/LSTM的正确方法吗?
gru = nn.GRU(input_size, hidden_size, num_layers,
bias=True, batch_first=False, dropout=dropout, bidirectional=bidirectional)
def set_nn_wih(layer, parameter_name, w, l0=True):
param = getattr(layer, parameter_name)
if l0:
for i in range(3*hidden_size):
param.data[i] = w[i*input_size:(i+1)*input_size]
else:
for i in range(3*hidden_size):
param.data[i] = w[i*num_directions*hidden_size:(i+1)*num_directions*hidden_size]
def set_nn_whh(layer, parameter_name, w):
param = getattr(layer, parameter_name)
for i in range(3*hidden_size):
param.data[i] = w[i*hidden_size:(i+1)*hidden_size]
l0=True
for i in range(num_directions):
for j in range(num_layers):
if j == 0:
wih = w0[i, :, :3*input_size]
whh = w0[i, :, 3*input_size:] # …Run Code Online (Sandbox Code Playgroud) 我是LSTM的新手,经历了理解Keras LSTM,并对Daniel Moller的漂亮答案产生了一些愚蠢的怀疑.
以下是我的一些疑问:
在Achieving one to many 编写的部分下指定了两种方法 ,我们可以使用stateful=True 这些方法循环地获取一步的输出并将其作为下一步的输入(需要output_features == input_features).
在该One to many with repeat vector图中,重复矢量在所有时间步长中One to many with stateful=True作为输入馈送,而在输出中在下一个时间步骤中作为输入馈送.那么,我们不是通过使用stateful=True?来改变图层的工作方式吗?
在构建RNN时,应遵循以上哪两种方法(使用重复向量或将前一时间步输出作为下一个输入)?
在该One to many with stateful=True部分下,为了改变one to many预测手动循环代码中的行为,我们将如何知道steps_to_predict变量,因为我们事先并不知道输出序列长度.
我也不明白整个模型使用last_step output生成方式的方式next_step ouput.它使我对model.predict()功能的工作感到困惑.我的意思是,不是model.predict()同时预测整个输出序列而不是循环通过no. of output sequences(我仍然不知道它的值)生成并做model.predict()预测给定迭代中的特定时间步输出?
我无法理解整个Many to many案例.任何其他链接都会有所帮助.
我知道我们model.reset_states()用来确保新批次独立于前一批次.但是,我们是否手动创建批次序列,以便一个批次跟随另一个批次,或者Keras在stateful=True …
我正在尝试使用tensorflow LSTM模型来进行下一个单词预测.
如此相关问题(没有接受的答案)中所述,该示例包含伪代码以提取下一个单词概率:
lstm = rnn_cell.BasicLSTMCell(lstm_size)
# Initial state of the LSTM memory.
state = tf.zeros([batch_size, lstm.state_size])
loss = 0.0
for current_batch_of_words in words_in_dataset:
# The value of state is updated after processing each batch of words.
output, state = lstm(current_batch_of_words, state)
# The LSTM output can be used to make next word predictions
logits = tf.matmul(output, softmax_w) + softmax_b
probabilities = tf.nn.softmax(logits)
loss += loss_function(probabilities, target_words)
Run Code Online (Sandbox Code Playgroud)
我对如何解释概率向量感到困惑.我修改__init__的功能PTBModel在ptb_word_lm.py存储概率和logits:
class PTBModel(object):
"""The …Run Code Online (Sandbox Code Playgroud) 我在Tensorflow模型中使用存储桶时遇到问题.当我运行它时buckets = [(100, 100)],它工作正常.当我用buckets = [(100, 100), (200, 200)]它运行它根本不起作用(底部的堆栈跟踪).
有趣的是,运行Tensorflow的Seq2Seq教程会产生相同类型的问题,几乎相同的堆栈跟踪.出于测试目的,此处链接到存储库.
我不确定问题是什么,但是有多个桶总是会触发它.
这段代码不能单独运行,但这是崩溃的功能 - 记住buckets从更改[(100, 100)]到[(100, 100), (200, 200)]触发崩溃.
class MySeq2Seq(object):
def __init__(self, source_vocab_size, target_vocab_size, buckets, size, num_layers, batch_size, learning_rate):
self.source_vocab_size = source_vocab_size
self.target_vocab_size = target_vocab_size
self.buckets = buckets
self.batch_size = batch_size
cell = single_cell = tf.nn.rnn_cell.GRUCell(size)
if num_layers > 1:
cell = tf.nn.rnn_cell.MultiRNNCell([single_cell] * num_layers)
# The seq2seq function: we use embedding for the input and attention
def …Run Code Online (Sandbox Code Playgroud) 我知道这是一个有很多问题的主题,但我找不到任何问题的解决方案.
我正在使用屏蔽层训练可变长度输入的LSTM网络,但它似乎没有任何影响.
输入形状(100,362,24),其中362是最大序列长度,24是特征数量,100是样本数量(划分75列火车/ 25有效).
输出形状(100,362,1)稍后变换为(100,362-N,1).
这是我的网络代码:
from keras import Sequential
from keras.layers import Embedding, Masking, LSTM, Lambda
import keras.backend as K
# O O O
# example for N:3 | | |
# O O O O O O
# | | | | | |
# O O O O O O
N = 5
y= y[:,N:,:]
x_train = x[:75]
x_test = x[75:]
y_train = y[:75]
y_test = y[75:]
model = Sequential()
model.add(Masking(mask_value=0., input_shape=(timesteps, features)))
model.add(LSTM(128, return_sequences=True))
model.add(LSTM(64, return_sequences=True)) …Run Code Online (Sandbox Code Playgroud) 我在Pytorch中使用Sequence to Sequence模型.序列到序列模型包括编码器和解码器.
编码器转换a (batch_size X input_features X num_of_one_hot_encoded_classes) -> (batch_size X input_features X hidden_size)
解码器将采用此输入序列并将其转换为 (batch_size X output_features X num_of_one_hot_encoded_classes)
一个例子是 -
所以在上面的例子中,我需要将22个输入功能转换为10个输出功能.在Keras中,可以使用RepeatVector(10)完成.
一个例子 -
model.add(LSTM(256, input_shape=(22, 98)))
model.add(RepeatVector(10))
model.add(Dropout(0.3))
model.add(LSTM(256, return_sequences=True))
Run Code Online (Sandbox Code Playgroud)
虽然,我不确定它是否是将输入序列转换为输出序列的正确方法.
所以,我的问题是 -
编码器代码片段(用Pytorch编写) -
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size):
super(EncoderRNN, self).__init__()
self.hidden_size = hidden_size
self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size,
num_layers=1, batch_first=True)
def forward(self, input):
output, hidden = self.lstm(input)
return output, hidden
Run Code Online (Sandbox Code Playgroud) 自编码器欠拟合时间序列重建,仅预测平均值。
这是我对序列到序列自动编码器的尝试的总结。该图片取自本文:https : //arxiv.org/pdf/1607.00148.pdf

编码器:标准 LSTM 层。输入序列在最终隐藏状态中编码。
解码器: LSTM Cell(我想!)。从最后一个元素开始,一次一个元素地重建序列x[N]。
对于长度为 的序列,解码器算法如下N:
hs[N]:只需使用编码器最终隐藏状态。x[N]= w.dot(hs[N]) + b。x[i]= w.dot(hs[i]) + bx[i]和hs[i]作为输入LSTMCell来获取x[i-1]和hs[i-1]这是我的实现,从编码器开始:
class SeqEncoderLSTM(nn.Module):
def __init__(self, n_features, latent_size):
super(SeqEncoderLSTM, self).__init__()
self.lstm = nn.LSTM(
n_features,
latent_size,
batch_first=True)
def forward(self, x):
_, hs = self.lstm(x)
return hs
Run Code Online (Sandbox Code Playgroud)
解码器类:
class SeqDecoderLSTM(nn.Module):
def __init__(self, emb_size, n_features):
super(SeqDecoderLSTM, self).__init__()
self.cell = …Run Code Online (Sandbox Code Playgroud) lstm ×10
keras ×6
python ×6
pytorch ×3
tensorflow ×2
autoencoder ×1
masking ×1
nlp ×1
python-3.x ×1
rnn ×1
seq2seq ×1