huggingface / huggingface_hub

The official Python client for the Huggingface Hub.
https://huggingface.co/docs/huggingface_hub
Apache License 2.0
1.98k stars 514 forks source link

Error using from_pretrained_keras model #2234

Closed 1MuhammadFarhanAslam closed 5 months ago

1MuhammadFarhanAslam commented 5 months ago

Describe the bug

I have trained a model and saved it as below

`import os import numpy as np from tensorflow.keras.optimizers import Adam from tensorflow.keras.losses import BinaryCrossentropy from tensorflow.keras.metrics import BinaryAccuracy from sklearn.model_selection import StratifiedKFold from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Input, Reshape, Bidirectional, LSTM, Concatenate, Dropout from tensorflow.keras.regularizers import l2 from tensorflow.keras.models import Model from tensorflow.keras.applications import Xception from tensorflow.keras.layers import Attention

Define Model Architecture with Self-Attention

def build_model_with_self_attention(dropout_rate=0.7, l2_reg=0.001): input_tensor = Input(shape=(299, 299, 3)) base_model = Xception(weights='imagenet', include_top=False) x = base_model(input_tensor)

Global average pooling to reduce spatial dimensions

x = GlobalAveragePooling2D()(x)
# Add dropout layer to reduce overfitting
x = Dropout(dropout_rate)(x)
# Self-Attention Mechanism
attention_output = Attention()([x, x])
# Add a dense layer with L2 regularization
output_tensor = Dense(1, activation='sigmoid', kernel_regularizer=l2(l2_reg))(attention_output)  # Binary classification
model = Model(inputs=input_tensor, outputs=output_tensor)
return model

Define the train_model_with_error_handling function

def train_model_with_error_handling(model, train_generator, val_generator, epochs, callbacks): for epoch in range(epochs): print(f'Epoch {epoch + 1}/{epochs}') try: history = model.fit( train_generator, validation_data=val_generator, epochs=1, # Train for 1 epoch at a time callbacks=callbacks, verbose=1 ) except Exception as e: print(f"Error encountered during training: {e}") continue

Define the number of folds

num_folds = 10

Initialize Stratified K-Fold

skf = StratifiedKFold(n_splits=num_folds, shuffle=True, random_state=42)

Define the main data directory

data_dir = "/content/gdrive/MyDrive/Images_06_Apr_2024_part_2/Combined_Images"

Define ImageDataGenerator for both training and validation data

datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)

Define batch size

batch_size = 32

Create generators for training and validation data

train_generator = datagen.flow_from_directory( data_dir, target_size=(299, 299), batch_size=batch_size, class_mode='binary', subset='training', # Specify this is for training data shuffle=True, seed=42 )

val_generator = datagen.flow_from_directory( data_dir, target_size=(299, 299), batch_size=batch_size, class_mode='binary', subset='validation', # Specify this is for validation data shuffle=False, seed=42 )

Define EarlyStopping callback

early_stopping = EarlyStopping(patience=5, restore_best_weights=True)

Create lists to store evaluation metrics for each fold

accuracy_scores = [] loss_values = []

Perform 10-fold cross-validation

for fold, (train_index, val_index) in enumerate(skf.split(train_generator.filenames, train_generator.classes)): print(f'Fold {fold + 1}/{num_folds}')

# Create separate generators for training and validation data for this fold
train_generator_fold = datagen.flow_from_directory(
    data_dir,
    target_size=(299, 299),
    batch_size=batch_size,
    class_mode='binary',
    subset='training',
    shuffle=True,
    seed=42
)

val_generator_fold = datagen.flow_from_directory(
    data_dir,
    target_size=(299, 299),
    batch_size=batch_size,
    class_mode='binary',
    subset='validation',
    shuffle=False,
    seed=42
)

# Reinitialize and compile the model for this fold
xception_model_with_self_attention = build_model_with_self_attention()
xception_model_with_self_attention.compile(optimizer=Adam(), loss=BinaryCrossentropy(), metrics=[BinaryAccuracy()])

# Train the model for this fold with error handling
train_model_with_error_handling(
    xception_model_with_self_attention,
    train_generator_fold,
    val_generator_fold,
    epochs=5,
    callbacks=[early_stopping]
)

# Evaluate the model on the validation data for this fold
metrics = xception_model_with_self_attention.evaluate(val_generator_fold, verbose=0)
accuracy_scores.append(metrics[1])  # Accuracy
loss_values.append(metrics[0])  # Loss

Calculate and print the average evaluation metrics

print(f'Average Accuracy: {np.mean(accuracy_scores)}') print(f'Average Loss: {np.mean(loss_values)}')

save model

xception_model_with_self_attention.save('/content/gdrive/MyDrive/xception_model_with_self_attention_06_APR.h5') xception_model_with_self_attention.save('/content/gdrive/MyDrive/xception_model_with_self_attention_06_APR.keras')`

