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

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

Related

Google colab shows error in "tutorial_deep_learning_basics.ipynb"

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()

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.

keras.layers.TimeDistributed with Huggingface Transformer gives NotImplementedError

I wanted to apply Bert on a sequence of sentences in the following manner, but I am getting a NotImplementedError
How to reproduce :
import tensorflow as tf
from transformers import BertTokenizer, TFBertModel
inputs = tf.keras.Input(shape=(50, 64), dtype='int32')
model = TFBertModel.from_pretrained('bert-base-uncased')
outputs = tf.keras.layers.TimeDistributed(model)(inputs)
NotImplementedError Traceback (most recent call last)
<ipython-input-5-631f3cd2e8b2> in <module>
----> 1 outputs = tf.keras.layers.TimeDistributed(model)(inputs)
Whereas the code would work fine for
inputs = tf.keras.Input(shape=(10, 128, 128, 3))
conv_2d_layer = tf.keras.layers.Conv2D(64, (3, 3))
outputs = tf.keras.layers.TimeDistributed(conv_2d_layer)(inputs)
Is there anything I am missing here?

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

Trying to implement recurrent network with tf.scan()

I am trying to implement a recurrent state tensor using tf.scan. The code I have at the moment is this:
import tensorflow as tf
import math
import numpy as np
INPUTS = 10
HIDDEN_1 = 20
BATCH_SIZE = 3
def iterate_state(prev_state_tuple, input):
with tf.name_scope('h1'):
weights = tf.get_variable('W', shape=[INPUTS, HIDDEN_1], initializer=tf.truncated_normal_initializer(stddev=1.0 / math.sqrt(float(INPUTS))))
biases = tf.get_variable('bias', shape=[HIDDEN_1], initializer=tf.constant_initializer(0.0))
matmuladd = tf.matmul(inputs, weights) + biases
unpacked_state, unpacked_out = tf.split(0,2,prev_state_tuple)
prev_state = unpacked_state
state = 0.9* prev_state + 0.1*matmuladd
output = tf.nn.relu(state)
return tf.concat(0,[state, output])
def data_iter():
while True:
idxs = np.random.rand(BATCH_SIZE, INPUTS)
yield idxs
with tf.Graph().as_default():
inputs = tf.placeholder(tf.float32, shape=(BATCH_SIZE, INPUTS))
with tf.variable_scope('states'):
initial_state = tf.zeros([HIDDEN_1],
name='initial_state')
initial_out = tf.zeros([HIDDEN_1],
name='initial_out')
concat_tensor = tf.concat(0,[initial_state, initial_out])
states, output = tf.scan(iterate_state, inputs,
initializer=concat_tensor, name='states')
sess = tf.Session()
# Run the Op to initialize the variables.
sess.run(tf.initialize_all_variables())
iter_ = data_iter()
for i in xrange(0, 2):
print ("iteration: ",i)
input_data = iter_.next()
out,st = sess.run([output,states], feed_dict={ inputs: input_data})
However, I get this error when running this:
Traceback (most recent call last):
File "cycles_in_graphs_with_scan.py", line 37, in <module>
initializer=concat_tensor, name='states')
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 442, in __iter__
raise TypeError("'Tensor' object is not iterable.")
TypeError: 'Tensor' object is not iterable.
(tensorflow)charlesq#Leviathan ~/projects/stuff $ python cycles_in_graphs_with_scan.py
Traceback (most recent call last):
File "cycles_in_graphs_with_scan.py", line 37, in <module>
initializer=concat_tensor, name='states')
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 442, in __iter__
raise TypeError("'Tensor' object is not iterable.")
TypeError: 'Tensor' object is not iterable.
I've already tried with pack/unpack and concat/split but I get this same error.
Any ideas how to solve this problem?
You're getting an error because tf.scan() returns a single tf.Tensor, so the line:
states, output = tf.scan(...)
...cannot destructure (unpack) the tensor returned from tf.scan() into two values (states and outputs). Effectively, the code is trying to treat the result of tf.scan() as a list of length 2, and assign the first element to states and the second element to output, but—unlike a Python list or tuple—tf.Tensor does not support this.
Instead you need to extract the values from the result of tf.scan() manually. For example, using tf.split():
scan_result = tf.scan(...)
# Assumes values are packed together along `split_dim`.
states, output = tf.split(split_dim, 2, scan_result)
Alternatively, you could use tf.slice() or tf.unpack() to extract the relevant states and output values.