详解Keras3.0 KerasNLP Models: GPT2 GPT2Tokenizer

1、GPT2Tokenizer

用于将文本数据转换为适合训练和预测的格式,主要功能是将输入的文本进行分词、编码等操作,以便在神经网络中使用

keras_nlp.models.GPT2Tokenizer(vocabulary, merges, **kwargs)
参数说明 
  • vocabulary一个字典,包含词汇表的映射关系。键是单词,值是对应的索引。
  • merges一个列表,包含合并规则。每个元素是一个元组,表示两个需要合并的单词及其对应的索引。
  • **kwargs其他可选参数。
示例
from keras_nlp.models import GPT2Tokenizer

# 定义词汇表和合并规则
vocabulary = {"hello": 1, "world": 2, "!": 3}
merges = [(1, 2)]

# 创建分词器实例
tokenizer = GPT2Tokenizer(vocabulary, merges)

# 对文本进行分词和编码
text = "hello world!"
encoded_text = tokenizer.encode(text)
print(encoded_text)  # 输出:[1, 2, 3]

# 对编码后的文本进行解码
decoded_text = tokenizer.decode(encoded_text)
print(decoded_text)  # 输出:"hello world!"

 

2、from_preset

GPT2Tokenizer.from_preset()是Hugging Face的Transformers库中的一个函数,用于从预定义的预设中加载一个GPT-2分词器。这个函数可以帮助你快速地创建一个适用于特定任务的分词器,而无需从头开始训练。

GPT2Tokenizer.from_preset("gpt2_base_en")
参数说明 

在这个例子中,我们加载的是"gpt2_base_en"预设,它包含了英文版本的GPT-2模型的基本参数和词汇表

示例
from transformers import GPT2Tokenizer

# 创建分词器
tokenizer = GPT2Tokenizer.from_pretrained("gpt2_base_en")

# 对输入进行分词
tokens = tokenizer("The quick brown fox tripped.")
print(tokens)  # 输出:{'input_ids': [31474, 2024, 2003, 1037, 2327, 102], 'attention_mask': [1, 1, 1, 1, 1, 1]}

# 对输入进行反分词
text = tokenizer.decode(tokens['input_ids'])
print(text)  # 输出:"The quick brown fox tripped."
  • gpt2_base_en:这是一个12层的GPT-2模型,参数量为124.44M,保持了大小写。它使用WebText数据集进行训练。
  • gpt2_medium_en:这是一个24层的GPT-2模型,参数量为354.82M,保持了大小写。它也使用WebText数据集进行训练。
  • gpt2_large_en:这是一个36层的GPT-2模型,参数量为774.03M,保持了大小写。同样使用WebText数据集进行训练。
  • gpt2_extra_large_en:这是一个48层的GPT-2模型,参数量为1.56B,保持了大小写。它也使用WebText数据集进行训练。
  • gpt2_base_en_cnn_dailymail:这是一个12层的GPT-2模型,参数量为124.44M,保持了大小写。它使用CNN/DailyMail摘要生成数据集进行微调。
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是使用Python语言,基于GPT2实现文本分类的详细代码: 首先,我们需要安装必要的库,包括tensorflow、numpy、scikit-learn、nltk等: ```python !pip install tensorflow==1.15.2 !pip install numpy !pip install scikit-learn !pip install nltk ``` 接下来,我们需要加载GPT2模型,这里我们选择使用已经预训练好的GPT2模型,可以通过Hugging Face提供的transformers库进行加载: ```python from transformers import TFGPT2Model, GPT2Tokenizer model = TFGPT2Model.from_pretrained('gpt2') tokenizer = GPT2Tokenizer.from_pretrained('gpt2') ``` 然后,我们需要准备训练数据和测试数据,这里我们选择使用20类新闻数据集作为样例数据: ```python from sklearn.datasets import fetch_20newsgroups from sklearn.model_selection import train_test_split data = fetch_20newsgroups(subset='all', shuffle=True, random_state=42) X = data.data y = data.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 接下来,我们需要将文本数据转换为GPT2模型所需的输入格式,这里我们使用tokenizer进行处理: ```python import numpy as np max_length = 128 def convert_to_input(texts): input_ids = [] attention_masks = [] for text in texts: encoded = tokenizer.encode_plus(text, add_special_tokens=True, max_length=max_length, padding='max_length', return_attention_mask=True, return_token_type_ids=False, truncation=True) input_ids.append(encoded['input_ids']) attention_masks.append(encoded['attention_mask']) return np.array(input_ids), np.array(attention_masks) X_train_input_ids, X_train_attention_masks = convert_to_input(X_train) X_test_input_ids, X_test_attention_masks = convert_to_input(X_test) ``` 然后,我们需要定义模型的输入和输出,以及模型的结构和参数: ```python import tensorflow as tf input_ids = tf.keras.layers.Input(shape=(max_length,), dtype=tf.int32, name='input_ids') attention_masks = tf.keras.layers.Input(shape=(max_length,), dtype=tf.int32, name='attention_masks') output = model({'input_ids': input_ids, 'attention_mask': attention_masks})[0] output = tf.keras.layers.Dense(20, activation='softmax')(output) model = tf.keras.models.Model(inputs=[input_ids, attention_masks], outputs=output) optimizer = tf.keras.optimizers.Adam(lr=2e-5, epsilon=1e-08, decay=0.01) model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.summary() ``` 接下来,我们可以开始训练模型: ```python epochs = 3 batch_size = 16 history = model.fit( [X_train_input_ids, X_train_attention_masks], y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2 ) ``` 最后,我们可以评估模型的性能: ```python from sklearn.metrics import classification_report y_pred = model.predict([X_test_input_ids, X_test_attention_masks]) y_pred = np.argmax(y_pred, axis=1) print(classification_report(y_test, y_pred)) ``` 以上就是使用Python语言,基于GPT2实现文本分类的详细代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

缘起性空、

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

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

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

打赏作者

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

抵扣说明:

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

余额充值