qubvel-org / segmentation_models.pytorch

Semantic segmentation models with 500+ pretrained convolutional and transformer-based backbones.
https://smp.readthedocs.io/
MIT License
9.34k stars 1.64k forks source link

'DeepLabV3Plus' object has no attribute 'save_pretrained' #880

Open Marcus2331 opened 3 months ago

Marcus2331 commented 3 months ago

Почему тут есть возможность сохранения модели https://smp.readthedocs.io/en/latest/save_load.html как в документации. А я не могу сохранить модель DeepLabV3Plus?

Why is it possible to save the model here https://smp.readthedocs.io/en/latest/save_load.html as in the documentation. Can't I save the DeepLabV3Plus model?

Marcus2331 commented 3 months ago
import torch
import segmentation_models_pytorch as smp
model = smp.DeepLabV3Plus(
    encoder_name="efficientnet-b5",    # Выбранный энкодер
    encoder_weights=None,        # Использование предобученных весов на ImageNet
    in_channels=1,                     # Количество входных каналов (например, 1 для черно-белых изображений)
    classes=1,                         # Количество классов для выходной маски
    activation='sigmoid'              # Функция активации
)
model = torch.nn.DataParallel(model)
model = model.cpu()

# Путь к сохраненной модели
PATH = 'best_model_epoch_8.pt'
model.load_state_dict(torch.load(PATH, map_location=torch.device('cpu')))
if isinstance(model, torch.nn.DataParallel):
    model = model.module
# Перевод модели в режим оценки
model.eval()
# After training your model, save it to a directory
model.save_pretrained('./model')

AttributeError: 'DeepLabV3Plus' object has no attribute 'save_pretrained'

qubvel commented 3 months ago

Hi @Marcus2331, thanks for the issue! The feature has not been released yet to PyPI package!

But you could try it out if you reinstall the library from the source with

pip install -U git+https://github.com/qubvel/segmentation_models.pytorch

I will release it to PyPI in a few days or so!

Marcus2331 commented 3 months ago

Привет@Marcus2331, спасибо за проблему! Эта функция еще не добавлена ​​в пакет PyPI!

Но вы можете попробовать, если переустановите библиотеку из исходного кода с помощью

pip install -U git+https://github.com/qubvel/segmentation_models.pytorch

Я выпущу его для PyPI примерно через несколько дней!

Thanks for the quick feedback

Marcus2331 commented 3 months ago

Привет@Marcus2331, спасибо за проблему! Эта функция еще не добавлена ​​в пакет PyPI!

Но вы можете попробовать, если переустановите библиотеку из исходного кода с помощью

pip install -U git+https://github.com/qubvel/segmentation_models.pytorch

Я выпущу его для PyPI примерно через несколько дней!

Прошу прощения возможно за глупый вопрос. Но есть ли возможность экспорта модели обученной на библиотеке smp в формат tf_saved_model Для tensorflow_serving?

qubvel commented 3 months ago

I tried an approach that Chat-GPT recommended, it seems to work fine, check this out in Colab:

https://colab.research.google.com/drive/1J5dAmPfMcoJkDv9Bh_IbDxKjafhCFCmM?usp=sharing

And, please, let me know if you have any questions or this solves your issue 🙂 I will include this example to examples folder then and in docs

Marcus2331 commented 3 months ago

I tried an approach that Chat-GPT recommended, it seems to work fine, check this out in Colab:

https://colab.research.google.com/drive/1J5dAmPfMcoJkDv9Bh_IbDxKjafhCFCmM?usp=sharing

And, please, let me know if you have any questions or this solves your issue 🙂 I will include this example to examples folder then and in docs

Слезно прошу вас помочь мне с конвертацией модели которую я сохранил с помощью model.save_pretrained('./model') сконвертировать в формат tf_saved_model для дальнейшего использования в tensorflow_serving:((

qubvel commented 3 months ago

Did you try to do it with provided colab example?

qubvel commented 2 months ago

Consider also looking at https://github.com/PINTO0309/onnx2tf/issues/543

Marcus2331 commented 2 months ago

Consider also looking at PINTO0309/onnx2tf#543

Thank you so much!!! this solved my problem)

Dittonal commented 1 month ago

when i run this code,failed ` import segmentation_models_pytorch as smp

model = smp.Unet('resnet34', encoder_weights='imagenet') model.save_pretrained('./my_model')

model.save_pretrained('username/my-model', push_to_hub=True) `

AttributeError Traceback (most recent call last) Cell In[1], line 6 3 model = smp.Unet('resnet34', encoder_weights='imagenet') 5 # After training your model, save it to a directory ----> 6 model.save_pretrained('./my_model') 8 # Or saved and pushed to the Hub simultaneously 9 model.save_pretrained('username/my-model', push_to_hub=True)

File e:\Anaconda\envs\py39_pytorch\lib\site-packages\torch\nn\modules\module.py:1688, in Module.getattr(self, name) 1686 if name in modules: 1687 return modules[name] -> 1688 raise AttributeError(f"'{type(self).name}' object has no attribute '{name}'")

AttributeError: 'Unet' object has no attribute 'save_pretrained'

Dittonal commented 1 month ago

my environment torch==2.2.2,segmentation-models-pytorch==0.3.3

qubvel commented 1 month ago

@Dittonal please install dev version from source

pip install -U git+https://github.com/qubvel/segmentation_models.pytorch