NLP(2)--搭建简单的模型(nn)

发布于:2024-04-25 ⋅ 阅读:(21) ⋅ 点赞:(0)

前言

仅记录学习过程,有问题欢迎讨论

可能使用到的包

可以通过Anaconda直接install,不行就PIP install xxx

  • Python
  • Torch
  • Transformers
  • Scikit-learn
  • Numpy
  • Gensim
  • Pandas

我的版本:
可以用 conda list 查看
在这里插入图片描述
在这里插入图片描述

代码

如果有包导入不进来,可以先去网上查查怎么用Anaconda下载包,
一般是conda install xxx;
还有就是项目环境的配置需要配置到对应Anaconda的环境下

注:python版本最好3.8以上。

# try to build a simple neural network
import torch
import numpy
import torch.utils.data as Data
from torch.nn import init
import torch.optim as optim
# produce data list
num_input = 2
num_example = 1000
true_w = [2, -3.4]  # 真参数
true_b = 4.2  # 真 偏移量
# 特征
features = torch.tensor(numpy.random.normal(0, 1, (num_example, num_input)), dtype=torch.float)
# function
labels = true_w[0]*features[:, 0]+true_w[1]*features[:, 1] + true_b
# +噪声因子 均值为0、标准差为0.01的正态分布
labels += torch.tensor(numpy.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)

batch_size = 10
# 将训练数据的特征和标签组合
dataset = Data.TensorDataset(features, labels)
# 随机读取小批量
data_iter = Data.DataLoader(dataset, batch_size, shuffle=True)
# 读取并打印第一个小批量数据样本
for X,y in data_iter:
    print(X,y)
    break
# 定义模型 nn input/output
net = torch.nn.Sequential(
    torch.nn.Linear(num_input, 1)
)
print("net =", net)

for param in net.parameters():
    print(param)

# 使用net前 需要初始化参数 初始化
init.normal(net[0].weight, mean=0, std=0.01 )
init.constant_(net[0].bias, val=0)

# 定义损失函数
loss = torch.nn.MSELoss()
# 定义优化算法
optimzer = optim.SGD(net.parameters(), lr=0.03)
print("optimzer =", optimzer)
# 训练模型
num_epochs = 10
for epoch in range(1, num_epochs+1):
    for X, y in data_iter:
        output = net(X)
        l = loss(output, y.view(-1, 1))
        optimzer.zero_grad()# 梯度清零,等价于net.zero_grad()
        l.backward()
        optimzer.step()
    print('epoch %d, loss: %f' % (epoch, l.item()))

# 比较学到的模型参数和真实的模型参数
print('result ==================')
dense = net[0]
print(true_w, dense.weight)
print(true_b, dense.bias)