vocab 文本_持续更新:那些Keras中文本预处理超好用API

e2fbd767da8ab31c984dc6c97a33d264.png
import tensorflow as tf
from tensorflow import keras
import numpy as np

Tokenizer : 文本到序列的映射1

  • fit_on_sequence
  • fit_on_texts
  • get_config
  • sequences_to_test ....
from tensorflow.keras.preprocessing.text import Tokenizer

# 导入文本数据
with open("shakespeare.txt",'r',encoding='utf=8') as f:
    text = f.read()

print(text[:100])

First Citizen:
Before we proceed any further, hear me speak.

All:
Speak, speak.

First Citizen:
You

# 初始化 tokenizer,oov_token是指语料库中不存在的单词,这里假定所有不存在的单词都为<unk>
tokernizer = Tokenizer(char_level=False,oov_token='<unk>')

# 在给定的语料库中训练,之后tokernizer能够映射任意给定的文本到序列
tokernizer.fit_on_texts([text])

sequences = tokernizer.texts_to_sequences(["Before we proceed any further, hear me speak."])
print(sequences)

sequences = tokernizer.texts_to_sequences(["First Citizen:"])
print(sequences)

sequences = tokernizer.texts_to_sequences(["Hello world and hi"])
print(sequences)

[[140, 36, 970, 144, 669, 128, 16, 103]]
[[89, 270]]
[[1, 187, 3, 1]]

# tokenizer.word_index 用来查看 tokenizer 中 token被编码的序号
tokenizer.word_index

9314bb73f42efbb9a74b3fd537735447.png
oov_token被编码在第一个位置,之后按照词频编码

one_hot :文本到序列的映射2

from tensorflow.keras.preprocessing.text import one_hot

# 参数 n 是vocab_size,字典大小,应当尽可能大,否则会出现两个单词相同映射的情况
one_hot("Before we proceed any further ha",n=128) 
[4, 106, 102, 87, 62, 96]

# 这里出现了 we 和 any 映射出的整数相同。
one_hot("Before we proceed any further ha",n=10) 
[8, 9, 2, 9, 2, 8]

text_to_word_sequence : 分词工具

from tensorflow.keras.preprocessing.text import text_to_word_sequence

print(text_to_word_sequence("Before we proceed any further, hear me speak.First Citizen:You"))

['before', 'we', 'proceed', 'any', 'further', 'hear', 'me', 'speak', 'first', 'citizen', 'you']

pad_sequences : padding工具

这个API是NLP的利器,大多数模型要求序列长度固定,但我们知道文本中sentence的长度不是固定的。因此我们就需要这个API对序列的长度进行padding或者truncating

'''
tf.keras.preprocessing.sequence.pad_sequences(
    sequences, maxlen=None, dtype='int32', padding='pre',
    truncating='pre', value=0.0
)
'''
t1 = tf.constant([[1,2,3,7,8],[1,2,5,7,8]])
t1
<tf.Tensor: id=0, shape=(2, 5), dtype=int32, numpy=
array([[1, 2, 3, 7, 8],
       [1, 2, 5, 7, 8]])>

# 默认 padding='pre',在前方填充,默认value=0.0,使用0值填充
keras.preprocessing.sequence.pad_sequences(t1,maxlen=7) # 将t1 填充至(2,7)
array([[0, 0, 1, 2, 3, 7, 8],
       [0, 0, 1, 2, 5, 7, 8]])

# 指定 padding='post',在后方填充
keras.preprocessing.sequence.pad_sequences(t1,maxlen=7,padding='post')
array([[1, 2, 3, 7, 8, 0, 0],
       [1, 2, 5, 7, 8, 0, 0]])

# 使用指定值填充
keras.preprocessing.sequence.pad_sequences(t1,maxlen=7,padding='post',value=1)
array([[1, 2, 3, 7, 8, 1, 1],
       [1, 2, 5, 7, 8, 1, 1]])

# truncating='pre' 当序列长度超过maxlen参数,会从前方截断,post则从后方截断
keras.preprocessing.sequence.pad_sequences(t1,maxlen=3,truncating='post')
array([[1, 2, 3],
       [1, 2, 5]])