But after 10 days of saving this model, now I want to use this model in hugging face spaces with radio. For that purpose, I again loaded model using:

`import tensorflow as tf from tensorflow import keras

Load the saved model

model = keras.models.load_model("/content/drive/MyDrive/xception_model_with_self_attention_03_APR.keras") `

Then I used official guidance from this video and notebook

%%capture ! pip install git+https://github.com/huggingface/huggingface_hub.git@main ! sudo apt -qq install git-lfs ! git config --global credential.helper store

! huggingface-cli login

from huggingface_hub import push_to_hub_keras push_to_hub_keras(model, 'cancer_image_classifier')

Now I reloaded model using following command:

from huggingface_hub import push_to_hub_keras push_to_hub_keras(model, 'cancer_image_classifier')

`import gradio as gr import numpy as np import tensorflow as tf

Load your uploaded model from Hugging Face Hub

from huggingface_hub import from_pretrained_keras

model = from_pretrained_keras("MuhammadFarhanAslam/cancer_image_classifier")

Define the class labels

labels = ['Normal', 'Cancer']

def predict(inp):

Convert the PIL image to a numpy array

inp_np = np.array(inp)

# Preprocess the image
inp_prep = tf.image.resize(inp_np, (299, 299))  # Resize input image to match model input size
inp_prep = inp_prep / 255.0  # Normalize the image

# Add batch dimension and predict
inp_batch = tf.expand_dims(inp_prep, axis=0)  # Add batch dimension
prediction = model.predict(inp_batch)

# Check if prediction array has only one value
if prediction.shape[1] == 1:
    confidences = {'Normal': float(prediction[0][0]), 'Cancer': 1.0 - float(prediction[0][0])}
else:
    # Map the probabilities to class labels using the defined labels
    confidences = {labels[i]: float(prediction[0][i]) for i in range(len(labels))}

return confidences

Create the Gradio interface with custom CSS for the submit button

demo = gr.Interface( fn=predict, inputs=gr.Image(type="pil", label="Image Path"), outputs=gr.Label(num_top_classes=2), examples=[ ["/content/drive/MyDrive/Images_07_Apr_2024/Cancer/ISIC_0024310.jpg"], ["/content/drive/MyDrive/Images_07_Apr_2024/Normal/ISIC_0024306.jpg"] ], title="Computer-Aided Diagnosis (CAD) Tool for Dermatologists to Detect Skin Cancer", allow_flagging='manual', # Set allow_flagging to 'manual' flagging_options=["Incorrect Prediction"], # Define flagging options theme=gr.themes.Base() )

demo.launch(debug=True)`

The error is as following:

image

Previously, it was working with

image image

@Wauplin Can you help me in this regard? How I can Successfully run the from_pretrained_keras model in colab back and Hugging face spaces too....I'll be very thankful to you.

Reproduction

`import tensorflow as tf from tensorflow import keras

Load the saved model

model = keras.models.load_model("/content/drive/MyDrive/xception_model_with_self_attention_03_APR.keras") `

%%capture ! pip install git+https://github.com/huggingface/huggingface_hub.git@main ! sudo apt -qq install git-lfs ! git config --global credential.helper store

! huggingface-cli login

