惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

TaoSecurity Blog
TaoSecurity Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
F
Fortinet All Blogs
Cisco Talos Blog
Cisco Talos Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Secure Thoughts
美团技术团队
雷峰网
雷峰网
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
Engineering at Meta
Engineering at Meta
人人都是产品经理
人人都是产品经理
月光博客
月光博客
T
Tor Project blog
P
Privacy & Cybersecurity Law Blog
Recorded Future
Recorded Future
I
Intezer
博客园 - 【当耐特】
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
GbyAI
GbyAI
罗磊的独立博客
V
V2EX
Google DeepMind News
Google DeepMind News
D
DataBreaches.Net
Last Week in AI
Last Week in AI
T
Tailwind CSS Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
A
About on SuperTechFans
Scott Helme
Scott Helme
Vercel News
Vercel News
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
Recent Announcements
Recent Announcements
Hacker News: Ask HN
Hacker News: Ask HN
C
CERT Recently Published Vulnerability Notes
G
Google Developers Blog
B
Blog
博客园 - 叶小钗
WordPress大学
WordPress大学
博客园 - 聂微东
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Jina AI
Jina AI
IT之家
IT之家
C
Cybersecurity and Infrastructure Security Agency CISA
P
Palo Alto Networks Blog
小众软件
小众软件
博客园 - Franky
Microsoft Azure Blog
Microsoft Azure Blog
AWS News Blog
AWS News Blog

陈少文的网站

巨变与机遇的未来十年 Kubernetes 平台管理软件压力测试方案 使用镜像部署 Hexo 静态页面 终于等到你 - GitHub 镜像仓库服务(ghcr.io) 一起来学 Go --(6)Interface 一起来学 Go --(5)Goroutine 和 Channel 什么是函数式编程 如何在 Kubernetes 集群集成 Kata 柯里化与偏函数 使用 PyGithub 自动创建 Label 软件产品是团队能力的输出 Helm 2 、Helm 3 比较 IoT 变现 Kubernetes 中的 DNS 服务 国内的 Helm 镜像源 Harbor 使用自签证书支持 Https 访问 DevOps 工具链之 Prow 如何使用 kfctl 安装 Kubeflow VS Code 无法下载 Go 插件的工具包 工程师更应具有服务精神 你不知道的 Docker 使用技巧 使用 Docker 运行 Tensorflow 论中国 什么是左移 如何清空 Git 仓库全部历史记录 一禅小和尚 有风吹过厨房 时间的玫瑰 如何在 CentOS 安装 GPU 驱动 开发 Tips(19) 使用 Velero 备份 Kubernetes 集群 Kubernetes Cheat Sheet 开发 Tips(18) 如何构建一个 Java 工程 开发 Tips(17) KubeSpray 安装 Kubernetes 报错 ip in ansible_all_ipv4_addresses 基于 Kubernetes 和 Jenkins 搭建自动化测试系统 在 Kubernetes 上动态创建 Jenkins Slave 使用 Jenkins 进行服务拨测 开发 Tips(16) Kubernetes 签发 Ingress 证书及日常故障运维 Kubernetes 中 Deployment 的基本操作 Kubernetes 中的证书 如何使用 KubeBuilder 开发一个 Operator Kubernetes 1.6.0 安装问题汇总 镜像管理工具 -- Harbor 开发 Tips(15) Docker 如何拉取镜像 开发 Tips(14) 使用 Helm 安装 harbor 开发 Tips(13) 使用 S2I 构建云原生应用 在 Kubernetes 中使用 emptyDir、hostPath、localVolume 开发 Tips(12) 开发 Tips(11) 代码质量分析工具 SonarQube 使用 Kubeadm 安装 Kubernetes 集群 一起来学 Go --(4)常用函数 Kubernetes 中的 Ceph Kubernetes 之 Volumes Kubernetes 之 Labels、Selectors 开发 Tips(10) 开源正在重构商业模式 Kubernetes 之网络 Kubernetes 之 API 使用 Helm 和 Operator 快速部署 Prometheus Kubernetes 复杂有状态应用管理框架 -- Operator Kubernetes 的包管理器 -- Helm 一起来学 Go --(3)Go Modules 如何一步一步地优化博客方案 kubectl 实用指南 Kubernetes 中的基本概念 搭建远程 Kubernetes 开发环境 大公司和小公司的 ToB 思路 开发 Tips(9) Go 入门指南 一起来学 Go --(2)数据与逻辑结构 如何预防 Web 富文本中的 XSS 攻击 django-xss-cleaner 云工作时代 一起来学 Go --(1)背景与特点 SaaS 开发团队的不同阶段 你不知道的 Git 使用技巧 输出既服务 微服务设计 继续奔跑 开发 Tips(8) 从账户安全到二次验证 Django 性能之数据库查询优化 Django 性能之分库分表 敏捷开发之研发流程 打造一致性的团队 开发 Tips(7) Pytest 进阶学习之 Mock PaaS 部署之 buildpack Go 开发配置 领域输出才是 PaaS 的核心竞争力 Pytest 入门学习 开发 Tips(6) 如何使用 Jenkins、Docker、GitLab 搭建 Django 自动化部署流程
HuggingFace 的模型和数据操作
微信公众号 · 2023-08-21 · via 陈少文的网站

