简体   繁体   中英

AttributeError: 'Dimension' object has no attribute 'log10' while using Keras Sequential Model.fit

I am using a simple Keras Sequential Model with CNN, on MNIST Data. I could Build the Model but when I run model.fit , I encounter the error, AttributeError: 'Dimension' object has no attribute 'log10' . Below mentioned is my code. Googled it but couldn't find the solution.

Below mentioned is the complete code. TF Version is 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)

Stack Trace of Error is shown below:

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'

Thank you in advance for your help.

Error is coming because your steps_per_epoch has datatype Dimension and not integer.

steps_per_epoch = X_train_reshaped.shape[0]//512
type(steps_per_epoch)
# output: tensorflow.python.framework.tensor_shape.Dimension

To change your shape to integer try this:

steps_per_epoch = X_train_reshaped.shape[0].value//512

我将尝试降级为TF 1.14,以查看错误是否仍然存在。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM