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


    前言

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

    可能使用到的包

    可以通过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)
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
  • 相关阅读:
    【clickhouse】ubuntu20安装clickhouse并用DBeaver远程管理
    [python 刷题] 42 Trapping Rain Water
    手撕前端javascript面试题---快速排序 | 全排列 | instanceof
    springboot项目中获取业务功能的导入数据模板文件
    Leetcode刷题Day8-------------字符串
    超级重磅!Apache Hudi多模索引对查询优化高达30倍
    SDK和API区别
    python 基于flask实现的sse 修改eventstream中类型字段
    手把手教你使用Vite构建第一个Vue3项目
    【无标题】
  • 原文地址:https://blog.csdn.net/njh1147394013/article/details/137867490