Please enable Javascript to view the contents

HuggingFace 通过提供共享模型 model、数据集 dataset、在线托管 space 等服务,为 AI 研究人员和开发者提供了一个完整的生态。本篇文章将介绍如何使用 HuggingFace 的模型和数据集。

1. 模型操作与使用

1.1 自定义存储目录

1
export HF_HOME=/Volumes/Data/HuggingFace

否则默认在 ~/.cache/huggingface 目录下。

1.2 模型的下载

第一种方法,页面上点击下载到本地

https://huggingface.co/LinkSoul/Chinese-Llama-2-7b/tree/main 点击文件列表中的下载 Icon 。

第二种方法,使用 Git LFS 下载

在安装 git-lfs 之后,执行命令:

下载模型到本地:

1
git clone https://huggingface.co/LinkSoul/Chinese-Llama-2-7b

第三种方法,使用 huggingface-hub 下载

1
pip install huggingface_hub
1
2
from huggingface_hub import snapshot_download
snapshot_download(repo_id="LinkSoul/Chinese-Llama-2-7b")

第四种方法,使用 transformers 使用时,在线下载

1
pip install transformers
1
2
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("LinkSoul/Chinese-Llama-2-7b")

1.3 模型的操作

  • 加载模型
1
2
3
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("LinkSoul/Chinese-Llama-2-7b")
  • 保存模型
1
2
3
4
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("LinkSoul/Chinese-Llama-2-7b")
model.save_pretrained("/Volumes/Data/HuggingFace/Chinese-Llama-2-7b-v2")

1.4 模型的使用

  • 安装依赖
1
pip install transformers torch
  • 使用模型
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from transformers import EncoderDecoderModel, AutoTokenizer

model_id = "raynardj/wenyanwen-chinese-translate-to-ancient"
model = EncoderDecoderModel.from_pretrained(model_id)
tokenizer = AutoTokenizer.from_pretrained(model_id)

def chat(text):
  input_ids = tokenizer.encode(text, return_tensors='pt')
  output = model.generate(input_ids, max_length=40)
  return tokenizer.decode(output[0], skip_special_tokens=True)

chat("你好")

2. Dataset 操作与使用

2.1 数据集的下载

  • 安装 datasets
  • 下载数据集

进入 Ipython

1
2
In [1]: import datasets
In [2]: remote_datasets = datasets.load_dataset("fka/awesome-chatgpt-prompts")

此时,数据集将被下载到 $HF_HOME/datasets 目录下。类似模型的下载,数据集也可以在页面上下载、Git LFS 下载,在此不再赘述。

  • 查看数据集合
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
tree -L 2 $HF_HOME/datasets

/Volumes/Data/HuggingFace/datasets
├── _Volumes_Data_HuggingFace_datasets_fka___awesome-chatgpt-prompts_default-18237255be23cc62_0.0.0_eea64c71ca8b46dd3f537ed218fc9bf495d5707789152eb2764f5c78fa66d59d.lock
├── downloads
│   ├── 7528ed6bf521cf4a58ed283bfa5ba864e12c7203ad53ea3495ba45326e30768a
│   ├── 7528ed6bf521cf4a58ed283bfa5ba864e12c7203ad53ea3495ba45326e30768a.json
│   ├── 7528ed6bf521cf4a58ed283bfa5ba864e12c7203ad53ea3495ba45326e30768a.lock
│   ├── f41fd13f9d4e803c35d9543c56b1d887676f17d84d10e3a428ad1e46bcce6c78.8fbabec58cee4e6f69e20f509619af34f2b4ed0052c2c39ca0d73a47e1035a8b
│   ├── f41fd13f9d4e803c35d9543c56b1d887676f17d84d10e3a428ad1e46bcce6c78.8fbabec58cee4e6f69e20f509619af34f2b4ed0052c2c39ca0d73a47e1035a8b.json
│   └── f41fd13f9d4e803c35d9543c56b1d887676f17d84d10e3a428ad1e46bcce6c78.8fbabec58cee4e6f69e20f509619af34f2b4ed0052c2c39ca0d73a47e1035a8b.lock
└── fka___awesome-chatgpt-prompts
    └── default-18237255be23cc62

