Py学习  »  机器学习算法

值错误:所有输入数组必须具有相同的形状(机器学习)

SpaceMonkey • 4 年前 • 602 次点击  

我的一个机器学习作业有问题。我们被要求使用机器学习来估计给定图像的个体的年龄。给出了28360幅列车图像和7090幅试验图像的数据集。

我遇到的问题是我的代码片段3 HERE :) 特别是,我得到了 ValueError: all input arrays must have the same shape . 就像我上面提到的,我的列车数据集的大小是28360。运行程序后,从 temp.append(img) 我能找到那个地方 print(len(temp)) 又给了我28360。也许我不太清楚到底是什么 np.stack(temp) 是在做还是如何工作,但是我的初始数组和最终数组的大小似乎是相同的,所以为什么会有问题呢?

当被问及这个问题时,我被告知这个问题不一定与我的 temp 但是我可能会碰到一个和其他图片大小不一样的图片。一个或多个包含的调整大小的图像(数组)具有不同的形状,可能是因为调整大小失败或图像丢失或其他原因。如果是这样的话,在一个28360张图片的数据集中,我怎样才能发现哪些是不同的,为什么我可以修复它们或者删除它们?这真的是个问题吗,或者是别的什么问题?

任何人,请帮忙。我做错什么了?如有任何意见/建议,将不胜感激。提前谢谢你。干杯,祝你好运!D

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39723
 
602 次点击  
文章 [ 1 ]  |  最新文章 4 年前
T. Kelher
Reply   •   1 楼
T. Kelher    5 年前

你知道这个问题,有些图片是一个痛苦,你必须调试我猜。每次都试着执行np.stack(),并找出出错的地方。当堆栈不再工作时,将打印所有图像的形状,这可能会让您了解出了什么问题。因为我不能复制它,所以没法再继续了。堆栈将所有图像连接到每个图像的顶部,但每个图像的形状必须相同。

for image_name in train.Id:
    img_path = os.path.join(data_dir, 'train', img_name)
    img = imageio.imread(img_path)
    img = skimage.transform.resize(img, (32, 32), mode='constant')
    img = img.astype('float32') # this will help us in later stage
    temp.append(img)
    try:
        train_x = np.stack(temp)
    except ValueError:
        [print(im.shape) for im in temp]
        break

为了让您更好地使用np.stack,请考虑以下代码:

tmp = [np.zeros((400,400,3)), np.zeros((400,400,3))]
print(np.stack(tmp).shape)
>>> (2, 400, 400, 3)

tmp = [np.zeros((400,400,3)), np.zeros((400,400))]
print(np.stack(tmp).shape)
>>> ValueError: all input arrays must have the same shape

在第一个示例中,我有一个列表,其中包含两个具有完全相同形状的三维数组。numpy将它们堆叠在一起并创建一个新维度,通常称为批处理大小。在第二个例子中,我在列表中有一个3d和一个2d数组,当你尝试用不同的形状(400,400,3)和(400,400)堆叠两个数组时,你会得到你提到的valueerror。

我还冒昧地看了一眼 here
在报税表上,您可以看到以下信息:

img_u数组:ndarray 不同的色带/通道存储在三维中,使得灰度图像是mxn、rgb图像mxnx3和rgb a图像mxnx4。

我感觉你的一些图像被读取为mxnx4数组而不是mxnx3

希望我帮了点忙,可以多问我一些。

编辑

for image_name in train.Id:
    img_path = os.path.join(data_dir, 'train', img_name)
    img = imageio.imread(img_path)
    img = skimage.transform.resize(img, (32, 32), mode='constant')
    img = img.astype('float32') # this will help us in later stage
    if len(img.shape) == 3 and img.shape[-1] == 3  # only append if 3D and last dimension is a 3, standing for RGB
        temp.append(img)
train_x = np.stack(temp)