Why TensorFlow throws this exception when loading a model that was normalized like this? - tensorflow

All latest versions from the very moment of this post.
tensorflow-gpu: 2.6.0
Python: 3.9.7
CUDA: 11.4.2
cuDNN: 8.2.4
As in the code below, when loading a model that was normalized by not passing arguments to Normalization() it throws an exception when that model is loaded by load_model(), however before loading the model I can use it without any apparent issues which makes you think it's all good since Normalization() did NOT complain and took care of the input shape. When loading a model that was normalized by Normalization(input_dim=5) it does NOT thrown any exception since a known shape is specified. That is weird I mean it should warn you that when normalizing it without passing arguments to Normalization() you should expect an exception when loading it.
I'm not sure if it's a bug so I'm posting it here before reporting a bug in the github section, maybe I'm missing to setup something.
Here's my code:
import numpy as np
import tensorflow as tf
def main():
train_data = np.array([[1, 2, 3, 4, 5]])
train_label = np.array([123])
# Uncomment this to load the model and comment the next model and normalizer related lines.
#model = tf.keras.models.load_model('AI/test.h5')
normalizer = tf.keras.layers.experimental.preprocessing.Normalization()
normalizer.adapt(train_data)
model = tf.keras.Sequential([normalizer, tf.keras.layers.Dense(units=1)])
model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.1), loss='mean_absolute_error')
model.fit(train_data, train_label, epochs=3000)
model.save('AI/test.h5')
unseen_data = np.array([[1, 2, 3, 4, 6]])
prediction = model.predict(unseen_data)
print(prediction)
if __name__ == "__main__":
main()
It throws the following exception:
Traceback (most recent call last):
File "E:\Backup\Desktop\tensorflow_test.py", line 30, in <module>
main()
File "E:\Backup\Desktop\tensorflow_test.py", line 11, in main
model = tf.keras.models.load_model('AI/test.h5')
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\saving\save.py", line 200, in load_model
return hdf5_format.load_model_from_hdf5(filepath, custom_objects,
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\saving\hdf5_format.py", line 180, in load_model_from_hdf5
model = model_config_lib.model_from_config(model_config,
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\saving\model_config.py", line 52, in model_from_config
return deserialize(config, custom_objects=custom_objects)
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\layers\serialization.py", line 208, in deserialize
return generic_utils.deserialize_keras_object(
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\utils\generic_utils.py", line 674, in deserialize_keras_object
deserialized_obj = cls.from_config(
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\sequential.py", line 434, in from_config
model.add(layer)
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\training\tracking\base.py", line 530, in _method_wrapper
result = method(self, *args, **kwargs)
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\sequential.py", line 217, in add
output_tensor = layer(self.outputs[0])
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\base_layer.py", line 976, in __call__
return self._functional_construction_call(inputs, args, kwargs,
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\base_layer.py", line 1114, in _functional_construction_call
outputs = self._keras_tensor_symbolic_call(
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\base_layer.py", line 848, in _keras_tensor_symbolic_call
return self._infer_output_signature(inputs, args, kwargs, input_masks)
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\base_layer.py", line 886, in _infer_output_signature
self._maybe_build(inputs)
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\base_layer.py", line 2659, in _maybe_build
self.build(input_shapes) # pylint:disable=not-callable
File "C:\Users\censored\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\layers\preprocessing\normalization.py", line 145, in build
raise ValueError(
ValueError: All `axis` values to be kept must have known shape. Got axis: (-1,), input shape: [None, None], with unknown axis at index: 1
Process finished with exit code 1

It looks like a bug.
Follow this link
if 'input_dim' in kwargs and 'input_shape' not in kwargs:
# Backwards compatibility: alias 'input_dim' to 'input_shape'.
kwargs['input_shape'] = (kwargs['input_dim'],)
if 'input_shape' in kwargs or 'batch_input_shape' in kwargs:
# In this case we will later create an input layer
# to insert before the current layer
if 'batch_input_shape' in kwargs:
batch_input_shape = tuple(kwargs['batch_input_shape'])
elif 'input_shape' in kwargs:
if 'batch_size' in kwargs:
batch_size = kwargs['batch_size']
else:
batch_size = None
batch_input_shape = (batch_size,) + tuple(kwargs['input_shape'])
self._batch_input_shape = batch_input_shape
The error occurs because the normalization could not get any shape information which would lead to self._input_batch_shape =(None, None).
But when loading model(deserialization), It would call build function which should have known shape in all axes.
# Sorted to avoid transposing axes.
self._keep_axis = sorted([d if d >= 0 else d + ndim for d in self.axis])
# All axes to be kept should have known shape.
for d in self._keep_axis:
if input_shape[d] is None:
raise ValueError(
'All `axis` values to be kept must have known shape. Got axis: {}, '
'input shape: {}, with unknown axis at index: {}'.format(
self.axis, input_shape, d))

Related

How to deal with incompatible shapes while trying to fit a model in Tensorflow Keras

So, I have done some modifications with the VGG16 neural network to make a linear-regression and classification model.
And at last I am writing the following code to compile and fit my data into the model to initiate training->
class Facetracker(Model):
# The initialization function-
def __init__(self,eyetracker,**kwargs):
super().__init__(**kwargs)
self.model = eyetracker #Instantiating the model
def compile(self,opt,classlosss,localization_loss,**kwargs):
super().compile(**kwargs)
self.classloss = class_loss
self.localization_loss = regress_loss
self.opt = optimizer
# Defining the training step
def train_step(self,batch,**kwargs):
X,y = batch #unpacking our data
with tf.GradientTape() as tape:
classes,coords = self.model(X,training=True)
batch_classloss = self.classloss(y[0],classes)
batch_localloss = self.localization_loss(tf.cast(y[1],tf.float32),coords)
# calculating total loss-
total_loss = batch_localloss+0.5*batch_classloss
grad = tape.gradient(total_loss,self.model.trainable_variables)
optimizer.apply_gradients(zip(grad,self.model.trainable_variables))
return{
"total_loss":total_loss,
"class_loss":batch_classloss,
"localilzation_loss":batch_localloss
}
def test_step(self,batch):
X,y = batch
classes,coords = self.model(X,training=False)
batch_classloss = self.classloss(y[0],classes)
batch_localloss = self.localization_loss(tf.cast(y[1],tf.float32),coords)
total_loss = batch_localloss+0.5*batch_classloss
return{
"total_loss": total_loss,
"class_loss": batch_classloss,
"localilzation_loss": batch_localloss
}
# def call(self, X, **kwargs):
# return self.model(X,**kwargs)
# Replacing the call function with a lambda function
lambda self,X,**kwargs: self.model(X,**kwargs)
# Subclassing our model-
print("Subclassing.....")
model = Facetracker(facetracker)
print("Compiling......")
model.compile(optimizer,classlosss=class_loss,localization_loss=localization_loss)
# Preparing the log directory
logdir="logdir"
tensorboard_callbacks = tf.keras.callbacks.TensorBoard(log_dir=logdir)
print("Fitting the model")
hist = model.fit(train.take(80),
epochs=16,
initial_epoch =8,
validation_data=val,
validation_steps =8,
validation_freq=2,
callbacks = [[tensorboard_callbacks]])
This includes the class prepared for training the model and the last few lines are subclassing the model and fitting the prepared data into the model.
The error I now get seems pretty hefty to me and it goes like this->
File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 535, in <module>
hist = model.fit(train.take(80),
File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\tensorflow\python\eager\execute.py", line 54, in quick_execute
tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:
Detected at node 'gradient_tape/sub_2/BroadcastGradientArgs' defined at (most recent call last):
File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 535, in <module>
hist = model.fit(train.take(80),
File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
return fn(*args, **kwargs)
File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1409, in fit
tmp_logs = self.train_function(iterator)
File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1051, in train_function
return step_function(self, iterator)
File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1040, in step_function
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\MarkATT\lib\site-packages\keras\engine\training.py", line 1030, in run_step
outputs = model.train_step(data)
File "C:\Users\Radhe Krishna\OneDrive\Documents\MarkATT\main.py", line 498, in train_step
grad = tape.gradient(total_loss,self.model.trainable_variables)
Node: 'gradient_tape/sub_2/BroadcastGradientArgs'
Incompatible shapes: [2,4] vs. [8]
[[{{node gradient_tape/sub_2/BroadcastGradientArgs}}]] [Op:__inference_train_function_22026]
It would be a great help if someone could examine this problem and help me get out of it. I have been quite struggling with it now.
Thanks in advance!!!
I has planned to initiate training with the code provided, but I firstly received an error for the call function and as I resolved it by converting it into lambda function- This issue of incompatible shapes came up. I tries to adjust the integers in the input data and batch related fields but nothing worked.

keras tape.gradient error: Input to reshape is a tensor with 1012 values, but the requested shape has 20240 [Op:Reshape]

i use the tape.gradient(g_loss, aa_mutator.trainable_variables) to calculate the gradient of a model called aa_mutator and got the error
File "/home/tialan/Data/gan/code/g.py", line 297, in <module>
grads_g = tape.gradient(g_loss, aa_mutator.trainable_variables)
File "/home/tialan/tf/lib/python3.7/site-packages/tensorflow/python/eager/backprop.py", line 1086, in gradient
unconnected_gradients=unconnected_gradients)
File "/home/tialan/tf/lib/python3.7/site-packages/tensorflow/python/eager/imperative_grad.py", line 77, in imperative_grad
compat.as_str(unconnected_gradients.value))
File "/home/tialan/tf/lib/python3.7/site-packages/tensorflow/python/eager/backprop.py", line 162, in _gradient_function
return grad_fn(mock_op, *out_grads)
File "/home/tialan/tf/lib/python3.7/site-packages/tensorflow/python/ops/array_grad.py", line 782, in _ReshapeGrad
_IndexedSlicesToTensorNoWarning(grad), array_ops.shape(op.inputs[0])),
File "/home/tialan/tf/lib/python3.7/site-packages/tensorflow/python/util/dispatch.py", line 201, in wrapper
return target(*args, **kwargs)
File "/home/tialan/tf/lib/python3.7/site-packages/tensorflow/python/ops/array_ops.py", line 195, in reshape
result = gen_array_ops.reshape(tensor, shape, name)
File "/home/tialan/tf/lib/python3.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 8368, in reshape
_ops.raise_from_not_ok_status(e, name)
File "/home/tialan/tf/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 6862, in raise_from_not_ok_status
six.raise_from(core._status_to_exception(e.code, message), None)
File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: Input to reshape is a tensor with 1012 values, but the requested shape has 20240 [Op:Reshape]
within the aa_mutator model i build a customized keras layer
class mutate_func_layer(layers.Layer):
def __init__(self):
super(mutate_func_layer, self).__init__()
def call(self, inputs):
Mut_pos_layer_out, input_pre, Mutation_3 = inputs
where = where_func(Mut_pos_layer_out)
return mutate_func(Mutation_3, where, input_pre)
with mutate_func defined as
#tf.custom_gradient
def mutate_func(x, where, input_pre):#(Mutation_3, where, input_pre): ## x = mutation 3
print('m3_in_mutate_func')
print(x.shape)
aa_aft = gather_nd_func(x, where)
print('m3_in_mutate_func')
print(aa_aft.shape)
aa_aft = K.argmax(aa_aft, axis=-1)
print('m3_in_mutate_func')
print(aa_aft.shape)
aa_aft = tf.reshape(aa_aft, [-1])
print('m3_in_mutate_func')
print(aa_aft.shape)
aa_aft = tf.cast(aa_aft, dtype=tf.float32)
print('m3_in_mutate_func')
print(aa_aft.shape)
aa_seq_out = tf.tensor_scatter_nd_update(input_pre, [where], [aa_aft])
print('m3_in_mutate_func')
print(aa_seq_out.shape)
def grad(upstream):
return upstream*1, upstream*1, upstream*1
the shape for layers in the mutate_func are printed as
m3_in_mutate_func
(1, 1012, 20)
m3_in_mutate_func
(675, 20)
m3_in_mutate_func
(675,)
m3_in_mutate_func
(675,)
m3_in_mutate_func
(675,)
m3_in_mutate_func
(1, 1012)
the model is able to predict given the input. just for fitting the error shows at the stage of tape.gradient. is the error raised due to the customized layer? Thanks for any help or suggestion

Data API Error : Cannot convert a symbolic Tensor (truediv:0) to a numpy array

I have 45000 images of size 224*224, stored as a numpy array. This array, called source_arr has shape 45000,224,224 and it fits in the memory.
I want to divide this array into train, test and validate array and pre-process (normalize and convert greyscale to 3 channels RGB) them using tf.data API.
I have written a pre process function like:
def pre_process(x):
#Zero centering the scaled dataset
x_norm = (x-mean_Rot_MIP)/Var_Rot_MIP
#Stack 3 channels
x_norm_3ch= np.stack((x_norm, x_norm, x_norm),axis=0)
print('Rotn MIP 3ch dim:', x_norm_3ch.shape) # (3, 224, 224)
#converting channel 1st to channel last move axis 1 to 3
x_norm_3ch = moveaxis(x_norm_3ch, 0,2)
print('Rotn MIP ch last dim: ',x_norm_3ch.shape) # (224, 224, 3)
return x_norm_3ch
X_train_cases_idx.idx contains the index of images from source_arr that are part of training data.
I have read the corresponding training images from source_arr in the dataset object like:
X_train = tf.data.Dataset.from_tensor_slices([source_arr[i] for i in X_train_cases_idx.idx])
And then I apply the pre_process function on the training images like
X_train = X_train.map(pre_process)
but I get the following error
Traceback (most recent call last):
File "<ipython-input-37-69aa131a6944>", line 1, in <module>
X_train = X_train.map(pre_process)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 1695, in map
return MapDataset(self, map_func, preserve_cardinality=True)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 4045, in __init__
use_legacy_function=use_legacy_function)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 3371, in __init__
self._function = wrapper_fn.get_concrete_function()
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 2939, in get_concrete_function
*args, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 2906, in _get_concrete_function_garbage_collected
graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 3213, in _maybe_define_function
graph_function = self._create_graph_function(args, kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 3075, in _create_graph_function
capture_by_value=self._capture_by_value),
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py", line 986, in func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 3364, in wrapper_fn
ret = _wrapper_helper(*args)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 3299, in _wrapper_helper
ret = autograph.tf_convert(func, ag_ctx)(*nested_args)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\autograph\impl\api.py", line 258, in wrapper
raise e.ag_error_metadata.to_exception(e)
NotImplementedError: in user code:
<ipython-input-2-746b4230fbd1>:58 pre_process *
x_norm_3ch= np.stack((x_norm, x_norm, x_norm),axis=1)
<__array_function__ internals>:6 stack **
C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\shape_base.py:419 stack
arrays = [asanyarray(arr) for arr in arrays]
C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\shape_base.py:419 <listcomp>
arrays = [asanyarray(arr) for arr in arrays]
C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\_asarray.py:138 asanyarray
return array(a, dtype, copy=False, order=order, subok=True)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py:848 __array__
" a NumPy call, which is not supported".format(self.name))
NotImplementedError: Cannot convert a symbolic Tensor (truediv:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported
What am I doing wrong, and how do I fix it?
I am using Tensorflow 2.0 with python 3.7 on windows 10
As the error message points out, you are trying to use NumPy functions to operate with TensorFlow tensors. Instead, you should use TensorFlow operations. This is equivalent to what you were trying to do:
def pre_process(x):
x_norm = (x - mean_Rot_MIP) / Var_Rot_MIP
# Stacking along the last dimension to avoid having to move channel axis
x_norm_3ch = tf.stack((x_norm, x_norm, x_norm), axis=-1)
return x_norm_3ch

Conv1D with data_format channels_first yields error on Keras

I am trying to define a basic ConvNet using one Conv1D operation as follows:
n_class = 10
# channels last (default)
input_shape = (100, 1)
inp = Input(shape=input_shape)
x = Conv1D(4, kernel_size=9, activation=activations.relu, padding='same')(inp)
x = MaxPool1D(pool_size=5)(x)
x = Flatten()(x)
out = Dense(n_class, activation='softmax')(x)
model = Model(inputs=inp, outputs=out)
and that works fine (which uses data_format='channels_last' as default). However, if, instead, I want to use data_format='channels_first':
# "channels_first" inputs with shape (batch, channels, length).
input_shape = (1, 100)
inp = Input(shape=input_shape)
x = Conv1D(4, kernel_size=9, activation=activations.relu, data_format='channels_first', padding='same')(inp)
x = MaxPool1D(pool_size=5, data_format='channels_first')(x)
x = Flatten()(x)
out = Dense(n_class, activation='softmax')(x)
model = Model(inputs=inp, outputs=out)
I get the following error when defining the Conv1D layer:
Traceback (most recent call last):
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1596, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 974, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/Users/edward/Desktop/baselines/cnn_mel.py", line 720, in <module>
model = get_1d_dummy_model(params_learn=params_learn, params_extract=params_extract)
File "/Users/edward/Desktop/baselines/architectures.py", line 71, in get_1d_dummy_model
x = Conv1D(4, kernel_size=9, activation=activations.relu, data_format='channels_first', padding='same')(inp)
File "/Users/edward/miniconda3/envs/baseline/lib/python3.6/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "/Users/edward/miniconda3/envs/baseline/lib/python3.6/site-packages/keras/layers/convolutional.py", line 337, in __init__
**kwargs)
TypeError: __init__() got multiple values for keyword argument 'data_format'
Any insight as to what is being done wrong? thanks!
It seems that you are not using the most recent code (not just most recent release). For Conv1D layer, data_format='channels_first' is not supported even in the most recent release 2.1.6. You will need to clone and use codes from the master branch. The support is added by this commit on 5/7/2018. The documentation is always synced to the master which can be confusing. The idea (from the Keras creator François Chollet) is that
versions only exist to force PyPI users to upgrade. They are not meaningful. You should be constantly synced to master.
You can find some old Keras documentation here.

Tensorflow tutorial estimator Failed to convert object of type <type 'dict'> to Tensor

I am running the tutorial code A Guide to TF Layers: Building a Convolutional Neural Network on API r.1.3
https://www.tensorflow.org/tutorials/layers
My code is here.
https://gist.github.com/Po-Hsuan-Huang/91e31d59fd3aa07f40272b75fe2a924d
The error shows:
runfile('/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py', wdir='/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST')
Extracting MNIST-data/train-images-idx3-ubyte.gz
Extracting MNIST-data/train-labels-idx1-ubyte.gz
Extracting MNIST-data/t10k-images-idx3-ubyte.gz
Extracting MNIST-data/t10k-labels-idx1-ubyte.gz
INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_save_checkpoints_secs': 600, '_session_config': None, '_keep_checkpoint_max': 5, '_tf_random_seed': 1, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_save_checkpoints_steps': None, '_model_dir': '/tmp/mnist_convnet_model', '_save_summary_steps': 100}
Traceback (most recent call last):
File "<ipython-input-1-c9b70e26f791>", line 1, in <module>
runfile('/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py', wdir='/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST')
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
builtins.execfile(filename, *where)
File "/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py", line 129, in <module>
main(None)
File "/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py", line 117, in main
hooks=[logging_hook])
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 241, in train
loss = self._train_model(input_fn=input_fn, hooks=hooks)
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 630, in _train_model
model_fn_lib.ModeKeys.TRAIN)
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 615, in _call_model_fn
model_fn_results = self._model_fn(features=features, **kwargs)
File "/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py", line 24, in cnn_model_fn
input_layer = tf.reshape(features, [-1, 28, 28, 1])
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 2619, in reshape
name=name)
File "/Users/pohsuanhuang/miniconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 493, in apply_op
raise err
TypeError: Failed to convert object of type <type 'dict'> to Tensor. Contents: {'x': <tf.Tensor 'random_shuffle_queue_DequeueMany:1' shape=(100, 784) dtype=float32>}. Consider casting elements to a supported type.
I traced down a little bit, and found the function estimator._call_input_fn() does not use parameter 'mode' at all, thus not able to create a tuple comprises features and labels. Is it the tutorial that needs to be modified, or there is some problem with this function. I don't understand why mode is unused here.
Thanks !
def _call_input_fn(self, input_fn, mode):
"""Calls the input function.
Args:
input_fn: The input function.
mode: ModeKeys
Returns:
Either features or (features, labels) where features and labels are:
features - `Tensor` or dictionary of string feature name to `Tensor`.
labels - `Tensor` or dictionary of `Tensor` with labels.
Raises:
ValueError: if input_fn takes invalid arguments.
"""
del mode # unused
input_fn_args = util.fn_args(input_fn)
kwargs = {}
if 'params' in input_fn_args:
kwargs['params'] = self.params
if 'config' in input_fn_args:
kwargs['config'] = self.config
with ops.device('/cpu:0'):
return input_fn(**kwargs)
Your gist doesn't actually contain any of your code... Either way, from your error message I think you have just mistranscribed a bit of code from the tutorial.
Your error log indicates you have
"/Users/pohsuanhuang/Documents/workspace/tensorflow_models/NMIST/cnn_mnist.py", line 24, in cnn_model_fn
input_layer = tf.reshape(features, [-1, 28, 28, 1])
Whereas the tutorial has:
input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])