Transformers x SwanLab:可视化NLP模型训练

HuggingFace 的 Transformers 是目前最流行的深度学习训框架之一(100k+ Star),现在主流的大语言模型(LLaMa系列、Qwen系列、ChatGLM系列等)、自然语言处理模型(Bert系列)等,都在使用Transformers来进行预训练、微调和推理。

在这里插入图片描述
SwanLab是一个深度学习实验管理与训练可视化工具,由西安电子科技大学团队打造,融合了Weights & Biases与Tensorboard的特点,能够方便地进行 训练可视化、多实验对比、超参数记录、大型实验管理和团队协作,并支持用网页链接的方式分享你的实验。

在这里插入图片描述

你可以使用Transformers快速进行模型训练,同时使用SwanLab进行实验跟踪与可视化。
下面将用一个Bert训练,来介绍如何将Transformers与SwanLab配合起来:

1. 代码中引入SwanLabCallback

from swanlab.integration.huggingface import SwanLabCallback

SwanLabCallback是适配于Transformers的日志记录类。

SwanLabCallback可以定义的参数有:

  • project、experiment_name、description 等与 swanlab.init 效果一致的参数, 用于SwanLab项目的初始化。
  • 你也可以在外部通过swanlab.init创建项目,集成会将实验记录到你在外部创建的项目中。

2. 传入Trainer

from swanlab.integration.huggingface import SwanLabCallback
from transformers import Trainer, TrainingArguments
...

# 实例化SwanLabCallback
swanlab_callback = SwanLabCallback()

trainer = Trainer(
    ...
    # 传入callbacks参数
    callbacks=[swanlab_callback],
)

3. 案例-Bert训练

查看在线实验过程:BERT-SwanLab

在这里插入图片描述

下面是一个基于Transformers框架,使用BERT模型在imdb数据集上做微调,同时用SwanLab进行可视化的案例代码

"""
用预训练的Bert模型微调IMDB数据集,并使用SwanLabCallback回调函数将结果上传到SwanLab。
IMDB数据集的1是positive,0是negative。
"""

import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
from swanlab.integration.huggingface import SwanLabCallback
import swanlab

def predict(text, model, tokenizer, CLASS_NAME):
    inputs = tokenizer(text, return_tensors="pt")

    with torch.no_grad():
        outputs = model(**inputs)
        logits = outputs.logits
        predicted_class = torch.argmax(logits).item()

    print(f"Input Text: {text}")
    print(f"Predicted class: {int(predicted_class)} {CLASS_NAME[int(predicted_class)]}")
    return int(predicted_class)
# 加载IMDB数据集
dataset = load_dataset('imdb')

# 加载预训练的BERT tokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')

# 定义tokenize函数
def tokenize(batch):
    return tokenizer(batch['text'], padding=True, truncation=True)

# 对数据集进行tokenization
tokenized_datasets = dataset.map(tokenize, batched=True)

# 设置模型输入格式
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
tokenized_datasets.set_format('torch', columns=['input_ids', 'attention_mask', 'labels'])

# 加载预训练的BERT模型
model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)

# 设置训练参数
training_args = TrainingArguments(
    output_dir='./results',
    eval_strategy='epoch',
    save_strategy='epoch',
    learning_rate=2e-5,
    per_device_train_batch_size=8,
    per_device_eval_batch_size=8,
    logging_first_step=100,
    # 总的训练轮数
    num_train_epochs=3,
    weight_decay=0.01,
    report_to="none",
    # 单卡训练
)

CLASS_NAME = {0: "negative", 1: "positive"}

# 设置swanlab回调函数
swanlab_callback = SwanLabCallback(project='BERT',
                                   experiment_name='BERT-IMDB',
                                   config={'dataset': 'IMDB', "CLASS_NAME": CLASS_NAME})

# 定义Trainer
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_datasets['train'],
    eval_dataset=tokenized_datasets['test'],
    callbacks=[swanlab_callback],
)

# 训练模型
trainer.train()

# 保存模型
model.save_pretrained('./sentiment_model')
tokenizer.save_pretrained('./sentiment_model')