to_categorical : 类别标签一键one_hot

在实际应用中,我们经常需要将类别标签y进行 one_hot 编码,to_categorical函数很好地解决了这个问题

from tensorflow.keras.utils import to_categorical

y = [0,0,3,5,1,4,2,2,1]
to_categorical(y)
array([[1., 0., 0., 0., 0., 0.],
       [1., 0., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 0., 1.],
       [0., 1., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0.],
       [0., 0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0.]], dtype=float32)

# 指定 class 的数量
y = [0,0,3,5,1,4,2,2,1]
to_categorical(y,num_classes=8)
array([[1., 0., 0., 0., 0., 0., 0., 0.],
       [1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 1., 0., 0.],
       [0., 1., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0., 0., 0.]], dtype=float32)

KeyValueTensorInitializer & StaticVocabularyTable : 类别映射到索引

vocab = ["Up",'Down','Left','Right'] # 词汇表,所有可能的类别的列表
indices = tf.range(len(vocab),dtype=tf.int64) # 词汇表索引的张量
table_init = tf.lookup.KeyValueTensorInitializer(vocab,indices)
num_oov = 3
table = tf.lookup.StaticVocabularyTable(table_init,num_oov) # 查找表
# 创建了查找表之后,我们就可以对任意的类别进行索引编码
categories = tf.constant(['Down','Down','Right','Up','Up','Unknown'])
table.lookup(categories)

<tf.Tensor: id=167, shape=(6,), dtype=int64, numpy=array([1, 1, 3, 0, 0, 6], dtype=int64)>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Python使用Keras训练对话机器人可以通过以下步骤实现: 1. 数据预处理:首先,你需要准备用于训练的对话数据。这些数据可以是一系列的问答对,其每个问答对都是一个输入和一个对应的输出。你可以使用自己的语料库或者从互联网上找到适合的对话数据集。然后,你需要对数据进行预处理,包括分词、去除停用词、标记化等操作。 2. 构建模型:接下来,你需要构建一个适合对话机器人的模型。在Keras,你可以使用Sequential模型或者函数式API来构建模型。你可以选择使用循环神经网络(RNN)或者变种(如长短期记忆网络LSTM)来处理对话序列。你还可以添加嵌入层、隐藏层和输出层来构建完整的模型。 3. 训练模型:一旦你构建好模型,你可以使用Keras提供的compile()函数来编译模型,并使用fit()函数来训练模型。你需要指定训练数据、验证数据、损失函数、优化器和训练的批次大小等参数。通过多次迭代训练,模型将逐渐学习到对话数据的模式和规律。 4. 评估模型:在训练过程,你可以使用验证数据来评估模型的性能。你可以计算模型的准确率、损失值等指标来评估模型的效果。如果模型的性能不够好,你可以调整模型的结构或者超参数来改进模型。 5. 使用模型进行对话:一旦你训练好了模型,你可以使用它来进行对话。你可以将用户的输入转化为模型可以理解的格式,并使用模型的predict()函数来生成对应的回答。你可以根据模型的输出选择最合适的回答,并将其返回给用户。 下面是一个使用Keras训练对话机器人的示例代码: ```python from keras.models import Sequential from keras.layers import Embedding, LSTM, Dense # 构建模型 model = Sequential() model.add(Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=max_seq_length)) model.add(LSTM(units=hidden_units)) model.add(Dense(units=vocab_size, activation='softmax')) # 编译模型 model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 训练模型 model.fit(x_train, y_train, batch_size=batch_size, epochs=num_epochs, validation_data=(x_val, y_val)) # 使用模型进行对话 def generate_response(input_text): # 将输入文本转化为模型可以理解的格式 input_seq = tokenizer.texts_to_sequences([input_text]) input_seq = pad_sequences(input_seq, maxlen=max_seq_length) # 使用模型生成回答 output_seq = model.predict(input_seq) output_text = tokenizer.sequences_to_texts([output_seq])[0] return output_text ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值