小言_互联网的博客

神经网络与深度学习-9- 网络结构 -PyTorch

254人阅读  评论(0)

参考

  《神经网络与深度学习》

    课时14 张量数据类型-1_哔哩哔哩_bilibili

    深度神经网络(DNN) - _yanghh - 博客园

目录

    1: 常见网络结构

    2: 前馈神经网络

    3: 反向传播算法

    4: Softmax 分类例子

## Versions:
- [Version 1.0](https://docs.google.com/presentation/d/11mR1nkIR9fbHegFkcFq8z9oDQ5sjv8E3JJp1LfLGKuk/edit?usp=sharing)


一  常见网络结构

     1.1 前馈网络

           定义:

           每一层中的神经元接收前一层神经元的输出,并输出到下一层神经元。

         主要包括:

                     全连接前馈网络 和 卷积神经网络

       

     1.2 记忆网络

            称为反馈网络,网络中的神经元不但可以接收其它神经元的信息,也可以接收自己的历史信息。 增加了记忆功能

           主要包括:

                     RNN,LSTM,Hopfield,玻尔兹曼机,受限玻尔兹曼机

   

     1.3 图网络

             前面输入都可以表示向量或者向量序列,实际应用中很多数据是图结构数据,比如

知识谱,社交网络,分子网络。

          主要包括:

          图卷网络  Graph Conolutional Network

          图注意网络: Graph Attention Network GAT

          消息传递网络   Message Passing Neural Netwrok 


二  前馈神经网络

     2.1 前馈神经网络记号

          :      神经网络层数

           :第l层神经网络的个数

           :第L层神经元的激活函数

          :       l-1层到l层的权重系数矩阵

          :        l-1层到l层的偏置

         :        l  层神经元的输入

        :         l层神经元的输出

         

         

        

   2.2 参数学习

      这边以分类问题为例,其损失函数为

      

    给定训练集,将每个样本输入给前馈神经网络,得到网络的输出为, 结构化风险函数为

      

    F: Frobenius 范数

    

 在梯度下降法的每次迭代中,第l层的参数 参数更新方式为

 

 

   在神经网络的训练过程中经常使用反向传播算法来高效计算梯度


四  张量数据类型

   pytorch 没有string 类型,对于单个字母用one-hot向量表示

如果是字符串,用word2vec 或者 glove 来实现


  
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Mon Sep 5 21:50:02 2022
  4. @author: cxf
  5. """
  6. import torch
  7. def Debug():
  8. data = torch.randn( 2, 3)
  9. print( "\n 数据类型: ",data. type(), "\t 维度 ",data.dim())
  10. data_gpu = data.cuda()
  11. hardware = isinstance(data_gpu, torch.cuda.FloatTensor)
  12. print( "是否为GPU类型:",hardware)
  13. a = torch.tensor( 1.0) #标量
  14. print( "\n 标量: ",a. type(),a.shape, len(a.shape),a.size(), "\t 维度 ",a.dim()) #标量维度
  15. if __name__ == "__main__":
  16. Debug()

二 反向传播算法

以DNN为例:

输入:

        训练集

        验证集V, 学习率

repeat

         训练集随机排序

         for  n =1  ... N   do

                 选取样本      

         前向传播:

                (神经元输入)

                (激活函数)

          反向传播计算每一层的误差

          

         

          

                     

     求层:

 

   更新每一层的导数

         

         

 更新每一层的参数

         

         

损失函数

       

   


 


  
  1. import torch
  2. import torch.utils.data as Data
  3. import numpy as np
  4. '''
  5. shuffle:(数据类型 bool)
  6. 洗牌。默认设置为False。在每次迭代训练时是否将数据洗牌,默认设置是False。
  7. 将输入数据的顺序打乱,是为了使数据更有独立性
  8. num_workers:(数据类型 Int)
  9. 工作者数量,默认是0。使用多少个子进程来导入数据。
  10. 设置为0,就是使用主进程来导入数据。注意:这个数字必须是大于等于0的,负数估计会出错。
  11. drop_last:(数据类型 bool)
  12. 丢弃最后数据,默认为False。设置了 batch_size 的数目后,
  13. 最后一批数据未必是设置的数目,有可能会小些。这时你是否需要丢弃这批数据。
  14. '''
  15. def load( x,y,batch):
  16. BATCH_SIZE = batch #批训练数据量的大小
  17. trainset = Data.TensorDataset(x, y) #训练数据集
  18. #创建一个dataloader类的实例
  19. loader = Data.DataLoader(
  20. dataset=trainset,
  21. batch_size=BATCH_SIZE,
  22. shuffle= True,
  23. num_workers= 2,
  24. drop_last = True)
  25. return loader
  26. '''
  27. 显示数据集
  28. '''
  29. def sampling( x,y,batch):
  30. loader = load(x,y,batch)
  31. for epoch in range( 1):
  32. print( "\n--------------------")
  33. for batch_idx, (batch_x, batch_y) in enumerate(loader):
  34. #print("\n batch_idx:{},\n batch_x:{}, \n batch_y:{}".format(batch_idx, batch_x, batch_y))
  35. return batch_x, batch_y
  36. '''
  37. 随机采样的API
  38. '''
  39. def sampling( x,y,batch,N):
  40. indices = np.arange( 0,N)
  41. np.random.shuffle(indices)
  42. indices1 = indices[ 0:batch]
  43. index = torch.tensor(indices1,dtype=torch. int)
  44. #indices = torch.tensor([0, 2])
  45. trainData = torch.index_select(x, 0, index) #行抽取
  46. trainLabel = torch.index_select(y, 0, index) #行抽取
  47. print( "\n trainlabel ",trainLabel)
  48. return trainData, trainLabel
  49. ----------------
  50. # -*- coding: utf-8 -*-
  51. """
  52. Created on Tue Nov 8 17:09:56 2022
  53. @author: chengxf2
  54. https://blog.51cto.com/u_15132389/4755744
  55. """
  56. import numpy as np
  57. import torch
  58. from sklearn.datasets import load_iris
  59. import sampling
  60. import torch.nn.functional as F
  61. class BP:
  62. '''
  63. 损失值
  64. args
  65. y: 标签值
  66. predY: 预测值 [150, 4]
  67. return
  68. loss 值
  69. '''
  70. def loss( self, y, predY):
  71. s = -torch.mm(y.T, torch.log(predY))
  72. loss = s.numpy()[ 0, 0]
  73. #print("\n s ",loss)
  74. return s
  75. '''
  76. 激活函数
  77. args
  78. x: 输入
  79. return
  80. y: 输出
  81. '''
  82. def softmax( self,x):
  83. y = F.softmax(x,dim= 0) #1 行
  84. """
  85. z = torch.exp(x)
  86. s = z.sum()
  87. y = z/s
  88. """
  89. return y
  90. '''
  91. 训练
  92. args
  93. trainData: 训练数据集
  94. trai
  95. '''
  96. def train( self):
  97. m= 150
  98. W = 0
  99. trainData = self.x
  100. trainLabel = self.y
  101. W = torch.ones(( 3, 4))
  102. m,n = self.x.shape[ 0],self.x.shape[ 1]
  103. print( "\n m ",m, "\t n ",n)
  104. trainData, trainLabel = sampling.sampling(self.x,self.y, self.batch,m)
  105. for j in range(self.maxIter):
  106. for i in range(self.batch):
  107. x = trainData[i].view( 4, 1)
  108. y = trainLabel[i].view( 3, 1)
  109. a = torch.mm(W, x)
  110. predY = self.softmax(a)
  111. deltaW = torch.mm(predY-y,x.T)
  112. W= W-self.learnRate*deltaW
  113. loss = self.loss(y, predY)
  114. print( "\n i %d loss %7.3f"%(j,loss))
  115. print(W)
  116. '''
  117. 加载数据集#[100,4]
  118. '''
  119. def load_data( self):
  120. iris = load_iris()
  121. x = iris.data #数据
  122. y = iris.target #特征
  123. print( "\n数据集数据的形状:", x.shape) #[150,4]
  124. print( "\n数据集的标签:\n", y) #[0,1,2]
  125. self.x = torch.tensor(x, dtype=torch. float)
  126. self.m, self.n = self.x.shape[ 0], self.x.shape[ 1]
  127. self.y =torch.zeros([self.m, 3],dtype=torch. float) #one-hot
  128. for i in range(self.m):
  129. j = y[i]
  130. self.y[i,j] = 1.0
  131. def __init__( self):
  132. self.m = 0
  133. self.n = 0
  134. self.batch = 20 #从每类数据中随机选取40个
  135. self.maxIter = 1000 #最大迭代次数
  136. self.learnRate = 0.1 #学习率
  137. if __name__ == "__main__":
  138. bp = BP()
  139. bp.load_data()
  140. bp.train()

 


转载:https://blog.csdn.net/chengxf2/article/details/126628577
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场