Transformer实战(5)——Hugging Face环境配置与应用详解

AI摘要

本文详述Hugging Face Transformers库的本地环境搭建流程,涵盖Anaconda安装、PyTorch/TensorFlow依赖配置、hf-mirror加速模型下载;重点讲解分词器与预训练语言模型(如BERT)的加载与推理、pipeline零样本任务调用、社区模型复用方法,以及CLIP等多模态Transformer在零样本图像分类中的端到端实践。

0. 前言

我们已经了解了使用深度学习 (Deep Learning, DL) 方法的自然语言处理 (Natural Language Processing, NLP) 技术演进,学习了关于 Transformer 及其架构的一些基本信息。在进行实践之前,我们将首先了解所需环境的安装步骤,介绍如何在 PyTorch 和 TensorFlow 框架中使用模型。
Hugging Face 模型库是本节的一个重要部分,我们将讨论如何获取不同的模型以及使用不同管道的步骤。例如,双向自回归 Transformer (Bidirectional and Auto-regressive Transformer, BART)、BERT 和 TAPAS (TAble PArSing) 等模型,同时介绍 GPT-2 (Generative Pretrained Transformer 2) 文本生成。需要注意的是,本节主要集中在如何准备环境以及如何使用预训练模型,而不是模型训练。模型训练将在后续学习中详细讨论。

1. 安装

Transformer架构和Transformers 库和Hugging Face 和之间的关系非常紧密,Hugging Face 是推动 Transformer 架构普及和应用的重要力量。 阅读详情

相关推荐

Transformer与Hugging Face:NLP工程范式迁移实战指南

Transformer架构标志着自然语言处理从序列状态机向并行张量流编程的根本转变,其核心价值在于确定性低延迟、长程依赖建模能力与工业级可扩展性;Hugging Face则将这一能力封装为开箱即用的NLP操作系统,涵盖模型加载、Tokenizer行为控制、Pipeline推理封装及生产部署全链路。理解自注意力机制与位置编码的协同原理、掌握tokenizer的padding/truncation静默行为、识别pipeline背后的状态管理逻辑,是构建高可用文本智能服务的技术基石。本文聚焦真实业务场景中的典型问

weixin_30325487的博客 416

Transformer与Hugging Face实战指南:从显存优化到生产部署

Transformer架构是现代NLP的基石,其自注意力机制通过并行化计算彻底替代了RNN的序列依赖,显著提升长文本建模能力;Hugging Face则将预训练-微调范式工程化落地,提供标准化tokenizer、模型Hub和Trainer等核心组件。理解attention mask机制与tokenization策略,直接关系到法律文书截断、金融新闻误判等真实问题的解决效率。在资源受限场景下(如16GB GPU),合理配置gradient checkpointing、fp16及Flash Attention,

weixin_34032621的博客 439

如何粗暴地下载huggingface_hub指定数据文件

snapshot_download 函数有点sb的一点是,你的本地目录已经存在了某个文件,你运行snapshot_download之后就重复下载。一看介绍:如果local_dir_use_symlinks=False并且blob文件不在缓存目录中,那么文件会被下载并直接放在local_dir下。snapshot_download 会利用 hf_hub_download 函数实现下载所有文件,hf_hub_download是负责下载单个文件的。可见下载单个文件,下载整个仓库文件都是可行的。

q742971636的博客 3453

transformers环境配置+文本分类实例

注意 transformers==4.33.2 的下载版本,下载太高容易出错。点击生成的网址,在网页中弹出如下结果验证transformers环境搭建成功!最好选用python3.9因为3.8会导致jupyterlab下载失败。这样的话默认使用清华镜像下载,就不会每次都去在指令后添加了。这里选择11以上的且小于你电脑配置的就可以。这里下载所有实验中常见需要的包。

LZL2020LZL的博客 899

TensorFlow深度学习实战——使用Hugging Face构建Transformer模型

本节介绍了如何利用Hugging Face库高效实现Transformer模型的应用,Hugging Face提供了丰富的预训练模型和工具,支持多种自然语言处理任务。首先说明了安装Hugging Face库的方法,并通过情感分析示例验证安装。随后,详细展示了文本生成、自动模型选择与分词、命名实体识别以及摘要生成等任务的实现步骤,均通过Hugging Face的pipeline或相关API轻松完成。最后,重点介绍了模型微调的方法,演示了如何加载数据集、转换为TensorFlow格式、选择预训练模型并进行训练。

盼小辉丶的博客 4116

PyTorch生成式人工智能——Hugging Face环境配置与应用详解

在本节中,我们将介绍如何在 PyTorch 和 TensorFlow 框架中使用 Hugging Face 模型库,我们将讨论如何获取不同的模型以及使用不同管道的步骤,例如,双向自回归 Transformer (BART)、BERT 和 TAPAS 等模型,同时介绍 GPT-2 (Generative Pretrained Transformer 2) 文本生成。需要注意的是,本节主要集中在如何准备环境以及如何使用预训练模型,而不是模型训练,模型训练将在后续学习中详细讨论。

盼小辉丶的博客 2384

Hugging Face Transformer 的APIs应用实例

Hugging Face 的变压器库提供了广泛的 API,可用于处理各种 NLP 任务的预训练变压器模型。在本教程中,我们将探讨主要 API 并提供示例来帮助你了解它们的用法。

gongdiwudu的专栏 6494

Hugging Face模型训练实战详解(NLP+Transformer+PyTorch)下篇

