Google colab shows error in "tutorial_deep_learning_basics.ipynb" - google-colaboratory

AttributeError Traceback (most recent call last)
in ()
5 print('.', end='')
6
----> 7 model = build_model()
8
9 early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=50)
in build_model()
5 ])
6
----> 7 model.compile(optimizer=tf.train.AdamOptimizer(),
8 loss='mse',
9 metrics=['mae', 'mse'])
AttributeError: module 'tensorflow._api.v2.train' has no attribute 'AdamOptimizer'
can you help resolve this?

Replace tf.train.AdamOptimizer() with tf.optimizers.Adam()

Related

How to solve this TensorFlow 'NameError: name 'tf' is not defined' error?

I tried to change the value of cap = cv2.VideoCapture(0) from 0 t0 3 and so on, so that I can try to access my external webcam, but I am unable. Following is the error I am facing in Jupyter notebook
NameError Traceback (most recent call last)
C:\Users\MIRZAT~1\AppData\Local\Temp/ipykernel_14320/2909626117.py in <module>
16 # np.mean(image_np, 2, keepdims=True), (1, 1, 3)).astype(np.uint8)
17
---> 18 input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 3), dtype=tf.float32)
19 detections, predictions_dict, shapes = detect_fn(input_tensor)
20
NameError: name 'tf' is not defined

TypeError: _variable_v2_call() got an unexpected keyword argument 'initializer' in tensor flow version=2.0.0

phi = tf.Variable("phi", shape=(k),dtype=tf.float32, initializer=tf.zeros_initializer(),
trainable=False)
TypeError Traceback (most recent call last)
<ipython-input-29-da3533caa9df> in <module>
3 dtype=tf.float32,
4 initializer=tf.zeros_initializer(),
----> 5 trainable=False)
6
~\Anaconda3\envs\tf\lib\site-packages\tensorflow_core\python\ops\variables.py in __call__(cls, *args, **kwargs)
258 return cls._variable_v1_call(*args, **kwargs)
259 elif cls is Variable:
--> 260 return cls._variable_v2_call(*args, **kwargs)
261 else:
262 return super(VariableMetaclass, cls).__call__(*args, **kwargs)
TypeError: _variable_v2_call() got an unexpected keyword argument 'initializer'
got an unexpected keyword argument 'initializer' in tensor flow version=2.0.0
Use this instead of tf.compat.v1.get_variable instead of tf.Variable. This works tensorflow 2.0 and above.
Use this (the initializer is deprecated in tensorflow 2.0):
phi = tf.Variable(
"phi",
shape=(k),
dtype=tf.float32,
tf.zeros_initializer(),
trainable=False)

AssertionError in keras while model Fitting

