如果这是一个简单的问题,或者只是愚蠢的问题,请原谅,我刚刚开始学习Python和神经网络… 所以我按照一个教程制作了一个简单的neural network,一切都运行良好,我的疑问是如何更改我的输入和输出目标,因为目前我不明白为什么输入和输出是数组?我希望能够让它学会在递减值达到某个点时返回1,比如0.25,其他情况下返回0?一个例子是输入是到障碍物的X距离,它可以学会在足够接近时跳跃(输出1 = 跳跃,输出0 = 什么都不做)?(总结一下,我的困惑在于我想找到一种方法来输入像浮点数这样的东西,并输出像浮点数或整数这样的东西,但它似乎只能接受和输出np.arrays)这里是供参考的代码(这个代码运行良好,但我不知道该如何更改输入和输出目标…):
import numpy as npdef 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(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): 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))) self.weights1 += d_weights1 self.weights2 += d_weights2if __name__ == "__main__": X = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]]) y = np.array([[1],[0],[1],[0]]) nn = NeuralNetwork(X,y) for i in range(10000): nn.feedforward() nn.backprop() print(nn.output)
回答:
你需要了解什么是batch size
,一般来说,我们通常将多个样本输入到神经网络中,batch size
是样本的数量,你看,输入至少有两个维度[batch_size, fea_size]
,所以我们使用ndarray来包含输入。
如果你想输入一个单一的(意味着batch size
是1)浮点数(意味着fea_size
是1),你需要使用形状为(1,1)的ndarray包装你的输入,比如np.array([[0.5]])
。
接下来,神经网络的输出也是形状为[batch_size, output_size]
,它为所有输入样本提供结果,而output_size
由最后一层的权重决定(在你的代码中self.weights2 = np.random.rand(4,1)
),这意味着output_size
是1。所以如果你想要一个浮点数输出,你可以从np.output[:, 0]
中获取所有样本的输出。