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)
)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值