【问题标题】:ValueError: All of the arrays in `x` should have the same length. Found a pair with: len(x[0]) = 97, len(x[?]) = 205ValueError: `x` 中的所有数组都应该具有相同的长度。找到一对: len(x[0]) = 97, len(x[?]) = 205
【发布时间】:2021-04-20 07:49:02
【问题描述】:

已经检查了this post,但答案没有帮助。

我有以下代码:

LABELS = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

data = []
labels = []

num_classes = 10
for i in range(num_classes):

    filenames = glob.glob(str(i) + '_*.png')

    for j in range(len(filenames)):
        im_gbr = cv2.imread(filenames[j])
        im = cv2.cvtColor(im_gbr, cv2.COLOR_BGR2RGB)

        data.append(im)
        labels.append(i)

# Normalise
x_min = np.min(data[0], axis=tuple(range(data[0].ndim-1)), keepdims=True)
x_max = np.max(data[0], axis=tuple(range(data[0].ndim-1)), keepdims=True)
data[0] = (data[0] - x_min)/ (x_max - x_min)

lb = LabelBinarizer()
labels = lb.fit_transform(labels)

(trainX, testX, trainY, testY) = train_test_split(data, labels,
                                                  test_size=0.33, stratify=labels, random_state=42)

# construct the training image generator for data augmentation
aug = ImageDataGenerator(rotation_range=20, zoom_range=0.15,
                         width_shift_range=0.2, height_shift_range=0.2, shear_range=0.15,
                         horizontal_flip=True, fill_mode="nearest")

# initialize the optimizer and model
EPOCH = 100
opt = Adam(lr=1e-4, decay=1e-4 / EPOCH)
model = StridedNet.build(width=96, height=96, depth=3,
                         classes=len(lb.classes_), reg=l2(0.0005))
model.compile(loss="categorical_crossentropy", optimizer=opt,
              metrics=["accuracy"])
# train the network

H = model.fit(x=aug.flow(trainX, trainY, batch_size=32),
              validation_data=(testX, testY), steps_per_epoch=len(trainX) // 32,
              epochs=EPOCH)

还有:

len(trainX) = 66

len(testX) = 33

len(trainY) = 66

len(testY) = 33

当我运行代码时,我收到以下错误:

ValueError: All of the arrays in `x` should have the same length. Found a pair with: len(x[0]) = 97, len(x[?]) = 205

错误对应x=aug.flow(trainX, trainY, batch_size=32)

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    我相信你需要让你所有的图片都一样大小,所以之后

    im = cv2.cvtColor(im_gbr, cv2.COLOR_BGR2RGB)
    # add the code
    height=96     # set your desired image height in pixels
    width= 96      # set your desired image width in pixels
    im = cv2.resize(im, (width, height))
    

    不确定您为什么要进行标准化。您可以在图像数据生成器中添加 rescale=1/255。当你丢失时,你正在使用 categorical_cross 熵。我认为如果是这种情况,您应该使用 lb=OneHotEncoder(sparse=False)。

    【讨论】:

    • 我在循环中添加了调整大小,但随后出现此错误:ValueError: 'x' (images tensor) and 'y' (labels) should have the same length. Found: x.shape = (128, 128, 3), y.shape = (66, 10)
    猜你喜欢
    • 1970-01-01
    • 2020-12-15
    • 2020-05-13
    • 2016-05-16
    • 1970-01-01
    • 2021-12-07
    • 2022-06-15
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多