The below code is recipe generation code from model. I’m new to the python and don’t know much about ML, It a ingredient-to-recipe generation Api.
STOP_WORD_TITLE = '???? '
STOP_WORD_INGREDIENTS = 'n????nn'
STOP_WORD_INSTRUCTIONS = 'n????nn'
def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
model = tf.keras.Sequential([
tf.keras.layers.Input(batch_shape=(batch_size, None)), # Specify batch size here
tf.keras.layers.Embedding(vocab_size, embedding_dim),
tf.keras.layers.LSTM(rnn_units, return_sequences=True, stateful=True, recurrent_initializer='glorot_uniform'),
tf.keras.layers.Dense(vocab_size)
])
return model
## Loading model into the architecture
simplified_batch_size = 1
filepath_of_trained_model = "/home/talha/StudioProjects/flutterxflask/meri api/Model/Model.h5"
VOCABULARY_SIZE = 176
model_simplified = build_model(VOCABULARY_SIZE, 256, 1024, simplified_batch_size)
model_simplified.load_weights(filepath_of_trained_model)
model_simplified.build(tf.TensorShape([simplified_batch_size, None]))
model_simplified.summary()
tokenizer = tf.keras.preprocessing.text.Tokenizer(
char_level=True,
filters='',
lower=False,
split=''
)
# Stop word is not a part of recipes, but tokenizer must know about it as well.
STOP_SIGN = '␣'
tokenizer.fit_on_texts([STOP_SIGN])
tokenizer.get_config()
def generate_text(model, start_string, num_generate = 1000, temperature=1.0):
# Evaluation step (generating text using the learned model)
padded_start_string = STOP_WORD_TITLE + start_string
# Converting our start string to numbers (vectorizing).
input_indices = np.array(tokenizer.texts_to_sequences([padded_start_string])).flatten()
# Empty string to store our results.
text_generated = []
# Here batch size == 1.
# model.reset_states()
for char_index in range(num_generate):
input_indices = np.expand_dims(input_indices, 0)
print(f"Input shape: {input_indices.shape}")
predictions = model(input_indices)
# remove the batch dimension
predictions = tf.squeeze(predictions, 0)
print(f"Predictions shape: {predictions.shape}")
# Using a categorical distribution to predict the character returned by the model.
predictions = predictions / temperature
predicted_id = tf.random.categorical(
predictions,
num_samples=1
)[-1, 0].numpy()
# We pass the predicted character as the next input to the model
# along with the previous hidden state.
# input_indices = np.array[predicted_id]
# input_indices = tf.expand_dims([predicted_id],0)
input_indices = np.expand_dims(np.array([predicted_id]), 0)
next_character = tokenizer.sequences_to_texts(input_indices.numpy())[0]
text_generated.append(next_character)
return (padded_start_string + ''.join(text_generated))
I am trying to generate recipes from the model, however they are certain problems i’m facing in this.
The error im recieving is this
File "/home/talha/anaconda3/lib/python3.11/site-packages/flask/app.py", line 2529, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/talha/anaconda3/lib/python3.11/site-packages/flask/app.py", line 1825, in full_dispatch_request
rv = self.handle_user_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/talha/anaconda3/lib/python3.11/site-packages/flask/app.py", line 1823, in full_dispatch_request
rv = self.dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^
File "/home/talha/anaconda3/lib/python3.11/site-packages/flask/app.py", line 1799, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/talha/StudioProjects/flutterxflask/meri api/original", line 245, in home
ans = generate_combinations(model_simplified, ingredients_list)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/talha/StudioProjects/flutterxflask/meri api/original", line 145, in generate_combinations
generated_text = generate_text(
^^^^^^^^^^^^^^
File "/home/talha/StudioProjects/flutterxflask/meri api/original", line 79, in generate_text
predictions = model(input_indices)
^^^^^^^^^^^^^^^^^^^^
File "/home/talha/anaconda3/lib/python3.11/site-packages/keras/src/utils/traceback_utils.py", line 122, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/home/talha/anaconda3/lib/python3.11/site-packages/tensorflow/python/framework/ops.py", line 5983, in raise_from_not_ok_status
raise core._status_to_exception(e) from None # pylint: disable=protected-access
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tensorflow.python.framework.errors_impl.InvalidArgumentError: Exception encountered when calling LSTM.call().
{{function_node __wrapped__StridedSlice_device_/job:localhost/replica:0/task:0/device:CPU:0}} slice index 0 of dimension 1 out of bounds. [Op:StridedSlice] name: sequential/lstm/strided_slice/
Arguments received by LSTM.call():
• sequences=tf.Tensor(shape=(1, 0, 256), dtype=float32)
• initial_state=None
• mask=None
• training=False
127.0.0.1 - - [28/May/2024 12:28:52] "POST /ingredient HTTP/1.1" 500 -
Sometimes i also got tensor input shape error
New contributor
Talha Rauf is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.