无法弄清楚将浮点数或整数输入我的神经网络

Cannot figure out inputting floats or integers into my neural-network

抱歉,如果这是一个微不足道的问题,或者只是愚蠢的问题,我才刚刚开始使用 python 和神经网络...所以我在教程中制作了这个简单的神经网络,一切正常好吧,我的问题是我将如何改变我的输入和输出目标,因为目前我不明白为什么输入和输出在数组中?我想做一些事情,比如让它在递减值达到某个点时学习 return a 1,比如 0.25,否则 return 0?一个例子是输入是到障碍物的 X 距离,当它足够近时它可以学会跳跃(输出 1 = 跳跃,输出 0 = 什么都不做)? (总而言之,我的问题是我试图找到一种方法来输入浮点数之类的东西并输出浮点数或整数之类的东西,但它似乎只接收和输出 np.arrays)这是参考代码(这个有效很好,但我不确定应该如何更改输入和输出目标...):

import numpy as np

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(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_weights2



if __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是什么,一般来说,我们通常会在NN中输入多个样本,batch size是样本的数量,看,输入有 at list 2 dim [batch_size, fea_size],所以我们使用 ndarray 来包含输入。

如果你想输入一个单一的(意味着batch size是1)浮点数(意味着fea_size是1),你需要使用形状(1,1)的ndarray包装你的intput,比如np.array([[0.5]]).

接下来,NN 的输出也是形状 [batch_size, output_size],它给出所有输入样本的结果,output_size id 由最后一层的权重决定(在你的代码中 self.weights2 = np.random.rand(4,1)), 这意味着 output_size 是 1。所以如果你想要一个浮点数输出,你可以从 np.output[:, 0] 中获取所有样本。