Numpy ValueError:操作数无法与形状(4,2)(2,1)一起广播

2024-09-28 22:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了错误

Traceback (most recent call last): File "C:/Users/PycharmProjects/project.py", line 61, in pred = wOuthiddennp.tanh(ImatwInhidden) ValueError: operands could not be broadcast together with shapes (4,2) (2,1)

程序是用python编写的bp神经网络

import numpy as np
import random


h = 2 #no of hidden nuerons

epoch = 2000 #no of epochs

#input matrix
Imat = np.array([[1, 1],     
        [1, -1],
        [-1, 1],
        [-1, -1]])

#target pattern
Dmat = np.array([-1, 1, 1, -1])

noCase = Imat.shape[0]                  #number of test cases

B = np.ones([noCase,0], dtype = float)

noInputs = Imat.shape[1]                #number of inputs

#setting weights
wInhidden = (np.random.randn(h,1) - 0.5)/10
wOuthidden = (np.random.randn(h,1) - 0.5)/10

for i in range(0,epoch):
    ALr = 0.6
    BLr = ALr / 10
    for j in range(0,noCase):
        case = round((random.random() * noCase) + 0.5)             #random pattern
        if case > noCase:
            case = noCase
        elif case < 1:
            case = 1

        this_case = Imat[case-1,0]                                    #current pattern
        act = Dmat[case-1]

        hval = np.tanh(this_case * wInhidden)
        pred = hval*wOuthidden

        error = pred - act

        delHO = error * BLr * hval                                  #adjusting hidden weight output
        wOuthidden = wOuthidden - delHO
        delIH = ALr * error * wOuthidden *(1-(hval**2))*this_case    #adjusting hidden weight input
        wInhidden = wInhidden - delIH

    pred = wOuthidden*np.tanh(Imat*wInhidden)
    error = pred - Dmat
    err = [0]
    err[i] = (sum(error**2))**0.5
    if err[i] < 0.001:
        print("It has converged at the epoch: ", i)
        break

#display actual,predicted & error
print("State after no epochs",i)
print(Dmat)
print(pred)
print(pred-Dmat)
print(wInhidden)
print(wOuthidden)

Tags: ofinnprandomerrorcaseprintpred