NLP自然语言处理(三)

NLP自然语言处理(三)

一、pytorchAPI的使用
  1. nn.Module
    a. _ init _:自定义的方法实现位置
    nn.Linear(input的特征数量,output的特征数量) torch预先定义好的模型(全链接层)传入的参数是输入的数量,输出的数量是(in_features,out_f
    eatures),是不算(batch_size的列数)
    b.forward : 完成一次向前计算过程

  2. optimizer 优化器类
    a. torch.optim.SGD(参数,学习率)
    b. torch.optim.Adam(参数,学习率)

  3. 损失函数
    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()

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敷衍zgf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值