pytorch 入门【task04】用PyTorch实现多层网络

本系列博客为跟随开源组织Datawhale学习小组的学习过程记录,任务内容及相关数据集为Datawhale开源组织搜集并无偿提供,饮水思源,特此宣传,欢迎关注Datawhale。
pytorch 入门【task04】用PyTorch实现多层网络
1、引入模块,读取数据
2、构建计算图(构建网络模型)
3、损失函数与优化器
3、开始训练模型
4、对训练的模型预测结果进行评估

import numpy as np
import matplotlib.pyplot as plt

# 生成数据
m = 200     # 样本个数
x = np.random.randn(2, m)
y = (x[0, :] > 0)*(x[1, :] > 0) * 1.0 + (x[0,:] < 0)*(x[1, :] < 0)

# 可视化数据分布
plt.scatter(x[0, :], x[1, :], c = y, s = 40, cmap=plt.cm.Spectral)
plt.show()

y = y.reshape(m, 1).T

建立网络模型并训练

import torch
import torch.nn.functional as F
import torch.nn.init as init
import math


# 从nn.module中继承整个神经网络的搭建元件,
# 这个类中可以继承所有可以用于搭建后续神经网络的元件

xy = np.loadtxt('', delimiter=',', dtype=np.float32)
x_data = Variable(torch.from_numpy(xy[:, 0:-1]))
y_data = Variable(torch.from_numpy(xy[:, [-1]]))

# 行数是样本数目,列数是特征数目
print(x_data.data.shape)
print(y_data.data.shape)

# 建立网络模型
class Model(torch.nn.Module):
    def __init__(self):
        """
        初始化
        """
        super(Model, self).__init__()
        # linear 可以让我们使用整个linear来进行y = Ax +b,包含weight和bias
        # 定义一个矩阵乘法, 需要填入的两个数字:in features, out features,代表乘法的两个维度

        self.l1 = torch.nn.Linear(8, 6)

        self.l2 = torch.nn.Linear(6, 4)
        self.l3 = torch.nn.Linear(4, 1)

    def forward(self, x):
        out1 = F.relu(self.l1(x))
        out2 = F.dropout(out1, p=0.5)
        out3 = F.relu(self.l2(out2))
        out4 = F.dropout(out3, p=0.5)
        y_pred = F.sigmoid(self.l3(out3))

        return y_pred