I am getting the following error:
Epoch 1/15
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-8-08aa5a9ec3b3> in <module>()
13 validation_data=[X_test, X_test],
14 callbacks=[keras_utils.TqdmProgressCallback()],
---> 15 verbose=0)
5 frames
/content/tqdm_utils.py in __init__(self, iterable, total, **kwargs)
10 self.iterable = list(iterable) if iterable is not None else None
11 self.total = len(self.iterable) if self.iterable is not None else total
---> 12 assert self.iterable is not None or self.total is not None
13 self.current_step = 0
14 self.print_frequency = max(self.total // 50, 1)
AssertionError:
While running the following piece of code:
s = reset_tf_session()
encoder, decoder = build_pca_autoencoder(IMG_SHAPE, code_size=32)
inp = L.Input(IMG_SHAPE)
code = encoder(inp)
reconstruction = decoder(code)
autoencoder = keras.models.Model(inputs=inp, outputs=reconstruction)
autoencoder.compile(loss='mse',optimizer='adamax' )
autoencoder.fit(x=X_train, y=X_train, epochs=15,
validation_data=[X_test, X_test],
callbacks=[keras_utils.TqdmProgressCallback()],
verbose=0)
I'm on Tensorflow version 1.15.2 and keras version 2.3.1
The code is from a coursera assignment which I am running on Google Colab.

AttributeError: 'KerasTPUModel' object has no attribute '_run_eagerly'

I am using tf.kaeras in google colab with python3.0 notebook and getting the error with the following code:
model = tf.keras.Model(inputs=[Inp], outputs=[output])
tpu_model = tf.contrib.tpu.keras_to_tpu_model(
model,
strategy=tf.contrib.tpu.TPUDistributionStrategy(
tf.contrib.cluster_resolver.TPUClusterResolver(
tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
)
)
tpu_model.fit(
train_input_fn,
steps_per_epoch = 60,
epochs=epochs)
And the error message is
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-11-d6a0cf977e09> in <module>()
2 train_input_fn,
3 steps_per_epoch = 60,
----> 4 epochs=epochs)
5
6 score = tpu_model.evaluate(x_test, y_test, verbose=0)
3 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in run_eagerly(self)
399 Boolean, whether the model should run eagerly.
400 """
--> 401 if self._run_eagerly is True and not context.executing_eagerly():
402 raise ValueError('You can only set `run_eagerly=True` if eager execution '
403 'is enabled.')
AttributeError: 'KerasTPUModel' object has no attribute '_run_eagerly'
INFO:
I get this error in google colab. Here is the Python and tensorflow version.
import sys
import tensorflow as tf
print("Python Version:", sys.version_info)
print("TensorFlow Version:", tf.__version__)
Python Version: sys.version_info(major=3, minor=6, micro=7, releaselevel='final', serial=0)
TensorFlow Version: 1.14.0-rc1

tensorflow lite toco python APl: NameError: "name 'tempfile' is not defined"

I ran the example from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/lite/toco/g3doc/python_api.md
import tensorflow as tf
img = tf.placeholder(name="img", dtype=tf.float32, shape=(1, 64, 64, 3))
val = img + tf.constant([1., 2., 3.]) + tf.constant([1., 4., 4.])
out = tf.identity(val, name="out")
with tf.Session() as sess:
tflite_model = tf.contrib.lite.toco_convert(sess.graph_def, [img], [out])
open("test.tflite", "wb").write(tflite_modeL)
but I got the error as "NameError: name 'tempfile' is not defined" in python3 and "NameError: global name 'tempfile' is not defined" in python2
NameError Traceback (most recent call last)
<ipython-input-21-24c36564faa4> in <module>()
5 out = tf.identity(val, name="out")
6 with tf.Session() as sess:
----> 7 tflite_model = tf.contrib.lite.toco_convert(sess.graph_def, [img], [out])
8 open("test.tflite", "wb").write(tflite_modeL)
python3.5/site-packages/tensorflow/contrib/lite/python/lite.py in toco_convert(input_data, input_tensors, output_tensors, inference_type, input_format, output_format, quantized_input_stats, drop_control_dependency)
196 data = toco_convert_protos(model.SerializeToString(),
197 toco.SerializeToString(),
--> 198 input_data.SerializeToString())
199 return data
200
python3.5/site-packages/tensorflow/contrib/lite/python/lite.py in toco_convert_protos(model_flags_str, toco_flags_str, input_data_str)
89 return _toco_convert_protos(model_flags_str, toco_flags_str, input_data_str)
90
---> 91 with tempfile.NamedTemporaryFile() as fp_toco, \
92 tempfile.NamedTemporaryFile() as fp_model, \
93 tempfile.NamedTemporaryFile() as fp_input, \
NameError: name 'tempfile' is not defined
How to make it work?
This issue has been fixed since TensorFlow 1.7 (see github bug).
I just successfully executed your snippet in the latest TensorFlow version 1.9:
import tensorflow as tf
img = tf.placeholder(name="img", dtype=tf.float32, shape=(1, 64, 64, 3))
val = img + tf.constant([1., 2., 3.]) + tf.constant([1., 4., 4.])
out = tf.identity(val, name="out")
with tf.Session() as sess:
tflite_model = tf.contrib.lite.toco_convert(sess.graph_def, [img], [out])
open("converteds_model.tflite", "wb").write(tflite_model)
The TFLite model converteds_model.tflite gets saved to file.