from huggingface_hub import push_to_hub_keras push_to_hub_keras(model, 'cancer_image_classifier')

The link to the: hugging face hub model directory

from huggingface_hub import push_to_hub_keras push_to_hub_keras(model, 'cancer_image_classifier')

`import gradio as gr import numpy as np import tensorflow as tf

Load your uploaded model from Hugging Face Hub

from huggingface_hub import from_pretrained_keras

model = from_pretrained_keras("MuhammadFarhanAslam/cancer_image_classifier")

Define the class labels

labels = ['Normal', 'Cancer']

def predict(inp):

Convert the PIL image to a numpy array

inp_np = np.array(inp)

# Preprocess the image
inp_prep = tf.image.resize(inp_np, (299, 299))  # Resize input image to match model input size
inp_prep = inp_prep / 255.0  # Normalize the image

# Add batch dimension and predict
inp_batch = tf.expand_dims(inp_prep, axis=0)  # Add batch dimension
prediction = model.predict(inp_batch)

# Check if prediction array has only one value
if prediction.shape[1] == 1:
    confidences = {'Normal': float(prediction[0][0]), 'Cancer': 1.0 - float(prediction[0][0])}
else:
    # Map the probabilities to class labels using the defined labels
    confidences = {labels[i]: float(prediction[0][i]) for i in range(len(labels))}

return confidences

Create the Gradio interface with custom CSS for the submit button

demo = gr.Interface( fn=predict, inputs=gr.Image(type="pil", label="Image Path"), outputs=gr.Label(num_top_classes=2), examples=[ ["/content/drive/MyDrive/Images_07_Apr_2024/Cancer/ISIC_0024310.jpg"], ["/content/drive/MyDrive/Images_07_Apr_2024/Normal/ISIC_0024306.jpg"] ], title="Computer-Aided Diagnosis (CAD) Tool for Dermatologists to Detect Skin Cancer", allow_flagging='manual', # Set allow_flagging to 'manual' flagging_options=["Incorrect Prediction"], # Define flagging options theme=gr.themes.Base() )

demo.launch(debug=True)`

