NLP自然语言处理(三)
一、pytorchAPI的使用
-
nn.Module
a. _ init _:自定义的方法实现位置
nn.Linear(input的特征数量,output的特征数量) torch预先定义好的模型(全链接层)传入的参数是输入的数量,输出的数量是(in_features,out_f
eatures),是不算(batch_size的列数)
b.forward : 完成一次向前计算过程 -
optimizer 优化器类
a. torch.optim.SGD(参数,学习率)
b. torch.optim.Adam(参数,学习率) -
损失函数
a.均方误差 nn.MELoss() 常用语分类问题
b.交叉熵损失 nn.CrossEntropyLoss() 常用与逻辑回归
二、API实现线性回归
import torch
import torch.nn as nn
from torch.optim import SGD
import matplotlib.pyplot as plt
# 1.准备数据
x = torch.rand([500,1]) # 创建一个0-1 符合要求形状的tensor
y_true = 3*x + 0.8
# 2.定义模型
class MyLinear(nn.Module) :
def __init__(self):
# 继承父类的init
super(MyLinear, self).__init__()
self.linear = nn.Linear(1,1)
def forward(self,x):
out = self.linear(x)
return out
# 3.实例化模型 优化器类实例化 loss实例化
my_linear = MyLinear()
optmizer = SGD(my_linear.parameters(),0.001) # 0.001学习率
loss_fn = nn.MSELoss()
# 4.循环 进行梯度下降 参数更新
for i in range(2000):
# 得到预测值
y_predict = my_linear(x)
loss = loss_fn(y_predict,y_true) # input:y_predict target:y_true
# 梯度置为0 使用优化器类optmizer
optmizer.zero_grad()
# 反向传播
loss.backward()
# 参数更新
optmizer.step()
if i % 50 == 0:
params = list(my_linear.parameters())
print(loss.item(),params[0].item(),params[1].item())
# print(loss.item(),list(my_linear.parameters())) my_linear.parameters() my_linear中的参数w,b
params = list(my_linear.parameters())
# 设置图片大小
plt.figure(figsize=(20,8))
# 散点图
plt.scatter(x.numpy().reshape(-1),y_true.numpy().reshape(-1))
# 直线
y_predict = torch.matmul(x,params[0]) + params[1]
plt.plot(x.numpy().reshape(-1),y_predict.detach().numpy().reshape(-1),c='r')
plt.show()