Hugging Face作为现代自然语言处理的基础设施,构建了以库为核心、涵盖模型、数据集和部署工具的完整开发生态。其核心设计理念是“民主化AI”,通过开源促进模型共享与协作创新。# 快速体验NLP任务的极简接口")print(result) # 输出: [{'label': 'POSITIVE', 'score': 0.9998}]该平台不仅提供统一API访问数万个预训练模型,还通过Model Hub实现版本控制、可复现性与社区协作,显著降低NLP应用门槛。

weixin_36064575的博客 1160

CXL ALMP(ARB/MUX Link Management Packet)理解

ALMP(ARB/MUX Link Management Packet) 是CXL协议中由ARB/MUX层生成和处理的专用管理报文,用于协调链路电源状态切换(如L0s/L1)和虚拟链路状态机(vLSM)同步。ALMP是ARB/MUX层的控制平面报文,专用于以下场景:协调多协议(CXL.io、CXL.cachemem等)的链路状态切换(如L1进入/退出)。维护各协议独立的虚拟链路状态机(vLSM) 状态同步。在物理层(PHY)与链路层(Link Layer)之间仲裁电源管理请求。

Summer的博客 1202

6G网络的关键技术、应用前景与挑战并存的科技征途

移动通信技术正以前所未有的速度迭代更新,而6G技术的研发进程渐渐成为了当前科技领域的热点。全球各国已纷纷将目光投向了充满想象的6G时代。本文将探讨全球6G技术研发的最新进展,以及6G技术的核心创新与潜在应用。

fiberroad的博客 2426

【面试系列】软件架构师 高频面试题及详细解答

本文介绍了软件架构师岗位的初级、中级和高级面试题及详细解答,涵盖了系统设计、面向对象设计、分布式系统、云计算技术、性能优化等关键领域。通过这些问题和解答,候选人可以深入理解软件架构师的核心职责和技能要求。此外,文章总结了在面试中需要掌握的常考知识点,包括架构模式、分布式系统管理、安全性、数据管理和DevOps实践。通过掌握这些知识点,软件架构师能够有效设计和指导复杂系统的结构,确保系统的可扩展性、性能和维护性。

在路上的专栏 853

Linux安装Docker(图文解说详细版)

第一步,下载docker 下载地址: https://download.docker.com/linux/static/stable/x86_64/ 这次的演示我们使用docker-18.06.3-ce.tgz 这个版本 第二步,上传到云服务器上面 使用rz命令上传或者fltp工具进行上传 第三步,解压文件 第四步,将解压出来的docker文件复制到 /usr/bin/ 目录下 这么做的目的是将docker交给linux自己去管理,类似spring中的ioc(猜测,非正经知识) cp docker

编码人生 1万+

LLM制造业最佳实践:基于大语言模型处理最优化问题,制造业如何更优排产,提升资源利用率

随着制造业数字化转型加速,生产排产优化成为提升企业效率和竞争力的关键环节。大语言模型(LLM)凭借其强大的多模态数据处理、动态优化和智能推理能力,在复杂排产场景中展现出独特优势。谷歌、DeepSeek等机构的研究表明,LLM可通过自然语言交互和生成式决策,突破传统优化算法的局限性。本报告结合半导体行业实践案例与技术路径,系统分析LLM在排产优化中的应用潜力与挑战。

shiter编写程序的艺术 943

基于STM32、HAL库的BMP585 气压传感器 驱动程序设计

define BMP585_I2C_ADDR_PRIMARY 0x76 << 1 /* 0x76地址左移一位 */#define BMP585_I2C_ADDR_SECONDARY 0x77 << 1 /* 0x77地址左移一位 *//* I2C句柄 *//* I2C地址 *//* 设置新的温度过采样率 *//* 设置新的滤波器系数 *//* 芯片ID *//* 清除温度过采样位 *//* 转换为hPa *//* 设置新的压力过采样率 *//* 设置新的电源模式 *//* 清除压力过采样位 */

corlin6688的博客 463

SAP 经营范围(Operating Concern) 和业务范围 (Business Area) 在核算架构或是管理架构中的区别和联系分别是什么 请给具体的示例

摘要:SAP系统中,业务范围(Business Area)和经营范围(Operating Concern)在核算架构中具有不同功能。业务范围是FI/CO共用维度,用于跨公司码的业务线核算(如电子产品、机械设备),支持内部管理和简单对外报表。经营范围则是CO-PA专属维度,聚焦获利能力分析,可细化到产品+客户+区域组合(如分析手机在华东区域的获利情况)。两者存在层级关联:经营范围包含业务范围作为基础维度,业务范围数据会传递至经营范围进行深度分析。实际应用中需先配置业务范围,再设置经营范围并关联相关维度,共同支

金牌架构师 97

Qt Creator配置MSVC编译环境、调试环境

获取和安装:cdb.exe 在 Debugging tools for Windows 中,而现在已经不单独提供下载,只在Windows SDK 或者Windows Driver Kit里面包含 所以需要下载微软的调试工具,最少需要下载 Windows SDK。在windows上开发,一般使用Qt Creator自带mingw编译器,编译和调试都很方便,安装Qt时勾选后,自动配置完毕。但是有时候我们需要使用MSVC的编译器,这个时候我们没法直接使用,需要配置环境才能使用,以下是配置方案。

希望能帮助大家,希望大家多多支持,你们的支持是我前进的动力。 6993

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

上一篇: TensorFlow深度学习实战——Transformer模型评价指标
下一篇: PyTorch生成式人工智能(11)——神经风格迁移
盼小辉丶
盼小辉丶 优质创作者: 人工智能技术领域 优质创作者: 人工智能技术领域 领域专家: 数据科学与机器学习技术领域 领域专家: 数据科学与机器学习技术领域
博客等级 码龄15年 14万+粉丝 904原创
评论 186
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼小辉丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址