Colab Logs after pressing submit button:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/gradio/queueing.py", line 527, in process_events
    response = await route_utils.call_process_api(
  File "/usr/local/lib/python3.10/dist-packages/gradio/route_utils.py", line 261, in call_process_api
    output = await app.get_blocks().process_api(
  File "/usr/local/lib/python3.10/dist-packages/gradio/blocks.py", line 1786, in process_api
    result = await self.call_function(
  File "/usr/local/lib/python3.10/dist-packages/gradio/blocks.py", line 1338, in call_function
    prediction = await anyio.to_thread.run_sync(
  File "/usr/local/lib/python3.10/dist-packages/anyio/to_thread.py", line 33, in run_sync
    return await get_asynclib().run_sync_in_worker_thread(
  File "/usr/local/lib/python3.10/dist-packages/anyio/_backends/_asyncio.py", line 877, in run_sync_in_worker_thread
    return await future
  File "/usr/local/lib/python3.10/dist-packages/anyio/_backends/_asyncio.py", line 807, in run
    result = context.run(func, *args)
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 759, in wrapper
    response = f(*args, **kwargs)
  File "<ipython-input-12-632552e38aef>", line 22, in predict
    prediction = model.predict(inp_batch)
AttributeError: '_UserObject' object has no attribute 'predict'
Keyboard interruption in main thread... closing server.
Killing tunnel 127.0.0.1:7860 <> https://beeebde23633046956.gradio.live

When I deployed same code on huggingface spaces it gave me following error and do not show even interface

Huggingface spaces errorError:

===== Application Startup at 2024-04-18 06:50:19 =====

2024-04-18 08:52:44.121025: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable TF_ENABLE_ONEDNN_OPTS=0. 2024-04-18 08:52:44.169714: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags. 2024-04-18 08:52:45.406006: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT Traceback (most recent call last): File "/home/user/app/app.py", line 7, in model = from_pretrained_keras("MuhammadFarhanAslam/cancer_image_classifier") File "/usr/local/lib/python3.10/site-packages/huggingface_hub/keras_mixin.py", line 296, in from_pretrained_keras return KerasModelHubMixin.from_pretrained(*args, *kwargs) File "/usr/local/lib/python3.10/site-packages/huggingface_hub/utils/_validators.py", line 119, in _inner_fn return fn(args, **kwargs) File "/usr/local/lib/python3.10/site-packages/huggingface_hub/hub_mixin.py", line 420, in from_pretrained instance = cls._from_pretrained( File "/usr/local/lib/python3.10/site-packages/huggingface_hub/keras_mixin.py", line 497, in _from_pretrained model = keras.models.load_model(storage_folder) File "/usr/local/lib/python3.10/site-packages/keras/src/saving/saving_api.py", line 191, in load_model raise ValueError( ValueError: File format not supported: filepath=/home/user/.cache/huggingface/hub/models--MuhammadFarhanAslam--cancer_image_classifier/snapshots/52ab370750099ca67e8c46193a595470b98bc1f2. Keras 3 only supports V3 .keras files and legacy H5 format files (.h5 extension). Note that the legacy SavedModel format is not supported by load_model() in Keras 3. In order to reload a TensorFlow SavedModel as an inference-only layer in Keras 3, use keras.layers.TFSMLayer(/home/user/.cache/huggingface/hub/models--MuhammadFarhanAslam--cancer_image_classifier/snapshots/52ab370750099ca67e8c46193a595470b98bc1f2, call_endpoint='serving_default') (note that your call_endpoint might have a different name).

System info

Copy-and-paste the text below in your GitHub issue.

- huggingface_hub version: 0.23.0.dev0
- Platform: Linux-6.1.58+-x86_64-with-glibc2.35
- Python version: 3.10.12
- Running in iPython ?: Yes
- iPython shell: Shell
- Running in notebook ?: Yes
- Running in Google Colab ?: Yes
- Token path ?: /root/.cache/huggingface/token
- Has saved token ?: True
- Who am I ?: MuhammadFarhanAslam
- Configured git credential helpers: store
- FastAI: 2.7.14
- Tensorflow: 2.15.0
- Torch: 2.2.1+cu121
- Jinja2: 3.1.3
- Graphviz: 0.20.3
- keras: 2.15.0
- Pydot: 1.4.2
- Pillow: 9.4.0
- hf_transfer: N/A
- gradio: 4.26.0
- tensorboard: N/A
- numpy: 1.25.2
- pydantic: 2.6.4
- aiohttp: 3.9.3
- ENDPOINT: https://huggingface.co
- HF_HUB_CACHE: /root/.cache/huggingface/hub
- HF_ASSETS_CACHE: /root/.cache/huggingface/assets
- HF_TOKEN_PATH: /root/.cache/huggingface/token
- HF_HUB_OFFLINE: False
- HF_HUB_DISABLE_TELEMETRY: False
- HF_HUB_DISABLE_PROGRESS_BARS: None
- HF_HUB_DISABLE_SYMLINKS_WARNING: False
- HF_HUB_DISABLE_EXPERIMENTAL_WARNING: False
- HF_HUB_DISABLE_IMPLICIT_TOKEN: False
- HF_HUB_ENABLE_HF_TRANSFER: False
- HF_HUB_ETAG_TIMEOUT: 10
- HF_HUB_DOWNLOAD_TIMEOUT: 10

{'huggingface_hub version': '0.23.0.dev0',
 'Platform': 'Linux-6.1.58+-x86_64-with-glibc2.35',
 'Python version': '3.10.12',
 'Running in iPython ?': 'Yes',
 'iPython shell': 'Shell',
 'Running in notebook ?': 'Yes',
 'Running in Google Colab ?': 'Yes',
 'Token path ?': '/root/.cache/huggingface/token',
 'Has saved token ?': True,
 'Who am I ?': 'MuhammadFarhanAslam',
 'Configured git credential helpers': 'store',
 'FastAI': '2.7.14',
 'Tensorflow': '2.15.0',
 'Torch': '2.2.1+cu121',
 'Jinja2': '3.1.3',
 'Graphviz': '0.20.3',
 'keras': '2.15.0',
 'Pydot': '1.4.2',
 'Pillow': '9.4.0',
 'hf_transfer': 'N/A',
 'gradio': '4.26.0',
 'tensorboard': 'N/A',
 'numpy': '1.25.2',
 'pydantic': '2.6.4',
 'aiohttp': '3.9.3',
 'ENDPOINT': 'https://huggingface.co',
 'HF_HUB_CACHE': '/root/.cache/huggingface/hub',
 'HF_ASSETS_CACHE': '/root/.cache/huggingface/assets',
 'HF_TOKEN_PATH': '/root/.cache/huggingface/token',
 'HF_HUB_OFFLINE': False,
 'HF_HUB_DISABLE_TELEMETRY': False,
 'HF_HUB_DISABLE_PROGRESS_BARS': None,
 'HF_HUB_DISABLE_SYMLINKS_WARNING': False,
 'HF_HUB_DISABLE_EXPERIMENTAL_WARNING': False,
 'HF_HUB_DISABLE_IMPLICIT_TOKEN': False,
 'HF_HUB_ENABLE_HF_TRANSFER': False,
 'HF_HUB_ETAG_TIMEOUT': 10,
 'HF_HUB_DOWNLOAD_TIMEOUT': 10}
Wauplin commented 5 months ago

@Wauplin Can you help me in this regard? How I can Successfully run the from_pretrained_keras model in colab back and Hugging face spaces too....I'll be very thankful to you.

Hi @1MuhammadFarhanAslam, from_pretrained_keras is unfortunately not compatible with Keras3. I suspect the issue might come from here. Keras3 has been made the default in TF 2.16. See release notes that describe workaround to continue using Keras2: https://github.com/tensorflow/tensorflow/releases/tag/v2.16.1. To make it work with Spaces you'll have to add a requirements.txt file and pin packages to earlier versions. We are currently working in making the integration with Keras3 working but it's not ready yet. Hope this will help you.

1MuhammadFarhanAslam commented 5 months ago

@Wauplin Can you help me in this regard? How I can Successfully run the from_pretrained_keras model in colab back and Hugging face spaces too....I'll be very thankful to you.

Hi @1MuhammadFarhanAslam, from_pretrained_keras is unfortunately not compatible with Keras3. I suspect the issue might come from here. Keras3 has been made the default in TF 2.16. See release notes that describe workaround to continue using Keras2: https://github.com/tensorflow/tensorflow/releases/tag/v2.16.1. To make it work with Spaces you'll have to add a requirements.txt file and pin packages to earlier versions. We are currently working in making the integration with Keras3 working but it's not ready yet. Hope this will help you.

Hi! @Wauplin, I checked the version of tensorflow and keras but I'm already using TensorFlow/Keras version==2.15.0. Can you please point out any other root cause of the error as I provided you with all the code and error logs? Thanking you in anticipation.

image

Wauplin commented 5 months ago

Hi! @Wauplin, I checked the version of tensorflow and keras but I'm already using TensorFlow/Keras version==2.15.0

ValueError: File format not supported: filepath=/home/user/.cache/huggingface/hub/models--MuhammadFarhanAslam--cancer_image_classifier/snapshots/52ab370750099ca67e8c46193a595470b98bc1f2. Keras 3 only supports V3 .keras files and legacy H5 format files (.h5 extension). Note that the legacy SavedModel format is not supported by load_model() in Keras 3. In order to reload a TensorFlow SavedModel as an inference-only layer in Keras 3, use keras.layers.TFSMLayer(/home/user/.cache/huggingface/hub/models--MuhammadFarhanAslam--cancer_image_classifier/snapshots/52ab370750099ca67e8c46193a595470b98bc1f2, call_endpoint='serving_default') (note that your call_endpoint might have a different name).

In the Spaces logs you've shared above, the problem really seems to be coming from Keras 3 being installed. Let's try to fix this one first.

1MuhammadFarhanAslam commented 5 months ago

Hi! @Wauplin, I checked the version of tensorflow and keras but I'm already using TensorFlow/Keras version==2.15.0

ValueError: File format not supported: filepath=/home/user/.cache/huggingface/hub/models--MuhammadFarhanAslam--cancer_image_classifier/snapshots/52ab370750099ca67e8c46193a595470b98bc1f2. Keras 3 only supports V3 .keras files and legacy H5 format files (.h5 extension). Note that the legacy SavedModel format is not supported by load_model() in Keras 3. In order to reload a TensorFlow SavedModel as an inference-only layer in Keras 3, use keras.layers.TFSMLayer(/home/user/.cache/huggingface/hub/models--MuhammadFarhanAslam--cancer_image_classifier/snapshots/52ab370750099ca67e8c46193a595470b98bc1f2, call_endpoint='serving_default') (note that your call_endpoint might have a different name).

In the Spaces logs you've shared above, the problem really seems to be coming from Keras 3 being installed. Let's try to fix this one first.

How can I troubleshoot this problem? Can you help me to fix this error?

Wauplin commented 5 months ago

How can I troubleshoot this problem? Can you help me to fix this error?

Yes, as mentioned above, "to make it work with Spaces you'll have to add a requirements.txt file and pin packages to earlier versions.".


I'm also not sure what's the issue you were having in your notebook. It might not be the same issue so not the same root cause.

1MuhammadFarhanAslam commented 5 months ago

How can I troubleshoot this problem? Can you help me to fix this error?

Yes, as mentioned above, "to make it work with Spaces you'll have to add a requirements.txt file and pin packages to earlier versions.".

I'm also not sure what's the issue you were having in your notebook. It might not be the same issue so not the same root cause.

I've successfully deployed the ml model on hugging face spaces but now there is one following error:

Error during classification whein I clicked on submit button.

2024-04-18 12:55:19.426257: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable TF_ENABLE_ONEDNN_OPTS=0. 2024-04-18 12:55:19.463182: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2024-04-18 12:55:19.463220: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2024-04-18 12:55:19.464260: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered 2024-04-18 12:55:19.469912: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags. 2024-04-18 12:55:20.399322: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT Running on local URL: http://0.0.0.0:7860

To create a public link, set share=True in launch(). Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/gradio/queueing.py", line 527, in process_events response = await route_utils.call_process_api( File "/usr/local/lib/python3.10/site-packages/gradio/route_utils.py", line 261, in call_process_api output = await app.get_blocks().process_api( File "/usr/local/lib/python3.10/site-packages/gradio/blocks.py", line 1786, in process_api result = await self.call_function( File "/usr/local/lib/python3.10/site-packages/gradio/blocks.py", line 1338, in call_function prediction = await anyio.to_thread.run_sync( File "/usr/local/lib/python3.10/site-packages/anyio/to_thread.py", line 56, in run_sync return await get_async_backend().run_sync_in_worker_thread( File "/usr/local/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 2144, in run_sync_in_worker_thread return await future File "/usr/local/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 851, in run result = context.run(func, args) File "/usr/local/lib/python3.10/site-packages/gradio/utils.py", line 759, in wrapper response = f(args, **kwargs) File "/home/user/app/app.py", line 22, in predict prediction = model.predict(inp_batch) AttributeError: '_UserObject' object has no attribute 'predict'

Wauplin commented 5 months ago

Great! Now I'm sorry but it doesn't seem to be a bug related to huggingface_hub/keras/Spaces. You would need to investigate it further to find which library is causing the problem. Good luck with that part ;)

1MuhammadFarhanAslam commented 5 months ago

Great! Now I'm sorry but it doesn't seem to be a bug related to huggingface_hub/keras/Spaces. You would need to investigate it further to find which library is causing the problem. Good luck with that part ;)

Hi! @Wauplin , I changed the model format to be uploaded using (from_pretrained_keras ) to .h5 format from .keras and also removed .predict for using the model again (with from_pretrained_keras) in app.py and it's successfully worked. Thank you very much for your support....!