- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
问题陈述
我正在尝试在 Linux RedHat 7.3 上的 TensorFlow v1.0.1 中训练动态 RNN(问题也出现在 Windows 7 上),无论我尝试什么,我在每个时期都会得到完全相同的训练和验证错误,即我的权重是不更新。
感谢您提供的任何帮助。
例子
我试图将其减少到显示我的问题的最小示例,但最小示例仍然很大。我的网络结构主要基于this gist .
网络定义
import functools
import numpy as np
import tensorflow as tf
def lazy_property(function):
attribute = '_' + function.__name__
@property
@functools.wraps(function)
def wrapper(self):
if not hasattr(self, attribute):
setattr(self, attribute, function(self))
return getattr(self, attribute)
return wrapper
class MyNetwork:
"""
Class defining an RNN for labeling a time series.
"""
def __init__(self, data, target, num_hidden=64):
self.data = data
self.target = target
self._num_hidden = num_hidden
self._num_steps = int(self.target.get_shape()[1])
self._num_classes = int(self.target.get_shape()[2])
self._weight_and_bias() # create weight and bias tensors
self.prediction
self.error
self.optimize
@lazy_property
def prediction(self):
"""Defines the recurrent neural network prediction scheme."""
# Dynamic LSTM.
network = tf.contrib.rnn.BasicLSTMCell(self._num_hidden)
output, _ = tf.nn.dynamic_rnn(network, data, dtype=tf.float32)
# Flatten and apply same weights to all time steps.
output = tf.reshape(output, [-1, self._num_hidden])
prediction = tf.nn.softmax(tf.matmul(output, self.weight) + self.bias)
prediction = tf.reshape(prediction,
[-1, self._num_steps, self._num_classes])
return prediction
@lazy_property
def cost(self):
"""Defines the cost function for the network."""
cross_entropy = -tf.reduce_sum(self.target * tf.log(self.prediction),
axis=[1, 2])
cross_entropy = tf.reduce_mean(cross_entropy)
return cross_entropy
@lazy_property
def optimize(self):
"""Defines the optimization scheme."""
learning_rate = 0.003
optimizer = tf.train.RMSPropOptimizer(learning_rate)
return optimizer.minimize(self.cost)
@lazy_property
def error(self):
"""Defines a measure of prediction error."""
mistakes = tf.not_equal(tf.argmax(self.target, 2),
tf.argmax(self.prediction, 2))
return tf.reduce_mean(tf.cast(mistakes, tf.float32))
def _weight_and_bias(self):
"""Returns appropriately sized weight and bias tensors for the output layer."""
self.weight = tf.Variable(tf.truncated_normal(
[self._num_hidden, self._num_classes],
mean=0.0,
stddev=0.01,
dtype=tf.float32))
self.bias = tf.Variable(tf.constant(0.1, shape=[self._num_classes]))
all_data
类只保存我的数据和标签,并在我调用
all_data.train.next()
时使用批处理生成器类吐出用于训练的批处理和
all_data.train_labels.next()
.您可以使用任何您喜欢的批量生成方案进行重现,如果您认为相关,我可以添加代码;我觉得这太长了。
tf.reset_default_graph()
data = tf.placeholder(tf.float32,
[None, all_data.num_steps, all_data.num_features])
target = tf.placeholder(tf.float32,
[None, all_data.num_steps, all_data.num_outputs])
model = MyNetwork(data, target, NUM_HIDDEN)
print('Training the model...')
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print('Initialized.')
for epoch in range(3):
print('Epoch {} |'.format(epoch), end='', flush=True)
for step in range(all_data.train_size // BATCH_SIZE):
# Generate the next training batch and train.
d = all_data.train.next()
t = all_data.train_labels.next()
sess.run(model.optimize,
feed_dict={data: d, target: t})
# Update the user periodically.
if step % summary_frequency == 0:
print('.', end='', flush=True)
# Show training and validation error at the end of each epoch.
print('|', flush=True)
train_error = sess.run(model.error,
feed_dict={data: d, target: t})
valid_error = sess.run(model.error,
feed_dict={
data: all_data.valid,
target: all_data.valid_labels
})
print('Training error: {}%'.format(100 * train_error))
print('Validation error: {}%'.format(100 * valid_error))
# Check testing error after everything.
test_error = sess.run(model.error,
feed_dict={
data: all_data.test,
target: all_data.test_labels
})
print('Testing error after {} epochs: {}%'.format(epoch + 1, 100 * test_error))
[num_samples, num_steps, num_features]
,并且每个样本都有一个与整个事物相关联的标签:
data = np.random.rand(5000, 1000, 2)
labels = np.random.randint(low=0, high=2, size=[5000])
labels
张量与
data
的大小相同张量。
Training the model...
Initialized.
Epoch 0 |.......................................................|
Training error: 56.25%
Validation error: 53.39999794960022%
Epoch 1 |.......................................................|
Training error: 56.25%
Validation error: 53.39999794960022%
Epoch 2 |.......................................................|
Training error: 56.25%
Validation error: 53.39999794960022%
Testing error after 3 epochs: 49.000000953674316%
None
的成本函数梯度.当我尝试使用不同的优化器并尝试裁剪渐变时,我继续使用
tf.Print
也可以输出梯度。网络崩溃,错误为
tf.Print
无法处理无类型值。
stddev
的不同值初始化我的权重. tf.zeros
)和不同的常数。 prediction
中定义的权重和偏差方法并且不是类的成员变量,并且是 _weight_and_bias
定义为 @staticmethod
的方法喜欢 this gist . prediction
中的 logits函数而不是 softmax 预测,即 predictions = tf.matmul(output, self.weights) + self.bias
,然后使用 tf.nn.softmax_cross_entropy_with_logits
.这需要一些 reshape ,因为该方法希望其标签和目标以形状 [batch_size, num_classes]
给出。 ,所以 cost
方法变为:@lazy_property
def cost(self):
"""Defines the cost function for the network."""
targs = tf.reshape(self.target, [-1, self._num_classes])
logits = tf.reshape(self.predictions, [-1, self._num_classes])
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=targs, logits=logits)
cross_entropy = tf.reduce_mean(cross_entropy)
return cross_entropy
None
当我按照 this answer 中的建议创建占位符时,这需要在网络定义中进行一些重写。基本设置size = [all_data.batch_size, -1, all_data.num_features]
和 size = [all_data.batch_size, -1, all_data.num_classes]
. tf.contrib.rnn.DropoutWrapper
在我的网络定义中并通过 dropout
在训练中设置为 0.5,在验证和测试中设置为 1.0。 最佳答案
当我使用时问题就消失了
output = tf.contrib.layers.flatten(output)
logits = tf.contrib.layers.fully_connected(output, some_size, activation_fn=None)
tf.matmul(output, weight) + bias
手动。然后我使用了
logits
(而不是问题中的
predictions
)在我的成本函数中
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=target,
logits=logits)
prediction = tf.nn.softmax(logits)
.
关于python - TensorFlow 动态 RNN 未训练,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43548738/
我使用 tensorflow 实现了一个简单的 RNN 模型来学习时间序列数据的可能趋势并预测 future 值。然而,该模型总是在训练后产生相同的值。实际上,它得到的最佳模型是: y = b. RN
我正在关注this tutorial关于循环神经网络。 这是导入: import tensorflow as tf from tensorflow.examples.tutorials.mnist i
一段时间以来,我一直在苦思冥想,无法弄清楚我在实现这些 RNN 时做错了什么(如果有的话)。为了让你们省去前向阶段,我可以告诉你们这两个实现计算相同的输出,所以前向阶段是正确的。问题出在倒退阶段。 这
我正在用 RNN 练习。我随机创建 5 个整数。如果第一个整数是奇数,则 y 值为 1,否则 y 为 0(因此,只有第一个 x 有效)。问题是,当我运行这个模型时,它不会“学习”:val_loss 和
我正在使用 bidirectional_rnn与 GRUCell但这是一个关于 Tensorflow 中 RNN 的普遍问题。 我找不到如何初始化权重矩阵(输入到隐藏,隐藏到隐藏)。它们是随机初始化的
我正在尝试找出适应开放命名实体识别问题的最佳模型(生物学/化学,因此不存在实体字典,但必须通过上下文来识别它们)。 目前我最好的猜测是调整 Syntaxnet,这样它就不会将单词标记为 N、V、ADJ
我正在通过以下方式训练 RNN: def create_rnn_model(stateful,length): model = Sequential() model.add(Simpl
我对 PyTorch 非常陌生,而且对一般神经网络也相当陌生。 我试图构建一个可以猜测性别名字的神经网络,并且基于判断国籍的 PyTorch RNN 教程。 我的代码运行没有错误,但损失几乎没有变化,
我正在尝试训练一个模型,返回单词序列(RNN)的类。 我为我的模型提供一系列嵌入: [ batchSize, sequence_length, word_embedding ] as float[]
我正在尝试预测输入向量中每个数字的类别。有3个类(class)。如果输入值从 0 变为 1,则为 1 类。如果从 1 变为 0,则为 2 类。否则为 0 类。 在第二个纪元之后,精度停留在 0.882
我正在尝试为我的日志分析项目开发一个顺序 RNN。 输入是一个日志序列,例如 [1,2,3,4,5,6,1,5,2,7,8,2,1] 目前我正在使用 keras 库中的 to_categorical
为了加深我对 RNN 和 LSTM 的理解,我正在尝试实现一个简单的 LSTM 来估计正弦波的频率和相位。事实证明,这出奇地难以收敛。 MSE 相当高(以千为单位)唯一似乎有点工作的是,如果我生成所有
请帮助我编写以下代码,当我尝试直接在数据上拟合模型时,该代码运行良好,但在网格搜索上失败(我已注释掉直接 model.fit()我的 grid.fit() 语句末尾的部分,这给了我满意的结果。还请告诉
前提1: 关于 RNN 层中的神经元 - 我的理解是,在“每个时间步,每个神经元都接收输入向量 x (t) 和前一个时间步的输出向量 y (t –1)”[1]: 前提2: 据我了解,在 Pytorch
我想训练一个 RNN 来解决一个简单的回归问题。我有一个形状为 (35584,) 的数组 X_train,它表示几年来每小时的测量值。我还有相应的 Y_train 形状为 (35584,) 作为预期值
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 4 年前。 Improve this qu
pytorch实现变长输入的rnn分类 输入数据是长度不固定的序列数据,主要讲解两个部分 1、Data.DataLoader的collate_fn用法,以及按batch进行padding数据
基于循环神经网络(RNN)的古诗生成器,具体内容如下 之前在手机百度上看到有个“为你写诗”功能,能够随机生成古诗,当时感觉很酷炫= = 在学习了深度学习后,了解了一下原理,打算自己做个实现练练手
使用循环神经网络(RNN)实现影评情感分类 作为对循环神经网络的实践,我用循环神经网络做了个影评情感的分类,即判断影评的感情色彩是正面的,还是负面的。 选择使用RNN来做情感分类,主要是因为影评
我的目标是在 Keras/TensorFlow 中构建一个 RNN,它由循环单元层(GRU、LSTM 等)以及从网络底部到顶部的循环组成,以添加注意力机制或特殊的内存类型。我不熟悉符号循环,所以首先我
我是一名优秀的程序员,十分优秀!