# 测试模型
test_reviews = [
    "I absolutely loved this movie! The storyline was captivating and the acting was top-notch. A must-watch for everyone.",
    "This movie was a complete waste of time. The plot was predictable and the characters were poorly developed.",
    "An excellent film with a heartwarming story. The performances were outstanding, especially the lead actor.",
    "I found the movie to be quite boring. It dragged on and didn't really go anywhere. Not recommended.",
    "A masterpiece! The director did an amazing job bringing this story to life. The visuals were stunning.",
    "Terrible movie. The script was awful and the acting was even worse. I can't believe I sat through the whole thing.",
    "A delightful film with a perfect mix of humor and drama. The cast was great and the dialogue was witty.",
    "I was very disappointed with this movie. It had so much potential, but it just fell flat. The ending was particularly bad.",
    "One of the best movies I've seen this year. The story was original and the performances were incredibly moving.",
    "I didn't enjoy this movie at all. It was confusing and the pacing was off. Definitely not worth watching."
]

model.to('cpu')
text_list = []
for review in test_reviews:
    label = predict(review, model, tokenizer, CLASS_NAME)
    text_list.append(swanlab.Text(review, caption=f"{label}-{CLASS_NAME[label]}"))

if text_list:
    swanlab.log({"predict": text_list})

swanlab.finish()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4. 相关链接

  • Transformers文档:🤗 Transformers
  • SwanLab官网:SwanLab - 在线AI实验平台,一站式跟踪、比较、分享你的模型
  • SwanLab官方文档:SwanLab官方文档 | 先进的AI团队协作与模型创新引擎

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/656332.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

MM模块六(收货)

接到供应商收到的货以后,进行一个收货的动作 收货:MIGO 1.消耗物料的采购订单 数量是供应商的数量 消耗物料的采购订单,收进来的货物直接进入消耗,不会增加库存,所以这里没有库存地点进行选择 点击过账 收货后在采购…

mysql手动新建数据库

点击号输入数据库名,端口号,密码,连接到sa数据库新建数据库,语言必须选择utf8mb4新建数据库用户给数据库用户设置对应权限给数据库用户勾选权限

利用迭代方法求解线性方程组(Matlab)

一、问题描述 利用迭代方法求解线性方程组。 二、实验目的 掌握Jacobi 方法和Gauss-Seidel 方法的原理,能够编写代码实现两种迭代方法;能够利用代码分析线性方程组求解中的误差情况。 三、实验内容及要求 用代码实现:对下列方程中重新组织…

区间选点问题-贪心-C++

问题: 给定 𝑁 个闭区间 [ai,bi],请你在数轴上选择尽量少的点,使得每个区间内至少包含一个选出的点。 输出选择的点的最小数量。 位于区间端点上的点也算作区间内。 输入格式 第一行包含整数 𝑁,表示区间数…

【C++11】lambda匿名函数和包装器

目录 一,lambda匿名函数 1-1,lambda的引入 1-2,lambda表达式书写格式 1-3,lambda函数的名称 1-4,lambda捕获列表的使用 1-5,函数对象与lambda表达式 二,包装器 2-1,function…

项目管理基础知识

项目管理基础知识 导航 文章目录 项目管理基础知识导航一、项目相关概念二、时间管理三、人员管理四、风险管理 一、项目相关概念 项目定义的三层意思 一定的资源约束:时间资源、经费资源、人力资源一定的目标一次性任务 里程碑 是项目中的重要时点或事件持续时间为零&…

PX4水下机器人源码分析

一、Px4版本1.14.1机型文件 PX4Autopilotmain\ROMFS\px4fmu_common\init.d\airframes路径下 这个脚本设置了BlueROV2(重型配置)的各种参数和初始化步骤,包括电池设置、通信设置、机架和旋翼配置以及PWM输出功能的映射。通过这些设置&#x…

unity制作app(10)--统一字体

1.载入字体,微软雅黑,需要3分钟左右 加载进来3个 2.font文件夹下创建一个txt,内部的内容如下: 啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏…

AI视频教程下载:零基础学会DALL-E 、Midjourney、Microsoft Designer、Adobe Firefly

学完本课程会得到什么: 掌握ChatGPT、DALL-E 2、Midjourney、Microsoft Bing Chat、Microsoft Designer和Adobe Firefly,全面理解生成性AI及其应用 了解OpenAI及其在生成性AI领域的尖端研究 理解提示工程的重要性以及它如何帮助产生更好的输出和数据 …

【QGIS入门实战精品教程】5.3:CGCS2000转Lambert投影

