Python数组维度问题

2024-10-01 15:35:16 发布

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

我又在用Python、NumPy和数组来计算矩阵之间的一些计算。你知道吗

可能无法正常工作的代码部分如下:

train, test, cv = np.array_split(data, 3, axis = 0) 
train_inputs = train[:,: -1]
test_inputs = test[:,: -1]
cv_inputs = cv[:,: -1]

train_outputs = train[:, -1]
test_outputs = test[:, -1]
cv_outputs = cv[:, -1]

当打印这些矩阵信息(np.ndimnp.shapedtype)时,您将得到:

2
1
2
1
2
1
(94936, 30)
(94936,)
(94936, 30)
(94936,)
(94935, 30)
(94935,)
float64
float64
float64
float64
float64
float64

我相信它在所有*_output数组中都缺少1维。你知道吗

我需要的另一个矩阵是通过以下命令创建的:

newMatrix = neuronLayer(30, 94936) 

其中neuronLayer是一个类,定义如下:

class neuronLayer():
    def __init__(self, neurons, neuron_inputs):
        self.weights = 2 * np.random.random((neuron_inputs, neurons)) - 1

以下是最终输出:

outputLayer1 = self.__sigmoid(np.dot(inputs, self.layer1.weights))
ValueError: shapes (94936,30) and (94936,30) not aligned: 30 (dim 1) != 94936 (dim 0)

Python清楚地告诉我矩阵没有加起来,但我不明白问题出在哪里。你知道吗

有什么建议吗?你知道吗

PS:完整的代码粘贴在ħere。你知道吗


Tags: 代码testselfnptrain矩阵数组outputs
2条回答

你知道吗np.dot公司当参数是矩阵时使用矩阵乘法。看起来您的代码试图将两个具有相同维数的非平方矩阵相乘,但这不起作用。也许你想转置一个矩阵?Numpy矩阵有一个返回转置的T属性,您可以尝试:

self.__sigmoid(np.dot(inputs.T, self.layer1.weights))
layer1 = neuronLayer(30, 94936)    # 29 neurons with 227908 inputs
layer2 = neuronLayer(1, 30)         # 1 Neuron with the previous 29 inputs

其中`nueronLayer创建

self.weights = 2 * np.random.random((neuron_inputs, neurons)) - 1 

两个砝码的大小分别为(94936,30)和(30,1)。你知道吗

这句话毫无意义。我很惊讶它没有出错

layer1error = layer2delta.dot(self.layer2.weights.np.transpose)

我怀疑你想要np.transpose(self.layer2.weights)self.layer2.weights.T。你知道吗

但也许它到不了那里。train第一次用(94936,30)inputs调用think

    outputLayer1 = self.__sigmoid(np.dot(inputs, self.layer1.weights))
    outputLayer2 = self.__sigmoid(np.dot(outputLayer1, self.layer2.weights))

所以它尝试用2(94936,30),(94936,30)数组做np.dot。它们与圆点不兼容。您可以转置其中一个,生成(9493694936)数组或(30,30)。一个看起来太大了。(30,30)与第二层的重量兼容。你知道吗

np.dot(inputs.T, self.layer1.weights)

有机会好好工作。你知道吗

np.dot(outputLayer1, self.layer2.weights)
(30,30) with (30,1) => (30,1)

但后来你知道了

train_outputs - outputLayer2

无论train_outputs是(94936,)还是(94936,1),都会有问题

您需要确保数组形状正确地通过计算。不要一开始就检查。然后检查内部。确保你了解他们在每一步应该有什么形状。你知道吗

用更小的输入和层(比如10个样本和3个特性)开发和测试这段代码会容易得多。这样,您可以查看值以及形状。你知道吗

相关问题 更多 >

    热门问题