Keras model.fit() 需要很长时间并且没有显示进度条

问题描述

我正在解决手写数字问题。希望我的代码不言自明的。

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
import csv
import numpy as np



with open('train.csv') as f:
    reader = csv.reader(f)
    contents = list(reader)



labels = np.array(contents[0][1:])
labels = np.reshape(labels,(28,28,1))


numbers = []
shape = np.shape(contents)
num_inputs = shape[1]
num_samples = shape[0]
for i in np.arange(1,num_samples):
    pixels = contents[i][1:]
    pixels = np.array(pixels,dtype = int)
    pixels = np.reshape(pixels,1))
    #pixels = to_categorical(pixels)
    pixels = pixels / 255
    numbers.append(pixels)

num_hidden_layer = round(2/3 * num_inputs + 10)



model = tf.keras.models.Sequential([
    tf.keras.layers.MaxPooling2D(pool_size=(4,4),input_shape=(28,1)),tf.keras.layers.Flatten(),tf.keras.layers.Dense(num_hidden_layer,activation = 'relu'),tf.keras.layers.Dense(10,activation = 'softmax')
])


model.summary()



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


model.fit(numbers,labels,epochs=3,verbose = 1)

numbers 的形状为 (42000,1)labels 的形状为 (42000,1)。我的 model.summary 的扁平化输入维度只有 49,总共有 31,990 个可训练参数。尽管如此,我的 model.fit() 只是永远运行,完全没有显示。我什至进一步尝试了 maxpooling,但一无所获。为什么它什么都不做?我有 verbose = 1 并且我还没有看到进度条。我怎样才能让它运行?

更新:

我只是让它运行,它最终停止了:ValueError: Layer sequential_1 expects 1 input(s),but it received 42000 input tensors.

解决方法

我很确定它不起作用,因为您的标签值与您的模型定义不兼容。你的标签里有什么?模型标签的 28x28 似乎是错误的。您正在使用 sparse_categorical_crossentropy,它需要一个整数作为一个示例。该单个整数将指向 softmax 输出中的正确标签。

,

标签应该只有一维,对吗?必须是整数数组。