我正在创建一个神经网络来打印患者是否患有心脏病。有6个输入属性和1个输出(0或1)。数据集有318行,我正在使用70-30拆分,因此x_train和y_train有222行。因此,在运行我在互联网上发现的代码时,它会给出尺寸错误:
Traceback (most recent call last):
File "nptestmedium.py", line 43, in <module>
nn.backprop()
File "nptestmedium.py", line 29, in backprop
d_weights1 = np.dot(self.input.T, (np.dot(2*(self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1)))
ValueError: shapes (222,222) and (1,4) not aligned: 222 (dim 1) != 1 (dim 0)
错误在于代码的权重部分,但我不知道rand()函数的参数是什么。有人可以帮我吗。谢谢
import numpy as np
from sklearn.model_selection import train_test_split
np.random.seed(2)
dataset = np.loadtxt("heartorig1.csv", delimiter=",")
X = dataset[:,0:6]
Y = dataset[:,6]
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=42)
def sigmoid(x):
return 1.0/(1+ np.exp(-x))
def sigmoid_derivative(x):
return x * (1.0 - x)
class NeuralNetwork:
def __init__(self, x, y):
self.input = x
self.weights1 = np.random.rand(self.input.shape[1],4)
self.weights2 = np.random.rand(4,1)
self.y = y
self.output = np.zeros(self.y.shape)
def feedforward(self):
self.layer1 = sigmoid(np.dot(self.input, self.weights1))
self.output = sigmoid(np.dot(self.layer1, self.weights2))
def backprop(self):
# application of the chain rule to find derivative of the loss function with respect to weights2 and weights1
d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output)))
d_weights1 = np.dot(self.input.T, (np.dot(2*(self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1)))
# update the weights with the derivative (slope) of the loss function
self.weights1 += d_weights1
self.weights2 += d_weights2
if __name__ == "__main__":
X = x_train
y = y_train
nn = NeuralNetwork(X,y)
for i in range(1500):
nn.feedforward()
nn.backprop()
print(nn.output)