python-pytorch实现lstm模型预测中文文本输出0.1.02

记录
2024年4月14日15:36:28----0.1.02

有问题还需要完善,会重复生成一句话

数据

一篇新闻:https://news.sina.com.cn/c/2024-04-12/doc-inarqiev0222543.shtml

参考

https://blog.csdn.net/qq_19530977/article/details/120936391

# https://blog.csdn.net/qq_19530977/article/details/120936391

效果

"""
布林肯国务卿
布林肯国务卿同王毅
布林肯国务卿同王毅主任
布林肯国务卿同王毅主任以及
布林肯国务卿同王毅主任以及其他
布林肯国务卿同王毅主任以及其他国家
布林肯国务卿同王毅主任以及其他国家敦促
布林肯国务卿同王毅主任以及其他国家敦促伊朗
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆的
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆的安全
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆的安全不容
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆的安全不容侵犯
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆的安全不容侵犯,
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆的安全不容侵犯,布
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆的安全不容侵犯,布林肯
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆的安全不容侵犯,布林肯国务卿
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆的安全不容侵犯,布林肯国务卿同王毅
布林肯国务卿同王毅主任以及其他国家敦促伊朗驻叙利亚使馆的安全不容侵犯,布林肯国务卿同王毅主任
"""

导入包

import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as Data
from torch.autograd import Variable
import jieba

分词到数组

复制文章到txt文档

allarray=[]
with open("./howtousercbow/data/news.txt",encoding="utf-8") as afterjieba:
    lines=afterjieba.readlines()
    print(lines)
    for line in lines:
        result=list(jieba.cut(line,False))
        for r in result:
            allarray.append(r.replace("\n",""))

allarray,len(allarray)
    

获取word2index和word2index

word2index={one:i for i,one in enumerate(allarray)}
index2word={i:one for i,one in enumerate(allarray)}
word2index[" "]=len(allarray)-1
index2word[len(allarray)-1]=" "
word2index[" "]

查看频次

from collections import Counter
Counter(allarray)

获取vacab

vocab_size = len(allarray)
vocab_size

生成训练数据



# 生成输入数据
batch_x = []
batch_y = []
window=1
seq_length=vocab_size
for i in range(seq_length - window + 1):
    x = word2index[allarray[i]]
    if i + window >= seq_length:
        y = word2index[" "]
    else:
        y = word2index[allarray[i + 1]]
    batch_x.append([x])
    batch_y.append(y)


# 训练数据
batch_x, batch_y = Variable(torch.LongTensor(batch_x)), Variable(torch.LongTensor(batch_y))
 
# 参数
embedding_size = 100
n_hidden = 32
batch_size = 10
num_classes = vocab_size
 
dataset = Data.TensorDataset(batch_x, batch_y)
loader = Data.DataLoader(dataset, batch_size, shuffle=True)
 
# 建立模型
class BiLSTM(nn.Module):
    def __init__(self):
        super(BiLSTM, self).__init__()
        self.word_vec = nn.Embedding(vocab_size, embedding_size)
        # bidirectional双向LSTM
        self.bilstm = nn.LSTM(embedding_size, n_hidden, 1, bidirectional=True)
        self.lstm = nn.LSTM(2 * n_hidden, 2 * n_hidden, 1, bidirectional=False)
        self.fc = nn.Linear(n_hidden * 2, num_classes)
 
    def forward(self, input):
    	# embedding_input是10x1x100
        embedding_input = self.word_vec(input)
      	# embedding_input调换后的size是1x10x100
        embedding_input = embedding_input.permute(1, 0, 2)
        bilstm_output, (h_n1, c_n1) = self.bilstm(embedding_input)
        lstm_output, (h_n2, c_n2)= self.lstm(bilstm_output)
        fc_out = self.fc(lstm_output[-1])
        return fc_out
 
model = BiLSTM()

训练

print(model)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
 
# 训练
for epoch in range(300):
    cost = 0
    for input_batch, target_batch in loader:
        pred = model(input_batch)
#         print("pred",pred)
#         print("target_batch",target_batch)
        loss = criterion(pred, target_batch)
        cost += loss.item()
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    print("Epoch: %d,  loss: %.5f " % (epoch, cost))

测试

def test(str):
    test_text =str
    test_batch = [word2index[str]]
#     print(test_batch)
    test_batch = torch.LongTensor([test_batch])
#     print("test_batch",test_batch)
#     print(test_batch)
    out = model(test_batch)
    predict = torch.max(out, 1)[1].item()
#     print(test_text,"后一个字母为:", index2word[predict])
    return index2word[predict]

连续预测

import time
s="布林肯"
while True:
    fenci=jieba.cut(s,False)
    fenciList=list(fenci)
    s=s+test(fenciList[-1:][0])
    
    time.sleep(1)
    print(s)
        
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是用PyTorch实现LSTM模型预测单时间序列的示例代码: ```python import torch import torch.nn as nn import numpy as np # 定义LSTM模型 class LSTM(nn.Module): def __init__(self, input_size, hidden_size, output_size=1, num_layers=1): super().__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.lstm = nn.LSTM(input_size, hidden_size, num_layers) self.fc = nn.Linear(hidden_size, output_size) def forward(self, x): h0 = torch.zeros(self.num_layers, x.size(1), self.hidden_size).to(device) c0 = torch.zeros(self.num_layers, x.size(1), self.hidden_size).to(device) out, _ = self.lstm(x, (h0, c0)) out = self.fc(out[-1, :, :]) return out # 设置随机种子 torch.manual_seed(42) np.random.seed(42) # 设定设备 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 生成数据 data = np.sin(np.arange(1000) * (20 * np.pi / 1000)).reshape(1, -1, 1) train_data = torch.from_numpy(data[:, :-200, :]).float().to(device) test_data = torch.from_numpy(data[:, -200:, :]).float().to(device) # 定义模型 model = LSTM(1, 32).to(device) # 定义损失函数和优化器 criterion = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # 训练模型 num_epochs = 1000 for epoch in range(num_epochs): outputs = model(train_data) optimizer.zero_grad() loss = criterion(outputs, train_data[-1, :, :]) loss.backward() optimizer.step() if epoch % 100 == 0: print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item())) # 测试模型 model.eval() with torch.no_grad(): outputs = model(test_data) loss = criterion(outputs, test_data[-1, :, :]) print('Test Loss: {:.4f}'.format(loss.item())) # 可视化结果 import matplotlib.pyplot as plt plt.plot(data[0, -200:, 0], label='True') plt.plot(outputs.cpu().numpy(), label='Predicted') plt.legend() plt.show() ``` 在这个示例中,我们生成了一个正弦波形的时间序列作为示例数据。我们使用LSTM模型预测未来200个时间步的值。我们将前800个时间步作为训练数据,后200个时间步作为测试数据。我们使用均方误差损失函数和Adam优化器进行训练。最后,我们将真实值和预测值可视化以进行比较。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值