Я создаю нейронную сеть, чтобы печатать, есть ли у пациента болезнь сердца или нет. Есть 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)