我最近开始学习Python,并试图实现我的第一个神经网络。我的目标是编写一个函数,生成具有可变层和节点数量的神经网络。所有必要的信息都存储在层结构中(例如:第一层有四个节点,第三层有三个节点)
import numpy as np
#Vector of input layer
input = np.array([1,2,3,4])
#Amount of nodes in each layer
layerStructure = np.array([len(input),2,3])
#Generating empty weight matrix container
weightMatrix_arr = np.array([])
#Initialsing random weights matrices
for ii in range(len(layerStructure[0:-1])):
randmatrix = np.random.rand(layerStructure[ii+1],layerStructure[ii])
print(randmatrix)
上面的代码生成以下输出:
[[0.6067148 0.66445212 0.54061231 0.19334004]
[0.22385007 0.8391435 0.73625366 0.86343394]]
[[0.61794333 0.9114799 ]
[0.10626486 0.95307027]
[0.50567023 0.57246852]]
我的第一次尝试是将每个随机权重矩阵存储在一个名为weightMatrix\u arr的容器数组中。但是,由于各个矩阵的形状不同,我不能使用np.append()将它们全部存储在矩阵容器中。如何保存这些矩阵,以便在反向传播期间访问它们
如果内存消耗不是问题,那么您可以将所有层塑造成最长的层,并根据
layerStructure
值忽略额外的单元您可以使用
list
而不是np.array
:否则,您可以将
weightMatrix_arr dtype
设置为object
: :请注意,在两种情况下,如果不访问图层矩阵,则无法访问内层索引:
相关问题 更多 >
编程相关推荐