四处走动" ValueError:操作数无法一起广播"

时间:2017-01-11 19:48:06

标签: python numpy error-handling scikit-learn

以下代码会产生以下值错误。

ValueError: operands could not be broadcast together with shapes (8,8) (64,)

当我扩展"培训时,它首先出现了。数据集从10个图像到100个。解释器似乎告诉我,我不能对这些数据点执行任何坐标操作,因为其中一个坐标对缺少一个值。我无法与之争辩。不幸的是,我的工作没有完全成功。我试图插入一个if条件,后跟一个continue语句(即,如果这个特定的坐标出现,它应该从循环的顶部继续)。口译员并不喜欢这个想法,而是喋喋不休地谈论那句话的真实性并没有像我想象的那样干脆。它建议我尝试a.any()或a.all()。我查看了两者的例子,并尝试将有问题的坐标对放在括号中,代替" a。"这两种方法都让我无处可去。我不知道任何类似于我在C中使用的函数的Python函数,以排除不符合特定条件的输入。关于类似问题的其他答案建议改变一个人使用的数学,但我被告知这是我要继续进行的,所以我把它看作是一个错误处理问题。

有没有人对如何处理这个问题有任何见解?任何想法将不胜感激!

以下是代码:

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

digits = datasets.load_digits()
#print the 0th image in the image database as an integer matrix
print(digits.images[0])
#plot the 0th image in the database assigning each pixel an intensity of black
plt.figure()
plt.imshow(digits.images[0], cmap = plt.cm.gray_r, interpolation = 'nearest')
plt.show()
#create training subsets of images and targets(labels)
X_train = digits.images[0:1000]
Y_train = digits.target[0:1000]
#pick a test point from images (345)
X_test = digits.images[345]
#view test data point
plt.figure()
plt.imshow(digits.images[345], cmap = plt.cm.gray_r, interpolation = 'nearest')
plt.show()
#distance
def dist(x, y):
    return np.sqrt(np.sum((x - y)**2))

#expand set of test data
num = len(X_train)
no_errors = 0
distance = np.zeros(num)
for j in range(1697, 1797):
    X_test = digits.data[j]
    for i in range(num):
        distance[i] = dist(X_train[i], X_test)
    min_index = np.argmin(distance)
    if Y_train[min_index] != digits.target[j]:
        no_errors += 1
print(no_errors)

1 个答案:

答案 0 :(得分:1)

您需要告诉我们错误发生的位置以及一些错误堆栈。

然后,您需要确定导致问题的阵列,并检查它们的形状。实际上错误告诉我们。一个操作数是8x8 2d阵列。另一个具有相同数量的元素但具有1d形状。您可能必须将一些变量追溯到您自己的代码。

只是为了说明问题:

In [381]: x = np.ones((8,8),int)
In [384]: y = np.arange(64)
In [385]: x*y
...
ValueError: operands could not be broadcast together with shapes (8,8) (64,) 
In [386]: x[:] = y
...
ValueError: could not broadcast input array from shape (64) into shape (8,8)

由于2个数组具有相同数量的元素,因此修复可能涉及重塑其中一个:

In [387]: x.ravel() + y
Out[387]: 
array([ 1,  2,  3,  4,  5, ... 64])

x-y.reshape(8,8)

我的基本观点是,您需要了解阵列形状的含义,以及不同形状的阵列如何一起使用。你不会四处走动。错误,你修复了输入,所以他们正在广播'兼容。

我不认为问题与特定元素的价值有关。

尝试在truth value上下文中测试数组时发生if错误。 if期望一个简单的True或False,而不是True / False值的数组。

In [389]: if x>0:print('yes')
....
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()