【modelscope】常用指令
【代码】【modelscope】常用指令。
·
一、环境准备(基础前置指令)
首先需要安装 ModelScope 库,以下是不同场景的安装指令:
1. 基础安装(适用于大部分基础功能)
# 基础版安装(推荐新手)
pip install modelscope -U
# 带依赖的完整安装(包含CV/NLP/语音等所有依赖)
pip install modelscope[all] -U
2. 可选依赖安装(按需选择)
# 如果需要GPU加速(需先安装对应版本的PyTorch)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
# 如果需要处理音频/视频类模型
pip install modelscope[audio,video] -U
# 如果需要处理多模态模型(如文生图、图生文)
pip install modelscope[multimodal] -U
二、模型下载 / 加载(最常用核心指令)
1. 命令行直接下载模型
# 基础格式:modelscope download --model 模型ID --local-dir 本地保存路径
modelscope download --model damo/nlp_structbert_sentiment-classification_chinese-base --local-dir ./sentiment_model
# 后台下载并保存日志
nohup modelscope download Qwen/Qwen-Image --local_dir ./local_models/qwen-image > download.log 2>&1 &
2. Python 代码中加载模型(推荐方式)
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
# 方式1:直接加载模型(自动下载到缓存)
# 情感分类任务示例
pipe = pipeline(
task=Tasks.sentiment_classification,
model='damo/nlp_structbert_sentiment-classification_chinese-base'
)
# 推理调用
result = pipe('这款手机用起来特别流畅,我很喜欢!')
print(result) # 输出:{'text': '这款手机用起来特别流畅,我很喜欢!', 'label': 'positive', 'score': 0.999874}
# 方式2:加载本地已下载的模型
pipe = pipeline(
task=Tasks.sentiment_classification,
model='./sentiment_model' # 本地模型路径
)
三、模型训练 / 微调指令
以文本分类模型微调为例,核心指令如下:
from modelscope.trainers import EpochBasedTrainer
from modelscope.msdatasets import MsDataset
from modelscope.metainfo import Trainers
# 加载数据集(示例:中文情感分类数据集)
dataset = MsDataset.load('clue_afqmc', split='train')
# 配置训练参数
trainer = EpochBasedTrainer(
model='damo/nlp_structbert_sentiment-classification_chinese-base',
train_dataset=dataset,
args={
'num_train_epochs': 3, # 训练轮数
'learning_rate': 2e-5, # 学习率
'output_dir': './finetuned_model', # 微调后模型保存路径
'per_device_train_batch_size': 8, # 批次大小
}
)
# 开始训练
trainer.train()
更多推荐




所有评论(0)