我正在处理一个手写数字问题。希望我的代码足够自我解释。
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, (28,28,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,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, 28, 28, 1)
,而labels
的形状则是(42000, 28, 28, 1)
。来自我的model.summary
的平坦输入维度只有49,总共有31990个可训练参数。尽管如此,我的model.fit()
只是永远运行,完全没有显示任何内容。我甚至尝试过进一步的maxpooling,但一无所获。为什么它什么都不做?我有verbose = 1
,我还没有看到进度条。我该如何运行?
更新:
我只是让它运行,它最终停止了:ValueError: Layer sequential_1 expects 1 input(s), but it received 42000 input tensors.
我很确定它不起作用,因为您的标签值与模型定义不兼容。你的标签上有什么?28x28的型号标签似乎是错误的。您使用的是spare_categorical_crossentry,例如,它需要一个整数。这个整数将指向softmax输出中正确的标签。
标签应该只有一个维度,对吧?必须是一个整数数组。