任务:预测提供的灾难推文是否真实。已经将我的文本数据转换成张量,然后再转换成train_loader。所有必需的代码如下所述
我的模型架构
class RealOrFakeLSTM(nn.Module):
def __init__(self, input_size, output_size, embedding_dim, hidden_dim, n_layers, bidirec, drop_prob):
super().__init__()
self.output_size=output_size
self.n_layers=n_layers
self.hidden_dim=hidden_dim
self.bidirec=True;
self.embedding=nn.Embedding(vocab_size, embedding_dim)
self.lstm1=nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=drop_prob, batch_first=True, bidirectional=bidirec)
#self.lstm2=nn.LSTM(hidden_dim, hidden_dim, n_layers, dropout=drop_prob, batch_first=True)
self.dropout=nn.Dropout(drop_prob)
self.fc=nn.Linear(hidden_dim, output_size)
self.sigmoid=nn.Sigmoid()
def forward(self, x):
batch=len(x)
hidden1=self.init_hidden(batch)
#hidden2=self.init_hidden(batch)
embedd=self.embedding(x)
lstm_out1, hidden1=self.lstm1(embedd, hidden1)
#lstm_out2, hidden2=self.lstm2(lstm_out1, hidden2)
lstm_out1=lstm_out1.contiguous().view(-1, self.hidden_dim) # make it lstm_out2, if you un comment the other lstm cell.
out=self.dropout(lstm_out1)
out=self.fc(out)
sig_out=self.sigmoid(out)
sig_out=sig_out.view(batch, -1)
sig_out=sig_out[:, -1]
return sig_out
def init_hidden(self, batch):
if (train_on_gpu):
if self.bidirec==True:
hidden=(torch.zeros(self.n_layers*2, batch, self.hidden_dim).cuda(),torch.zeros(self.n_layers*2, batch, self.hidden_dim).cuda())
else:
hidden=(torch.zeros(self.n_layers, batch, self.hidden_dim).cuda(),torch.zeros(self.n_layers, batch, self.hidden_dim).cuda())
else:
if self.bidirec==True:
hidden=(torch.zeros(self.n_layers*2, batch, self.hidden_dim),torch.zeros(self.n_layers*2, batch, self.hidden_dim))
else:
hidden=(torch.zeros(self.n_layers, batch, self.hidden_dim),torch.zeros(self.n_layers, batch, self.hidden_dim))
return hidden
超参数和训练
learning_rate=0.005
epochs=50
vocab_size = len(vocab_to_int)+1 # +1 for the 0 padding
output_size = 2
embedding_dim = 300
hidden_dim = 256
n_layers = 2
batch_size=23
net=RealOrFakeLSTM(vocab_size, output_size, embedding_dim, hidden_dim, n_layers, True, 0.3)
net.to(device)
criterion=nn.BCELoss()
optimizer=torch.optim.Adam(net.parameters(),lr=learning_rate)
net.train()
loss_arr=np.array([])
lossPerEpoch=np.array([])
for i in range(epochs):
total_loss=0;
for input,label in train_loader:
if train_on_gpu:
input=input.to(device)
label=label.to(device)
optimizer.zero_grad()
input=input.clone().detach().long()
out=net(input)
loss=criterion(out.squeeze(),label.float())
loss_arr=np.append(loss_arr,loss.cpu().detach().numpy())
loss.backward()
optimizer.step()
total_loss+=loss
total_loss=total_loss/len(train_loader)
lossPerEpoch=np.append(lossPerEpoch,total_loss.cpu().detach().numpy())
print("Epoch ",i,": ",total_loss)
torch.save(net.state_dict(), Path+"/RealOrFakeLSTM.pt")
torch.save(net, Path+"/RealOrFakeLSTM.pth")
current_time=str(time.time())
torch.save(net.state_dict(), Path+"/pt/RealOrFakeLSTM"+'_pt_'+current_time+".pt")
torch.save(net, Path+"/pth/RealOrFakeLSTM"+'_pth_'+current_time+".pth")
总损失值几乎相同,测试数据集中的所有结果概率完全相同。我对这个很陌生,所以超参数调整,我有点喜欢bruteforce,但似乎没有任何效果,我认为我的问题不在于架构,而在于训练部分,因为所有的预测都完全相同
好消息是:“总损失值几乎相同”,这意味着它们并不总是相同的,因此,我认为您的网络不会输出恒定的概率!我可以看出你的培训没有按计划进行的原因有很多。不幸的是,如果不调试自己,我将无法肯定地说会发生什么。以下是我的假设:
True
输入和5%的False
输入,那么你的网络自然会从每次预测True
开始(logits对应的概率约为95%)。在这种情况下,尝试人为地平衡它(至少暂时地):可以通过复制False
示例(理想情况下不是在内存中而是直接在代码中)或删除一些True
示例(理想情况下也只是在代码中,而不是在数据库中)来实现李>尽管测试所有这些假设可能会对您有所帮助,但我首先鼓励您了解网络的输出,打印softmax层的输出:它输出的概率有多大,您能猜出原因吗?(有时你不能,但通常情况下,这是可能的,就像我在前面的回答中提到的95/5概率的情况)检查损失是否是你期望的,如果有这个输出(如果需要的话,手动计算),一般来说,好奇地想知道你的代码是如何运行的,并检查它是否在任何可以解释变量的地方都能正常工作
这是机器学习中最难的部分之一,在机器学习中一帆风顺并不容易;)祝你好运
从我可以告诉你的是,在每次向前传递中初始化hidden1=self.init_hidden(批处理)。这不应该是正确的。在每个正向过程中初始化一个层可以解释您描述的行为
相关问题 更多 >
编程相关推荐