参考阅读: 【GlobalMapper精品教程】081:WGS84/CGCS2000转Lambert投影 文章目录 一、加载实验数据二、投影转换三、批量投影转换一、加载实验数据 加载配套实验数据,如下图所示:图层为长沙市范围、长沙市酒店宾馆分布点位、湖南省酒店分布点位矢量数据。 双击图层,打开信…

【Vue】Vue2中的Vuex

目录 Vuex介绍Vuex 中的核心概念 在vue2中使用Vuex安装 Vuex创建一个 Vuex Store在 Vue 实例中使用 Vuex编写 Vuex 的 state、mutations 和 actions在组件中使用 Vuex Vuex的核心State组件中获取 Vuex 的状态mapState 辅助函数对象展开运算符 Getter基本使用示例 通过属性访问通…

Unity实现首行缩进两个字符

效果 在Unity中如果想实现首行缩进两个字符&#xff0c;你会发现按空格是没法实现的。 实现原理&#xff1a;用空白的透明的字替代原来的位置。 代码&#xff1a; <color#FFFFFF00>XXX</color> 赶紧去试试吧&#xff01;

《架演》共创者第一次线上沟通会议总结

《架演》共创者第一次线上沟通——启动会 会议主题&#xff1a;《架演》共创启动会议会议时间&#xff1a;2024年5月28日&#xff0c;20:00 - 21:00会议地点&#xff1a;腾讯会议主持人&#xff1a;寒山参会人员&#xff1a; 夏军、mirror、刘哥、悟缺席人员&#xff1a;可心、…

性能测试(一)—— 性能测试理论+jmeter的使用

1.性能测试介绍 定义&#xff1a;软件的性能是软件的一种非功能特性&#xff0c;它关注的不是软件是否能够完成特定的功能&#xff0c;而是在完成该功能时展示出来的及时性。 由定义可知性能关注的是软件的非功能特性&#xff0c;所以一般来说性能测试介入的时机是在功能测试完…

20240521在Ubuntu20.04下编译RK3588平台的IPC方案

20240521在Ubuntu20.04下编译RK3588平台的IPC方案 2024/5/21 15:27 viewproviewpro-ThinkBook-16-G5-IRH:~$ viewproviewpro-ThinkBook-16-G5-IRH:~$ md5sum RK3588_IPC_SDK.tar.gz 7481cc8d59f697a5fa4fd655de866707 RK3588_IPC_SDK.tar.gz viewproviewpro-ThinkBook-16-G5…

【vue-4】遍历数组或对象v-for

1、遍历数组 <ul><li v-for"(value,index) in web.number">index>{{index}}:value>{{value}}</li> </ul> 知识点&#xff1a; <ul>标签定义无序列表 举例&#xff1a; <ul><li>Coffee</li><li>Tea…

LeetCode199二叉树的右视图

题目描述 给定一个二叉树的 根节点 root&#xff0c;想象自己站在它的右侧&#xff0c;按照从顶部到底部的顺序&#xff0c;返回从右侧所能看到的节点值。 解析 这一题的关键其实就是找到怎么去得到当前是哪一层级&#xff0c;可以利用队列对二叉树进行层次遍历&#xff0c;但…

FFmpeg操作命令 - 精简版

PS&#xff1a;&#xff08;因为我只需要简单的操作&#xff0c;所以我整理出了这份笔记&#xff09; 原网址&#xff1a;30分钟带你入门&#xff0c;20个 FFmpeg操作命令&#xff0c;包你学会 - 知乎 大佬零声Github整理库整理的笔记非常的全面&#xff0c;想看完整版去上面…

Java | Leetcode Java题解之第102题二叉树的层序遍历

题目&#xff1a; 题解&#xff1a; class Solution {public List<List<Integer>> levelOrder(TreeNode root) {Queue<TreeNode> queue new LinkedList<>();List<List<Integer>> res new ArrayList<>();if (root ! null) queue.a…

前端开发框架Angular

版权声明 本文原创作者&#xff1a;谷哥的小弟作者博客地址&#xff1a;http://blog.csdn.net/lfdfhl Angular概述 Angular是由Google开发并维护的一款开源前端开发框架。它最初被设计为用于构建单页面应用&#xff08;SPA&#xff09;&#xff0c;但随着版本的更新和发展&am…