Pytorch学习(六)---- 神经网络快速搭建

莫烦python视频学习笔记 视频链接https://www.bilibili.com/video/BV1Vx411j7kT?from=search&seid=3065687802317837578

import torch
import torch.nn.functional as F
from torch.autograd import Variable
import matplotlib.pyplot as plt
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
# import os 这里是为了防止报错加的

# 设置数据
n_data = torch.ones(100, 2)           # 全部数据
x0 = torch.normal(2*n_data, 1)
y0 = torch.zeros(100)                 # x0的标签都为0
x1 = torch.normal(-2*n_data, 1)
y1 = torch.ones(100)                  # x1的标签都为1
x = torch.cat((x0, x1), 0).type(torch.FloatTensor)          # FloatTensor = 32-bit floating
y = torch.cat((y0, y1), ).type(torch.LongTensor)            # LongTensor = 64-bit integer
x, y = Variable(x), Variable(y)

方法一

# method 1
class Net(torch.nn.Module):
# 搭建基本信息
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)   # 隐藏层
        self.predict = torch.nn.Linear(n_hidden, n_output)    # 预测层
# 神经网络前向传递的过程(流程)
    def forward(self, x):
        x = F.relu(self.hidden(x))      # 用激励函数激活
        x = self.predict(x)      # 预测值的取值范围很大,激励函数会将预测值截断,故而不用激励函数
        return x

net1 = Net(2, 10, 2)             # 两个特征,10个神经元,输出两个特征

方法二 -----快速搭建

# method 2
net2 = torch.nn.Sequential(
       torch.nn.Linear(2, 10),
       torch.nn.ReLU(),
       torch.nn.Linear(10, 2)
)

输出看一下结果:

print(net1)
print(net2)

方法一结果:

Net(
  (hidden): Linear(in_features=2, out_features=10, bias=True)
  (predict): Linear(in_features=10, out_features=2, bias=True)
)

方法二结果:

Sequential(
  (0): Linear(in_features=2, out_features=10, bias=True)
  (1): ReLU()
  (2): Linear(in_features=10, out_features=2, bias=True)
)

你可能感兴趣的:(神经网络)