Build a recommendation system with TensorFlow and Keras - error - python

while trying to run this code:
https://colab.research.google.com/github/xei/recommender-system-tutorial/blob/main/recommender_system_tutorial.ipynb#scrollTo=l-8TmjXRTezi&uniqifier=1
I got an error while running the index method:
brute_force_layer = tfrs.layers.factorized_top_k.BruteForce(
movielens_retrieval_model.query_model
)
brute_force_layer.index(
candidates_corpus_dataset.batch(100).map(
movielens_retrieval_model.candidate_model
),
candidates_corpus_dataset
)
ValueError: Attempt to convert a value (<MapDataset element_spec=TensorSpec(shape=(None, 32), dtype=tf.float32, name=None)>) with an unsupported type (<class 'tensorflow.python.data.ops.dataset_ops.MapDataset'>) to a Tensor.
Thanks for your help.

Related

Tensorflow ValueError for ReinforceAgent

I see that Tensorflow support is pretty slim but I'll try anyway …
When running my agent:
optimizer = tf.keras.optimizers.Adam()
train_step_counter = tf.Variable(0)
tf_agent = reinforce_agent.ReinforceAgent(
train_py_env.time_step_spec(),
train_py_env.action_spec(),
actor_network=actor_net,
optimizer=optimizer,
normalize_returns=True,
train_step_counter=train_step_counter)
I get a ValueError from _make_gin_wrapper (Line 1605). The error text is:
Exception encountered when calling layer \"lambda_12\" (type Lambda).\n\nShapes (1, 9) and (9, 9) are incompatible\n\nCall arguments received by layer \"lambda_12\" (type Lambda):\n • inputs=tf.Tensor(shape=(1, 9), dtype=int32)\n • mask=None\n • training=None\n In call to configurable 'ReinforceAgent' (<class 'tf_agents.agents.reinforce.reinforce_agent.ReinforceAgent'>)"
So apparently some incompatibility with (1,9) and (9,9) shape. The environment is taken from https://towardsdatascience.com/creating-a-custom-environment-for-tensorflow-agent-tic-tac-toe-example-b66902f73059. It is TicTacToe on a [0,0,0,0,0,0,0,0,0]board, which has (9,)-shape, so I can see why there are 9's but I don't know which objects have (1,9) and (9,9) shapes or what I could do to get the agent running.

How can I change a tensor to NumPy?

I want to exchange Tensor a to a NumPy two-dimensional array for getting a heat map.
(Tensor(1, 64, 64, 1) -> numpy (64, 64))
I tried x.numpy(), but it doesn't work. The error message is this:
AttributeError: in user code: :187 call * x_np=x.numpy() /usr/local/lib/python3.7/dist packages/tensorflow/python/framework/ops.py:401 getattr self.getattribute(name) AttributeError: 'Tensor' object has no attribute 'numpy'
This is the tensor information and type of the tensor:
Tensor("ExpandDims:0", shape=(1, 64, 64, 1), dtype=float32)
<class 'tensorflow.python.framework.ops.Tensor'>
and I don't know what ExpandDims:0 means (what is this argv?).
Tensorflow:2.6.0
Numpy:1.21.2
I made the test code that has the same Tensor type, shape, and env, and it works.
What should I do?
import tensorflow as tf
import numpy
print(tf.__version__)
print(numpy.__version__)
a = tf.constant([[[[0.1]*1]*64]*64])
print(a)
print(a.numpy())

An error when declaring the variable placeholder

I am building sample Neural Network using Pycharm, tensorflow 2.4 and python v3.8.5. When Running this command:
X = tf.placeholder("float", [None, num_input]) #num_input is the sized of input vector
I get an error like this one:
raise TypeError("Error converting %s to a TensorShape: %s." % (arg_name, e))
TypeError: Error converting shape to a TensorShape: Dimension value must be integer or None or have an __index__ method, got value '8.0' with type '<class 'numpy.float64'>'.
What is the problem of that error? thanks in advance
This row (tf.placeholder) is enable for tensorflow 1, but you have installed tensorflow2. Disable Tf2 and run your backend on Tf1 .
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
X = tf.placeholder("float", [None, 8])
print(X)
<tf.Tensor 'Placeholder:0' shape=(?, 8) dtype=float32>

AttributeError: 'TensorSliceDataset' object has no attribute 'get_shape'

I'm trying to load images into a model using datasets. However, I keep getting an error that my tensor slices don't have the get_shape() attribute. I have confirmed that they don't by trying to call it within my code. What am I doing wrong?
I'm using:
Spyder 4.1.5 on Anaconda |
Keras 2.3.1 |
Tensorflow 2.1.0
# load dataset
dataset = h5py.File('3dshapes.h5', 'r')
print(dataset.keys())
images = dataset['images'] # array shape [480000,64,64,3], uint8 in range(256)
labels = dataset['labels'] # array shape [480000,6], float64
train_dataset = tf.data.Dataset.from_tensor_slices((images[1:10], labels[1:10]))
test_dataset = tf.data.Dataset.from_tensor_slices((images[10:20], labels[10:20]))
print("train_dataset", train_dataset)
print("test_dataset", test_dataset)
train_dataset <TensorSliceDataset shapes: ((64, 64, 3), (6,)), types:
(tf.uint8, tf.float64)>
test_dataset <TensorSliceDataset shapes: ((64, 64, 3), (6,)), types: (tf.uint8, tf.float64)>
File "C:\Users\Administration
User.conda\envs\Keras\lib\site-packages\tensorflow_core\python\keras\layers\convolutional.py",
line 192, in call
call_input_shape = inputs.get_shape()
AttributeError: 'TensorSliceDataset' object has no attribute
'get_shape'
Turns out I just needed to setup a new Python environment on Anaconda and install Tensorflow and Keras. My existing environment was already setup with these, but various other posts mentioned that doing this can help, and it did.

Error when trying to compile a keras model ValueError: Tensor conversion requested dtype int64 for Tensor with dtype float32

I am trying to make a speech recognizer using tensorflow and am getting this error that
ValueError: Tensor conversion requested dtype int64 for Tensor with
dtype float32: 'Tensor("loss_2/lambda_loss/ExpandDims:0", shape=(?,
1), dtype=float32)'
and
TypeError: Input 'y' of 'Mul' Op has type float32 that does not match
type int64 of argument 'x'.
Minimum Running Code where tensorflow is imported as tf
train_input_val = tf.keras.layers.Input(name='the_input', shape=[None,num_features], dtype='float32')
seq_len = tf.keras.layers.Input(name='input_length', shape=[1], dtype='int64')
y_pred = tf.keras.layers.Lambda(ctc_decode_func ,name = 'lambda')([train_input_val, seq_len])
model2 = tf.keras.Model(inputs=[train_input_val,seq_len],outputs=y_pred)
model2.compile(loss={'lambda': lambda y_true, y_pred: y_true}, optimizer='adam')
and ctc_decode_func is defined as
def ctc_decode_func(args):
y_pred, seq_len = args
y_pred,log_prob = tf.keras.backend.ctc_decode(y_pred, tf.squeeze(seq_len))
return y_pred
I tried casting everything to int64 , but still the error persisted. I dont Even know which part of lambda layer is throwing the error.
Please Help

Categories

Resources