可以看到存储的目录并不是 fka/awesome-chatgpt-prompts 。不能使用 datasets.load_from_disk("fka/awesome-chatgpt-prompts") 加载数据集,load_from_disk 适合直接下载、Git LFS 等方式下载的数据集。

2.2 数据集的操作

  • 查看数据集
1
2
3
4
5
6
7
8
In [3]: remote_datasets

DatasetDict({
    train: Dataset({
        features: ['act', 'prompt'],
        num_rows: 153
    })
})

可以看到一共有 153 条数据,数据放在两个字段中,actprompt

  • 查看数据
1
2
3
In [4]: remote_datasets["train"][0]
Out[4]: {'act': 'Linux Terminal',
 'prompt': 'I want you to act as a linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. do not write explanations. do not type commands unless I instruct you to do so. when i need to tell you something in english, i will do so by putting text inside curly brackets {like this}. my first command is pwd'}
  • 随机选取数据
1
2
3
4
5
6
In [5]: remote_datasets["train"].select(range(10))
Out[5]:
Dataset({
    features: ['act', 'prompt'],
    num_rows: 10
})
  • 更新列名
1
2
3
4
5
6
7
8
9
In [5]: new_datasets = remote_datasets.rename_column("act", "actor")
In [6]: new_datasets
Out[6]:
DatasetDict({
    train: Dataset({
        features: ['actor', 'prompt'],
        num_rows: 153
    })
})
  • filter 过滤数据
1
2
3
4
5
6
7
8
In [7]: new_datasets.filter(lambda x: "Linux" in x["actor"])
Out[7]:
DatasetDict({
    train: Dataset({
        features: ['actor', 'prompt'],
        num_rows: 1
    })
})
  • map 处理数据
1
2
3
4
In [8]: new_datasets.map(lambda x: {"actor": x["actor"].upper(), "prompt": x["prompt"]})["train"][0]
Out[8]:
{'actor': 'LINUX TERMINAL',
 'prompt': 'I want you to act as a linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. do not write explanations. do not type commands unless I instruct you to do so. when i need to tell you something in english, i will do so by putting text inside curly brackets {like this}. my first command is pwd'}
  • sort 排序
1
2
3
4
In [9]: new_datasets.sort("actor")["train"][0]
Out[9]:
{'actor': 'AI Assisted Doctor',
 'prompt': 'I want you to act as an AI assisted doctor. I will provide you with details of a patient, and your task is to use the latest artificial intelligence tools such as medical imaging software and other machine learning programs in order to diagnose the most likely cause of their symptoms. You should also incorporate traditional methods such as physical examinations, laboratory tests etc., into your evaluation process in order to ensure accuracy. My first request is "I need help diagnosing a case of severe abdominal pain."'}
  • shuffle 乱序
1
2
3
4
In [10]: new_datasets.shuffle(seed=42)["train"][0]
Out[10]:
{'actor': 'Tech Reviewer:',
 'prompt': 'I want you to act as a tech reviewer. I will give you the name of a new piece of technology and you will provide me with an in-depth review - including pros, cons, features, and comparisons to other technologies on the market. My first suggestion request is "I am reviewing iPhone 11 Pro Max".'}
  • 随机选取数据
1
2
3
4
5
6
In [11]: new_datasets.shuffle(seed=42)["train"].select(range(10))
Out[11]:
Dataset({
    features: ['actor', 'prompt'],
    num_rows: 10
})
  • 导出数据集
1
new_datasets.save_to_disk("fka_awesome-chatgpt-prompts_2")

数据将保存至 Ipython 工作目录下的 fka_awesome-chatgpt-prompts_2 中。


微信公众号