【问题标题】:Getting Around "ValueError: operands could not be broadcast together"解决“ValueError:无法一起广播操作数”
【发布时间】:2017-01-11 19:48:06
【问题描述】:

下面的代码产生以下值错误。

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)

【问题讨论】:

    标签: python numpy error-handling scikit-learn


    【解决方案1】:

    您需要向我们展示错误发生的位置,以及一些错误堆栈。

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

    只是为了说明问题:

    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)

    我的基本观点是,您需要了解数组形状的含义,以及不同形状的数组如何一起使用。您不会“绕过”错误,而是修复输入以使其“广播”兼容。

    我认为问题不在于特定元素的值。

    当您尝试在if 上下文中测试数组时,会出现truth value 错误。 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()
    

    【讨论】:

    • 非常感谢。这里使用的导入模块对我来说很新,所以我会更仔细地考虑你的反应,玩一会儿,也许对它依赖的模块做更多的阅读(关注数组和广播规则),和看看我在哪里。非常感谢您的宝贵时间!
    • 您可能需要详细了解datasets 的性质,sklearns 为您提供。您可能需要搜索其他sklearn 问题。
    猜你喜欢
    • 2017-09-09
    • 2012-10-31
    • 2013-04-07
    • 2012-08-05
    • 2018-08-18
    • 2020-06-20
    • 2014-08-24
    • 2018-12-26
    • 2018-02-01
    相关资源
    最近更新 更多