如何使用 python 计算这些权重和偏差的前向传递输出

How to compute the forward pass outputs for these weights and biases with python

我正在尝试使用 python 进行一些密集神经网络机器学习。我在完成代码以计算权重和偏差的输出时遇到问题。当我在权重和某个索引处的矩阵元素之间应用操作数 * 时,我得到 ValueError: operands could not be broadcast together with shapes (100,784) (1000,784,1) 的错误。我是在循环中应用了错误的索引还是我做错了什么请帮忙。

##initialize the training and test arrays
train=np.empty((1000,28,28),dtype='float64')
trainY=np.zeros((1000,10,1))
test=np.empty((10000,28,28), dtype='float64')
testY=np.zeros((10000,10,1))

##reading image data into the training array
#load the images
i=0
for filename in os.listdir('Data/Training1000/'):
    y=int(filename[0])
    trainY[i,y]=1.0
    train[i]=cv2.imread('Data/Training1000/{0}'.format(filename),0)/255.0
    i+=1

##reading image data into the testing array
i=0

for filename in os.listdir('Data/Test10000'):
    y = int(filename[0])
    testY[i,y] = 1.0
    test[i] = cv2.imread('Data/Test10000/{0}'.format(filename),0)/255.0 
    i=i+1

##reshape the training and testing arrays
trainX = train.reshape(train.shape[0],train.shape[1]*train.shape[2],1)
testX = test.reshape(test.shape[0],test.shape[1]*test.shape[2],1)
##section to declare the weights and the biases
w1 = np.random.uniform(low=-0.1,high=0.1,size=(numNeuronsLayer1,784))
b1 = np.random.uniform(low=-1,high=1,size=(numNeuronsLayer1,1))
w2 = np.random.uniform(low=-0.1,high=0.1,size=(numNeuronsLayer2,numNeuronsLayer1))
b2 = np.random.uniform(low=-0.1,high=0.1,size=(numNeuronsLayer2,1))

##declare the hidden layers
numNeuronsLayer1=100
numNeuronsLayer2=10
numEpochs=100

##declare a learning rate
learningRate = 0.1;

##do the forward pass on the weights and the biases
for n in range(0,numEpochs):
    loss=0
    trainX,trainY = shuffle(trainX, trainY)

    for i in range(trainX.shape[0]):
    ##this is where I have a problem, the line below throws the error described above
    ##my first pass is declared a2
    a2=w1*train[i]+w2*trainX[i]+b1
    

如何在上面的循环中正确引用我的训练变量以消除广播错误,谢谢。

你非常接近,但有几个问题。首先,您需要进行矩阵乘法。 * 将进行逐元素乘法(即 np.array([1,2,3]) * np.array([2,3,4]) = np.array([2,6,12])。要使用 numpy 进行矩阵乘法,您可以使用 @ 运算符(即 matrix1 @ matrix2)或使用 np.matmul 函数。

你的另一个问题是输入的形状。我不确定你为什么要添加第 3 维([=19= 末尾的 1)。你应该把它保持为矩阵(将其更改为 train.reshape(train.shape[0],train.shape[1]*train.shape[2]),更改 test.reshape相应地。

最后,你的推理线有点偏离:a2=w1*train[i]+w2*trainX[i]+b1

您必须先计算 a1,然后再计算 a2。矩阵乘法的一个重要部分是内部维度必须一致(即,不能将形状为 [100,50] 和 [100, 50] 的矩阵相乘,但可以将形状为 [100,50] 和 [50, 60] 的矩阵相乘,矩阵乘积的结果形状是每个矩阵的外部指标,在本例中为 [100,60])。作为矩阵乘法的结果,您还可以摆脱围绕训练示例的 for 循环。所有的例子都是同时计算的。所以要计算 a1,我们需要转置我们的 w1 并将其作为右手变量。

a1 = ( trainX @ w1.transpose() ) + b1.transpose()

然后我们可以计算 a2 作为 a1

的函数
a2 = ( a1 @ w2.transpose() ) + b2.transpose()