【深度学习Pytorch】二、多层神经网络

有关python图像绘制

import matplotlib.pyplot as plt
import seaborn as sns

plt.style.use('seaborn-whitegrid') #设置图像的风格
sns.set_style("white")
plt.figure(figsize=(5,3)) #设置画布大小
plt.title("AND GATE",fontsize=16) #设置图像标题
plt.scatter(X[:,1],X[:,2],#散点图的横坐标和纵坐标
c=andgate,#颜色=真实标签的类别
cmap="rainbow") #绘制散点图

plt.xlim(-1,3) #设置横纵坐标尺寸
plt.ylim(-1,3)

plt.grid(alpha=.4,axis="y") #显示背景中的网格
plt.gca().spines["top"].set_alpha(.0) #让上方和右侧的坐标轴被隐藏
plt.gca().spines["right"].set_alpha(.0);

分类模型和决策边界参考:分类模型的决策边界、评价指标-CSDN博客

一、异或门的多层神经网络

绘图发现四个点无法通过绘制一条直线分为两类,这是非线性问题

多层神经网络结构图:

x0 = torch.tensor([1,1,1,1],dtype=tensor.float32)
sigma_nand = NAND(x)
sigma_or = OR(x)
#torch.cat((x0,sigma_nand,sigma_or),dim=1)#联合,三个一维张量,报错没有dim=1的维度
input2 = torch.cat((x0.view(4,1)sigma_nand.view(4,1),sigma_or.view(4,1),dim=1)#把三个张量均换为四行一列的形式

二、黑箱:深层神经网络的不可解释性

有关激活函数h(z)机器学习中的数学——激活函数(一):Sigmoid函数_von Neumann的博客-CSDN博客

通常同一层的激活函数一致。

三、深度神经网络正向传播全过程实现

我们有500条数据,20个特征,标签为3分类。我们现在要实现一个三层神经网络,这个神经网络的架构如下:第一层有13个神经元,第二层有8个神经元,第三层是输出层。其中,第一层的激活函数是relu,第二层是sigmoid。

import torch
import torch.nn as nn
from torch.nn import functional as F

#确定数据
torch.random.manual_seed(99)
X = torch.rand((500,2),dtype=torch.float32)
y = torch.randint(low=0,high=3,size=(500,1),dtype=torch.float32)

#用继承的方式 torch.nn->nn.modle,nn.functional
class Model(nn.Module):
    def __init__(self,in_features=10,out_features=2):#类被实例化后瞬间执行的函数

        """
            in_features (int): 输入该神经网络的数目
            out_features (int): 神经网络的输出数目
        """
        super(Model,self).__init__()#继承父类的全部内容,包含init函数

        self.linear1 = nn.Linear(in_features,13,bias=True)
        self.linear2 = nn.Linear(13,8,bias=True)
        self.output = nn.Linear(8,out_features,bias=True)
    
    def forward(self,x):#神经网络的向前传播
        z1 = self.linear1(x)
        sigma1 = torch.relu(z1)
        z2 = self.linear2(sigma1)
        sigma2 = torch.sigmoid(z2)
        z3 = self.output(sigma2)
        sigma3 = F.softmax(z3,dim=1)
        return sigma3

input_ = X.shape[1]
output_ = len(y.unique())

#实例化神经网络
torch.random.manual_seed(99)
net = Model(in_features=input_,out_features=output_)

print(net.forward(X))
print(net.linear1.weight)#w X(500,20)->(20,500)
print(net.linear1.weight.shape)#[13.20] (13,20)*(20,500)->(13,500)
#属性的继承
net.training#是否用于训练
net.cuda() #将整个网络转移到GPU运行
net.cpu() #将整个网络转移到CPU运行
net.apply() #对神经网络中所有层,init函数中所有的类对象执行同样操作
net.parameters() #内包含所有需要求解的权重和截距
for param in net.parameters():
    print(param)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wing以一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值