由于LSTM RNN使用先前的事件来预测当前序列,为什么我们将训练数据混洗?我们不会失去训练数据的时间顺序吗?在对改组后的训练数据进行训练后,如何进行预测仍然有效?
在这篇博文中,回顾性神经网络的不合理有效性,Andrej Karpathy提到了基于神经网络的机器学习的未来发展方向:
关注的概念是神经网络中最有趣的近期架构创新.[...]用于内存寻址的软注意方案很方便,因为它使模型保持完全可微分,但不幸的是,牺牲了效率,因为可以注意到的所有事情(但是轻柔地).可以认为这是在C中声明一个指针,它不指向特定的地址,而是在整个内存中的所有地址上定义一个完整的分布,并且取消引用指针返回指向内容的加权和(这将是一个昂贵的操作!).这促使多位作者交换软注意力模型以获得难以注意的情况,其中一个人对特定的一块存储器进行采样(例如,某些存储器单元的读/写动作,而不是在某种程度上从所有单元读取/写入).这种模式在哲学上更具吸引力,可扩展性和高效性,但不幸的是它也是不可微分的.
我认为我理解了指针的隐喻,但究竟是什么才是注意力,为什么难以辨别?
我在这里找到了关于注意力的解释,但仍然对软/硬部分感到困惑.
给定训练有素的LSTM模型,我想对单个时间步进行推理,即seq_length = 1在下面的示例中.在每个时间步之后,需要记住内部LSTM(内存和隐藏)状态以用于下一个"批处理".在推理的最开始,init_c, init_h给定输入计算内部LSTM状态.然后将它们存储在LSTMStateTuple传递给LSTM 的对象中.在训练期间,每个时间步都更新此状态.然而,对于推理,我希望state在批次之间保存,即初始状态只需要在开始时计算,然后在每个"批次"(n = 1)之后保存LSTM状态.
我发现这个相关的StackOverflow问题:Tensorflow,在RNN中保存状态的最佳方法?.但是,这仅在以下情况下有效state_is_tuple=False,但TensorFlow很快就会弃用此行为(请参阅rnn_cell.py).Keras似乎有一个很好的包装器可以使有状态的 LSTM成为可能,但我不知道在TensorFlow中实现这一目标的最佳方法.TensorFlow GitHub上的这个问题也与我的问题有关:https://github.com/tensorflow/tensorflow/issues/2838
有关构建有状态LSTM模型的任何好建议吗?
inputs = tf.placeholder(tf.float32, shape=[None, seq_length, 84, 84], name="inputs")
targets = tf.placeholder(tf.float32, shape=[None, seq_length], name="targets")
num_lstm_layers = 2
with tf.variable_scope("LSTM") as scope:
lstm_cell = tf.nn.rnn_cell.LSTMCell(512, initializer=initializer, state_is_tuple=True)
self.lstm = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * num_lstm_layers, state_is_tuple=True)
init_c = # compute initial LSTM memory state using contents in placeholder 'inputs'
init_h = # compute initial LSTM …Run Code Online (Sandbox Code Playgroud) 我正在使用张量流中的双向动态RNN进行文本标记.在加工输入维度后,我尝试运行一个Session.这是blstm设置部分:
fw_lstm_cell = BasicLSTMCell(LSTM_DIMS)
bw_lstm_cell = BasicLSTMCell(LSTM_DIMS)
(fw_outputs, bw_outputs), _ = bidirectional_dynamic_rnn(fw_lstm_cell,
bw_lstm_cell,
x_place,
sequence_length=SEQLEN,
dtype='float32')
Run Code Online (Sandbox Code Playgroud)
这是运行部分:
with tf.Graph().as_default():
# Placehoder Settings
x_place, y_place = set_placeholder(BATCH_SIZE, EM_DIMS, MAXLEN)
# BLSTM Model Building
hlogits = tf_kcpt.build_blstm(x_place)
# Compute loss
loss = tf_kcpt.get_loss(log_likelihood)
# Training
train_op = tf_kcpt.training(loss)
# load Eval method
eval_correct = tf_kcpt.evaluation(logits, y_place)
# Session Setting & Init
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
# tensor summary setting
summary = tf.summary.merge_all()
summary_writer = tf.summary.FileWriter(LOG_DIR, sess.graph)
# Save
saver …Run Code Online (Sandbox Code Playgroud) python bidirectional deep-learning tensorflow recurrent-neural-network
我试图使用RNN(特别是LSTM)进行序列预测.但是,我遇到了可变序列长度的问题.例如,
sent_1 = "I am flying to Dubain"
sent_2 = "I was traveling from US to Dubai"
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用基于此Benchmark的简单RNN来预测当前的下一个词,以构建PTB LSTM模型.
但是,num_steps参数(用于展开到先前的隐藏状态)应该在每个Tensorflow的纪元中保持相同.基本上,由于句子的长度不同,因此无法批量处理句子.
# inputs = [tf.squeeze(input_, [1])
# for input_ in tf.split(1, num_steps, inputs)]
# outputs, states = rnn.rnn(cell, inputs, initial_state=self._initial_state)
Run Code Online (Sandbox Code Playgroud)
在这里,num_steps每个句子都需要改变我的情况.我尝试了几次黑客攻击,但似乎没有任何效果.
我正在构建一个模型,使用循环图层(GRU)将字符串转换为另一个字符串.我已经尝试了Dense和TimeDistributed(密集)层作为最后一层,但我不明白使用return_sequences = True时两者之间的区别,特别是因为它们似乎具有相同数量的参数.
我的简化模型如下:
InputSize = 15
MaxLen = 64
HiddenSize = 16
inputs = keras.layers.Input(shape=(MaxLen, InputSize))
x = keras.layers.recurrent.GRU(HiddenSize, return_sequences=True)(inputs)
x = keras.layers.TimeDistributed(keras.layers.Dense(InputSize))(x)
predictions = keras.layers.Activation('softmax')(x)
Run Code Online (Sandbox Code Playgroud)
网络摘要是:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 64, 15) 0
_________________________________________________________________
gru_1 (GRU) (None, 64, 16) 1536
_________________________________________________________________
time_distributed_1 (TimeDist (None, 64, 15) 255
_________________________________________________________________
activation_1 (Activation) (None, 64, 15) 0
=================================================================
Run Code Online (Sandbox Code Playgroud)
这对我来说很有意义,因为我对TimeDistributed的理解是它在所有时间点都应用相同的层,因此Dense层有16*15 + 15 = 255个参数(权重+偏差).
但是,如果我切换到一个简单的Dense图层:
inputs = keras.layers.Input(shape=(MaxLen, InputSize))
x = keras.layers.recurrent.GRU(HiddenSize, return_sequences=True)(inputs)
x = …Run Code Online (Sandbox Code Playgroud) machine-learning neural-network keras recurrent-neural-network keras-layer
我的输入只是一个包含339732行和两列的csv文件:
我正在尝试在堆叠的LSTM模型上训练我的数据:
data_dim = 29
timesteps = 8
num_classes = 2
model = Sequential()
model.add(LSTM(30, return_sequences=True,
input_shape=(timesteps, data_dim))) # returns a sequence of vectors of dimension 30
model.add(LSTM(30, return_sequences=True)) # returns a sequence of vectors of dimension 30
model.add(LSTM(30)) # return a single vector of dimension 30
model.add(Dense(1, activation='softmax'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.summary()
model.fit(X_train, y_train, batch_size = 400, epochs = 20, verbose = 1)
Run Code Online (Sandbox Code Playgroud)
这会引发错误:
回溯(最近一次调用最后一次):文件"first_approach.py",第80行,在model.fit中(X_train,y_train,batch_size = 400,epochs = 20,verbose = 1)
ValueError:检查模型输入时出错:预期lstm_1_input有3个维度,但是有形状的数组(339732,29)
我尝试使用重塑我的输入,X_train.reshape((1,339732, 29))但它没有显示错误:
ValueError:检查模型输入时出错:期望lstm_1_input具有形状(无,8,29)但是具有形状的数组(1,339732,29) …
我正在尝试使用具有不同时间长度的序列在Keras中安装RNN.我的数据是在一个numpy的阵列格式(sample, time, feature) = (20631, max_time, 24),其中max_time在运行时被确定为可用于与最时间戳采样时间的步数.我已经填写了每个时间序列的开头0,除了最长的一个,显然.
我最初定义了我的模型......
model = Sequential()
model.add(Masking(mask_value=0., input_shape=(max_time, 24)))
model.add(LSTM(100, input_dim=24))
model.add(Dense(2))
model.add(Activation(activate))
model.compile(loss=weibull_loglik_discrete, optimizer=RMSprop(lr=.01))
model.fit(train_x, train_y, nb_epoch=100, batch_size=1000, verbose=2, validation_data=(test_x, test_y))
Run Code Online (Sandbox Code Playgroud)
为了完整性,这里是损失函数的代码:
def weibull_loglik_discrete(y_true, ab_pred, name=None):
y_ = y_true[:, 0]
u_ = y_true[:, 1]
a_ = ab_pred[:, 0]
b_ = ab_pred[:, 1]
hazard0 = k.pow((y_ + 1e-35) / a_, b_)
hazard1 = k.pow((y_ + 1) / a_, b_)
return -1 * k.mean(u_ * k.log(k.exp(hazard1 - hazard0) - 1.0) …Run Code Online (Sandbox Code Playgroud) 我正在基于TensorFlow教程松散地构建RNN .
我模型的相关部分如下:
input_sequence = tf.placeholder(tf.float32, [BATCH_SIZE, TIME_STEPS, PIXEL_COUNT + AUX_INPUTS])
output_actual = tf.placeholder(tf.float32, [BATCH_SIZE, OUTPUT_SIZE])
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(CELL_SIZE, state_is_tuple=False)
stacked_lstm = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * CELL_LAYERS, state_is_tuple=False)
initial_state = state = stacked_lstm.zero_state(BATCH_SIZE, tf.float32)
outputs = []
with tf.variable_scope("LSTM"):
for step in xrange(TIME_STEPS):
if step > 0:
tf.get_variable_scope().reuse_variables()
cell_output, state = stacked_lstm(input_sequence[:, step, :], state)
outputs.append(cell_output)
final_state = state
Run Code Online (Sandbox Code Playgroud)
和喂养:
cross_entropy = tf.reduce_mean(-tf.reduce_sum(output_actual * tf.log(prediction), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(output_actual, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with …Run Code Online (Sandbox Code Playgroud) python artificial-intelligence typeerror tensorflow recurrent-neural-network
我试图将一层的输出传递到两个不同的层,然后将它们连接在一起.但是,我被这个错误所阻止,这个错误告诉我输入不是符号张量.
Received type: <class 'keras.layers.recurrent.LSTM'>. All inputs to the layers should be tensors.
Run Code Online (Sandbox Code Playgroud)
但是,我相信我非常密切地关注文档:https: //keras.io/getting-started/functional-api-guide/#multi-input-and-multi-output-models
我不完全确定为什么这是错的?
net_input = Input(shape=(maxlen, len(chars)), name='net_input')
lstm_out = LSTM(128, input_shape=(maxlen, len(chars)))
book_out = Dense(len(books), activation='softmax', name='book_output')(lstm_out)
char_out = Dense(len(chars-4), activation='softmax', name='char_output')(lstm_out)
x = keras.layers.concatenate([book_out, char_out])
net_output = Dense(len(chars)+len(books), activation='sigmoid', name='net_output')
model = Model(inputs=[net_input], outputs=[net_output])
Run Code Online (Sandbox Code Playgroud)
谢谢
python ×7
keras ×5
lstm ×4
tensorflow ×4
keras-layer ×1
numpy ×1
stateful ×1
typeerror ×1
valueerror ×1