【问题标题】:Keras Error: Error when checking model target: the list of Numpy arrays that you are passing to your model is not the size the model expectedKeras 错误:检查模型目标时出错:您传递给模型的 Numpy 数组列表不是模型预期的大小
【发布时间】:2022-05-10 00:44:03
【问题描述】:

我正在关注 https://www.tensorflow.org/tutorials/keras/basic_classification 以解决 Kaggle 挑战。

但是,我不明白应该向 fit 函数输入什么样的数据。

我将训练数据集拆分为X_trainy_trainX_testy_testX_train 的形状为 (13125, 32, 32, 3)

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(32, 32, 3)),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer='adam', 
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(X_train, y_train, epochs=5)

我得到一个错误:

检查模型目标时出错:您传递给模型的 Numpy 数组列表不是模型预期的大小。预计会看到 1 个数组,但得到了以下 13125 个数组的列表:

更新:

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(32,32,3)),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer='adam', 
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])


X_train_stack = np.vstack(X_train)
model.fit(X_train_stack, y_train, epochs=5)

我遇到了一个错误:

检查输入时出错:预期 flatten_7_input 有 4 个维度,但得到的数组形状为 (420000, 32, 3)

#read in training set
train_img = []
train_lb = []
for i in range(len(cactus_label)):
    row = cactus_label.iloc[i]
    fileName = row['id']
    train_lb.append(row['has_cactus'])
    path = "../input/train/train/{}".format(fileName)
    im = mpimg.imread(path)
    train_img.append(im)

X_train, X_test, y_train, y_test = train_test_split(train_img, train_lb) 
X_train = np.array(X_train)
X_test = np.array(X_test)

【问题讨论】:

  • 你能补充一下你是如何创建X_train的吗,看来问题就在那里。
  • 请注意,我从 vstack() 更改为 stack()

标签: python tensorflow machine-learning keras deep-learning


【解决方案1】:

您需要传递 numpy 数组,但您传递的是一个 numpy 数组列表。使用 np.stack() 从 numpy 数组列表中创建单个 numpy 数组:

X_train = np.stack(X_train, axis=0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 2021-02-18
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多