tensorflow / tensorflow

An Open Source Machine Learning Framework for Everyone
https://tensorflow.org
Apache License 2.0
185.38k stars 74.17k forks source link

'Sequential' object has no attribute '_get_save_spec'. Did you mean: '_set_save_spec'? #71726

Closed Leli1024 closed 3 weeks ago

Leli1024 commented 1 month ago

Im using the latest version of tensorflow installed from PIP

I'm getting the error: File "/Users/andrewattard/Downloads/Foodity Dataset/main.py", line 88, in tflite_model = converter.convert() ^^^^^^^^^^^^^^^^^^^ File "/Users/andrewattard/miniforge3/envs/foodity/lib/python3.12/site-packages/tensorflow/lite/python/lite.py", line 1175, in wrapper return self._convert_and_export_metrics(convert_func, *args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/andrewattard/miniforge3/envs/foodity/lib/python3.12/site-packages/tensorflow/lite/python/lite.py", line 1129, in _convert_and_export_metrics result = convert_func(self, *args, *kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/andrewattard/miniforge3/envs/foodity/lib/python3.12/site-packages/tensorflow/lite/python/lite.py", line 1641, in convert self._freeze_keras_model() File "/Users/andrewattard/miniforge3/envs/foodity/lib/python3.12/site-packages/tensorflow/lite/python/convert_phase.py", line 215, in wrapper raise error from None # Re-throws the exception. ^^^^^^^^^^^^^^^^^^^^^ File "/Users/andrewattard/miniforge3/envs/foodity/lib/python3.12/site-packages/tensorflow/lite/python/convert_phase.py", line 205, in wrapper return func(args, kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/andrewattard/miniforge3/envs/foodity/lib/python3.12/site-packages/tensorflow/lite/python/lite.py", line 1582, in _freeze_keras_model input_signature = _model_input_signature( ^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/andrewattard/miniforge3/envs/foodity/lib/python3.12/site-packages/tensorflow/lite/python/tflite_keras_util.py", line 84, in model_input_signature input_specs = model._get_save_spec( # pylint: disable=protected-access ^^^^^^^^^^^^^^^^^^^^ AttributeError: 'Sequential' object has no attribute '_get_save_spec'. Did you mean: '_set_save_spec'?

My code is

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing import image_dataset_from_directory
import tensorflow.lite as tflite
import os

# Constants
IMG_SIZE = (224, 224)
BATCH_SIZE = 32
EPOCHS = 1
DIRECTORY_PATH = "./archive/Dataset"  # Update this to the path of your dataset
LABELS_FILE = "labels.txt"

# Load the data
train_dataset = image_dataset_from_directory(
    DIRECTORY_PATH,
    validation_split=0.2,
    subset="training",
    seed=123,
    image_size=IMG_SIZE,
    batch_size=BATCH_SIZE
)

validation_dataset = image_dataset_from_directory(
    DIRECTORY_PATH,
    validation_split=0.2,
    subset="validation",
    seed=123,
    image_size=IMG_SIZE,
    batch_size=BATCH_SIZE
)

# Prefetching for better performance
AUTOTUNE = tf.data.AUTOTUNE
train_dataset = train_dataset.prefetch(buffer_size=AUTOTUNE)
validation_dataset = validation_dataset.prefetch(buffer_size=AUTOTUNE)

# Data augmentation
data_augmentation = tf.keras.Sequential(
    [
        tf.keras.layers.RandomFlip("horizontal_and_vertical"),
        tf.keras.layers.RandomRotation(0.2),
    ]
)

# Manually extract class names from the directory structure
class_names = sorted(item.name for item in os.scandir(DIRECTORY_PATH) if item.is_dir())

# Save the labels to a file
with open(LABELS_FILE, "w") as f:
    for label in class_names:
        f.write(f"{label}\n")

print(f"Labels saved to {LABELS_FILE}")

# Build the model
model = tf.keras.Sequential([
    data_augmentation,
    tf.keras.layers.Rescaling(1./255),
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3)),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(len(class_names), activation='softmax')  # Number of classes
])

# Compile the model
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

# Train the model
model.fit(
    train_dataset,
    validation_data=validation_dataset,
    epochs=EPOCHS
)

# Convert the model to TensorFlow Lite format with quantization
converter = tflite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()

# Save the TensorFlow Lite model
tflite_model_path = "model_quantized.tflite"
with open(tflite_model_path, "wb") as f:
    f.write(tflite_model)

print(f"Quantized model saved to {tflite_model_path}")
Leli1024 commented 1 month ago

UPDATE:

Adding the following code works as a workaround

import os

os.environ["TF_USE_LEGACY_KERAS"]="1"
sawantkumar commented 1 month ago

Hi @Leli1024 ,

This issue is resolved in tf 2.17, can you please retry your code with tf version 2.17 and let me know if it works for you.

github-actions[bot] commented 1 month ago

This issue is stale because it has been open for 7 days with no activity. It will be closed if no further activity occurs. Thank you.

github-actions[bot] commented 3 weeks ago

This issue was closed because it has been inactive for 7 days since being marked as stale. Please reopen if you'd like to work on this further.

google-ml-butler[bot] commented 3 weeks ago

Are you satisfied with the resolution of your issue? Yes No