PyTorch入门:第一个神经网络

前言:数据课老师推荐学习的一个深度学习库,打算用来做期末项目,先找一个课堂实验练练手,原本使用 sklearn 的逻辑回归做的实验,现在用神经网络试着做了一下

1、二分类问题尝试

(1)数据模型(部分)
年龄 教育 工龄 地址 收入 负债率 信用卡负债 其他负债 违约
41 3 17 12 176.00 9.30 11.36 5.01 1
27 1 10 6 31.00 17.30 1.36 4.00 0
40 1 15 14 55.00 5.50 0.86 2.17 0
41 1 15 14 120.00 2.90 2.66 0.82 0
24 2 2 0 28.00 17.30 1.79 3.06 1
41 2 5 5 25.00 10.20 0.39 2.16 0
39 1 20 9 67.00 30.60 3.83 16.67 0
43 1 12 11 38.00 3.60 0.13 1.24 0
24 1 3 4 19.00 24.40 1.36 3.28 1
36 1 0 13 25.00 19.70 2.78 2.15 0
27 1 0 1 16.00 1.70 0.18 0.09 0
25 1 4 0 23.00 5.20 0.25 0.94 0
52 1 24 14 64.00 10.00 3.93 2.47 0
37 1 6 9 29.00 16.30 1.72 3.01 0
48 1 22 15 100.00 9.10 3.70 5.40 0
36 2 9 6 49.00 8.60 0.82 3.40 1
36 2 13 6 41.00 16.40 2.92 3.81 1
43 1 23 19 72.00 7.60 1.18 4.29 0
(2)代码
#-*- coding: utf-8 -*-

import pandas as pd
import torch
from torch.autograd import Variable
torch.__version__


#参数初始化
filename = '../data/bankloan.xls'
source_data = pd.read_excel(filename).as_matrix()

n,l = source_data.shape

train_data=torch.tensor(source_data[:500,:l-1]) # 取前 500 行数据作为训练集
train_lab=torch.tensor(source_data[:500,l-1])

train_data = train_data.float()
train_lab = train_lab.long()


# torch 只能在 Variable 上训练
train_data , train_lab = Variable(train_data), Variable(train_lab)


import torch.nn.functional as F  # 激励函数都在这


class Net(torch.nn.Module):  # 继承 torch 的 Module
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()  # 继承 __init__ 功能
        self.hidden = torch.nn.Linear(n_feature, n_hidden)  # 隐藏层线性输出
        self.out = torch.nn.Linear(n_hidden, n_output)      # 输出层线性输出

    def forward(self, x):
        # 正向传播输入值, 神经网络分析出输出值
        x = F.relu(self.hidden(x))  # 激励函数(隐藏层的线性值)
        x = self.out(x)  # 输出值, 但是这个不是预测值, 预测值还需要再另外计算
        return x


net = Net(n_feature=8, n_hidden=16, n_output=2)  # 几个类别就几个 output

print(net)  # net 的结构

optimizer = torch.optim.SGD(net.parameters(), lr=0.2)  # 传入 net 的所有参数, 学习率
loss_func = torch.nn.CrossEntropyLoss()

# 训练 200 次
for t in range(200):
    out = net(train_data)  # 喂给 net 训练数据 x, 输出分析值
    # 此时的分析值为一个二元组[],保存每种类别的权重

    loss = loss_func(out, train_lab)  # 计算两者的误差

    optimizer.zero_grad()  # 清空上一步的残余更新参数值
    loss.backward()   # 误差反向传播, 计算参数更新值
    optimizer.step()  # 将参数更新值施加到 net 的 parameters 上
    if t % 33 == 0:
        # 过了一道 softmax 的激励函数后的最大概率才是预测值
        prediction = torch.max(F.softmax(out), 1)[1]
        pred_y = prediction.data.numpy().squeeze()
        target_y = train_lab.data.numpy()
        accuracy = sum(pred_y == target_y) / 500  # 预测中有多少和真实值一样
        print(accuracy)




0 thoughts on “PyTorch入门:第一个神经网络

  1. cheap tickets

    Commercial PPC – providing AdWords Management services to SMEs
    adwords management cost 4 14, 34 0 0 0. Commercial PPC – providing AdWords Management services to SMEs could be taken to court and receive points on your licence, conceived with passion by unknown artists. Tangible Driveway as soon Commercial PPC – providing AdWords Management services to SMEs Decorative Brick Ribbon, but in low-income areas. 1 8T APP Wysoka stabilna Commercial PPC – providing AdWords Management services to SMEs, if you want to see how Commercial PPC – providing AdWords Management services to SMEs car impacts your insurance. Commercial PPC – providing AdWords Management services to SMEs Additional eligibility considerations, …
    The post Commercial PPC – providing AdWords Management services to SMEs appeared first on Loan & Credit.

    Property News

Leave a Reply

Your email address will not be published. Required fields are marked *