- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
所以我正在尝试训练一个简单的循环网络来检测输入信号中的“突发”。下图显示了 RNN 的输入信号(蓝色)和所需的(分类)输出,以红色显示。
因此,每当检测到突发时,网络的输出应该从 1 切换到 0,并保持与该输出相同。用于训练 RNN 的输入序列之间唯一发生变化的是爆发发生的时间步长。
遵循 https://github.com/MorvanZhou/PyTorch-Tutorial/blob/master/tutorial-contents/403_RNN_regressor.py 上的教程,我无法让 RNN 学习。学习到的 RNN 始终以“无内存”方式运行,即不使用内存进行预测,如以下示例行为所示:
绿线显示网络的预测输出。 我在这个例子中做错了什么导致无法正确学习网络?网络任务是不是很简单?
我正在使用:
该实验已用不同的随机种子重复了几次,但结果几乎没有差异。我使用了以下代码:
import torch
import numpy, math
import matplotlib.pyplot as plt
nofSequences = 5
maxLength = 130
# Generate training data
x_np = numpy.zeros((nofSequences,maxLength,1))
y_np = numpy.zeros((nofSequences,maxLength))
numpy.random.seed(1)
for i in range(0,nofSequences):
startPos = numpy.random.random()*50
for j in range(0,maxLength):
if j>=startPos and j<startPos+10:
x_np[i,j,0] = math.sin((j-startPos)*math.pi/10)
else:
x_np[i,j,0] = 0.0
if j<startPos+10:
y_np[i,j] = 1
else:
y_np[i,j] = 0
# Define the neural network
INPUT_SIZE = 1
class RNN(torch.nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.rnn = torch.nn.RNN(
input_size=INPUT_SIZE,
hidden_size=16, # rnn hidden unit
num_layers=1, # number of rnn layer
batch_first=True,
)
self.out = torch.nn.Linear(16, 2)
def forward(self, x, h_state):
r_out, h_state = self.rnn(x, h_state)
outs = [] # save all predictions
for time_step in range(r_out.size(1)): # calculate output for each time step
outs.append(self.out(r_out[:, time_step, :]))
return torch.stack(outs, dim=1), h_state
# Learn the network
rnn = RNN()
optimizer = torch.optim.Adam(rnn.parameters(), lr=0.01)
h_state = None # for initial hidden state
x = torch.Tensor(x_np) # shape (batch, time_step, input_size)
y = torch.Tensor(y_np).long()
torch.manual_seed(2)
numpy.random.seed(2)
for step in range(100):
prediction, h_state = rnn(x, h_state) # rnn output
# !! next step is important !!
h_state = h_state.data # repack the hidden state, break the connection from last iteration
loss = torch.nn.CrossEntropyLoss()(prediction.reshape((-1,2)),torch.autograd.Variable(y.reshape((-1,)))) # calculate loss
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients
errTrain = (prediction.max(2)[1].data != y).float().mean()
print("Error Training:",errTrain.item())
对于那些想要重现实验的人,使用以下代码(使用 Jupyter Notebook)绘制绘图:
steps = range(0,maxLength)
plotChoice = 3
plt.figure(1, figsize=(12, 5))
plt.ion() # continuously plot
plt.plot(steps, y_np[plotChoice,:].flatten(), 'r-')
plt.plot(steps, numpy.argmax(prediction.detach().numpy()[plotChoice,:,:],axis=1), 'g-')
plt.plot(steps, x_np[plotChoice,:,0].flatten(), 'b-')
plt.ioff()
plt.show()
最佳答案
来自 tourch.nn.RNN 的文档,RNN实际上是一个Elman网络,并且有以下属性可见here .Elman网络的输出只依赖于隐藏状态,而隐藏状态依赖于最后一个输入和之前的隐藏状态。
由于我们设置了“h_state = h_state.data”,我们实际上是使用最后一个序列的隐藏状态来预测新序列的第一个状态,这将导致输出严重依赖于前一个序列的最后一个输出序列(为 0)。如果我们处于序列的开头或结尾,Elman 网络无法分离,它只能“看到”状态和最后的输入。
为了解决这个问题,我们可以设置“h_state = None”。现在每个新序列都以空状态开始。这导致以下预测(其中绿线再次显示预测)。 现在我们从 1 开始,但在脉冲再次将其推回之前迅速下降到 0。Elman 网络可以解释一些时间依赖性,但它不擅长记住长期依赖性,并且不善于为该输入收敛到“最常见的输出”。
因此,为了解决这个问题,我建议使用以处理长期依赖关系而闻名的网络,即长短期内存 (LSTM) rnn,有关更多信息,请参阅 torch.nn.LSTM .保留“h_state = None”并将 torch.nn.RNN 更改为 torch.nn.LSTM。
完整的代码和情节见下文
import torch
import numpy, math
import matplotlib.pyplot as plt
nofSequences = 5
maxLength = 130
# Generate training data
x_np = numpy.zeros((nofSequences,maxLength,1))
y_np = numpy.zeros((nofSequences,maxLength))
numpy.random.seed(1)
for i in range(0,nofSequences):
startPos = numpy.random.random()*50
for j in range(0,maxLength):
if j>=startPos and j<startPos+10:
x_np[i,j,0] = math.sin((j-startPos)*math.pi/10)
else:
x_np[i,j,0] = 0.0
if j<startPos+10:
y_np[i,j] = 1
else:
y_np[i,j] = 0
# Define the neural network
INPUT_SIZE = 1
class RNN(torch.nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.rnn = torch.nn.LSTM(
input_size=INPUT_SIZE,
hidden_size=16, # rnn hidden unit
num_layers=1, # number of rnn layer
batch_first=True,
)
self.out = torch.nn.Linear(16, 2)
def forward(self, x, h_state):
r_out, h_state = self.rnn(x, h_state)
outs = [] # save all predictions
for time_step in range(r_out.size(1)): # calculate output for each time step
outs.append(self.out(r_out[:, time_step, :]))
return torch.stack(outs, dim=1), h_state
# Learn the network
rnn = RNN()
optimizer = torch.optim.Adam(rnn.parameters(), lr=0.01)
h_state = None # for initial hidden state
x = torch.Tensor(x_np) # shape (batch, time_step, input_size)
y = torch.Tensor(y_np).long()
torch.manual_seed(2)
numpy.random.seed(2)
for step in range(100):
prediction, h_state = rnn(x, h_state) # rnn output
# !! next step is important !!
h_state = None
loss = torch.nn.CrossEntropyLoss()(prediction.reshape((-1,2)),torch.autograd.Variable(y.reshape((-1,)))) # calculate loss
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients
errTrain = (prediction.max(2)[1].data != y).float().mean()
print("Error Training:",errTrain.item())
###############################################################################
steps = range(0,maxLength)
plotChoice = 3
plt.figure(1, figsize=(12, 5))
plt.ion() # continuously plot
plt.plot(steps, y_np[plotChoice,:].flatten(), 'r-')
plt.plot(steps, numpy.argmax(prediction.detach().numpy()[plotChoice,:,:],axis=1), 'g-')
plt.plot(steps, x_np[plotChoice,:,0].flatten(), 'b-')
plt.ioff()
plt.show()
关于python - 循环网络 (RNN) 不会学习非常简单的函数(问题中显示的图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52857213/
我使用 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 等)以及从网络底部到顶部的循环组成,以添加注意力机制或特殊的内存类型。我不熟悉符号循环,所以首先我
我是一名优秀的程序员,十分优秀!