![](/img/trans.png)
[英]Keras : AttributeError: 'int' object has no attribute 'ndim' when using model.fit
[英]AttributeError: 'Dimension' object has no attribute 'log10' while using Keras Sequential Model.fit
我在 MNIST 數據上使用帶有 CNN 的簡單 Keras 序列模型。 我可以構建模型,但是當我運行model.fit
,我遇到了錯誤AttributeError: 'Dimension' object has no attribute 'log10'
。 下面提到的是我的代碼。 谷歌搜索但找不到解決方案。
下面提到的是完整的代碼。 TF 版本是 1.15。
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
from io import open
# Common imports
import numpy as np
import os
import tensorflow as tf
from tensorflow.keras.layers import Input, Conv2D, MaxPool2D, Dense, Dropout, Flatten
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
height = 28
width = 28
channels = 1
n_inputs = height * width
conv1_fmaps = 32
conv1_ksize = 3
conv1_stride = 1
conv1_pad = "SAME"
conv2_fmaps = 64
conv2_ksize = 3
conv2_stride = 2
conv2_pad = "SAME"
pool3_fmaps = conv2_fmaps
n_fc1 = 64
n_outputs = 10
with tf.name_scope("inputs"):
X = tf.placeholder(tf.float32, shape=[None, n_inputs], name="X")
X_reshaped = tf.reshape(X, shape=[-1, height, width, channels])
y = tf.placeholder(tf.int32, shape=[None], name="y")
cnn_model = Sequential()
cnn_model.add(Conv2D(filters=conv1_fmaps, kernel_size=conv1_ksize,
strides=conv1_stride, padding=conv1_pad,
activation=tf.nn.relu, input_shape=(height, width, channels),
data_format='channels_last'))
cnn_model.add(MaxPool2D(pool_size = (2,2), strides= (2,2), padding="VALID"))
cnn_model.add(Dropout(0.25))
cnn_model.add(Flatten())
cnn_model.add(Dense(units = 32, activation = 'relu'))
cnn_model.add(Dense(units = 10, activation = 'sigmoid'))
cnn_model.summary()
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()
X_train = X_train.astype(np.float32).reshape(-1, 28*28) / 255.0
X_train_reshaped = tf.reshape(X_train, shape=[-1, height, width, channels])
X_test = X_test.astype(np.float32).reshape(-1, 28*28) / 255.0
X_test_reshaped = tf.reshape(X_test, shape=[-1, height, width, channels])
#y_train = y_train.astype(np.int32)
y_train = tf.cast(y_train, dtype = tf.int32)
#y_test = y_test.astype(np.int32)
y_test = tf.cast(y_test, dtype = tf.int32)
cnn_model.compile(loss ='sparse_categorical_crossentropy', optimizer=Adam(lr=0.001),metrics =['accuracy'])
steps_per_epoch = X_train_reshaped.shape[0]//512
steps_per_epoch
epochs = 50
history = cnn_model.fit(x = X_train_reshaped,
y = y_train,
batch_size = 512,
epochs = 5,
verbose = 1, validation_data = (X_test_reshaped, y_test),
validation_steps = 10, steps_per_epoch=steps_per_epoch)
錯誤堆棧跟蹤如下所示:
Train on 117 samples, validate on 10000 samples
Epoch 1/5
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-13-89dd7568f671> in <module>
6 epochs = 5,
7 verbose = 1, validation_data = (X_test_reshaped, y_test),
----> 8 validation_steps = 10, steps_per_epoch=steps_per_epoch)
~/anaconda3/envs/TF_PY_36/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
725 max_queue_size=max_queue_size,
726 workers=workers,
--> 727 use_multiprocessing=use_multiprocessing)
728
729 def evaluate(self,
~/anaconda3/envs/TF_PY_36/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_arrays.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, **kwargs)
673 validation_steps=validation_steps,
674 validation_freq=validation_freq,
--> 675 steps_name='steps_per_epoch')
676
677 def evaluate(self,
~/anaconda3/envs/TF_PY_36/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_arrays.py in model_iteration(model, inputs, targets, sample_weights, batch_size, epochs, verbose, callbacks, val_inputs, val_targets, val_sample_weights, shuffle, initial_epoch, steps_per_epoch, validation_steps, validation_freq, mode, validation_in_fit, prepared_feed_values_from_dataset, steps_name, **kwargs)
347 batch_logs = cbks.make_logs(model, batch_logs, batch_outs, mode)
348 callbacks._call_batch_hook(mode, 'end', step, batch_logs)
--> 349 progbar.on_batch_end(step, batch_logs)
350 step += 1
351
~/anaconda3/envs/TF_PY_36/lib/python3.6/site-packages/tensorflow_core/python/keras/callbacks.py in on_batch_end(self, batch, logs)
759 # will be handled by on_epoch_end.
760 if self.verbose and (self.target is None or self.seen < self.target):
--> 761 self.progbar.update(self.seen, self.log_values)
762
763 def on_epoch_end(self, epoch, logs=None):
~/anaconda3/envs/TF_PY_36/lib/python3.6/site-packages/tensorflow_core/python/keras/utils/generic_utils.py in update(self, current, values)
393
394 if self.target is not None:
--> 395 numdigits = int(np.log10(self.target)) + 1
396 bar = ('%' + str(numdigits) + 'd/%d [') % (current, self.target)
397 prog = float(current) / self.target
AttributeError: 'Dimension' object has no attribute 'log10'
預先感謝您的幫助。
錯誤即將到來,因為您的steps_per_epoch
具有數據類型Dimension
而不是整數。
steps_per_epoch = X_train_reshaped.shape[0]//512
type(steps_per_epoch)
# output: tensorflow.python.framework.tensor_shape.Dimension
要將您的形狀更改為整數,請嘗試以下操作:
steps_per_epoch = X_train_reshaped.shape[0].value//512
我將嘗試降級為TF 1.14,以查看錯誤是否仍然存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.