tf.keras.preprocessing.text.Tokenizer函数

本文详细介绍了TensorFlow Keras库中的Tokenizer函数,从函数原型、参数解读到实际应用,涵盖了词频统计、文本切分、字符级别处理及oov_token的使用。通过实例演示,学习如何构建、配置和利用Tokenizer进行高效的数据预处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数原型
tf.keras.preprocessing.text.Tokenizer(
    num_words=None,
    filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
    lower=True,
    split=' ',
    char_level=False,
    oov_token=None,
    document_count=0,
    **kwargs
)
函数说明

Tokenizer函数用于创建一个分词器对象tokenizer。参数num_words用于表示应该保持的最大的单词数,如果小于输入数据所构成词汇表的不同的单词数,则一部分单词会被删掉。默认值为None,表示应该保持的单词数和词汇表的一致。

参数filters表示应该被过滤的单词或者字符。参数lower表示输入的大写字母是否应该转换成小写字母,默认为True。参数split表示用于分词的分隔符,默认情况下,文本变成以空格分隔的单词序列(单词可能包括 ’ 字符)。

参数char_level表示是对一个单词进行分割还是对一个字符进行分割,默认为True,表示对一个字符进行分割。

参数oov_token如果给定,它将被添加到 word_index 并用于在 text_to_sequence 调用期间替换词汇表外的单词。

tokenizer对象具有以下常用属性和方法:

1、fit_on_texts(texts):根据文本来更新内部词汇表,如果texts为一个字符串,那么结果都将按照字符划分;如果texts为一个字符串列表,比如[“hello world”]、[“hello”, “world”],则如果设置char_level=False,分词器按照单词划分。

2、get_config():获取分词器的配置,里面有word_index、index_word、word_docs、index_docs、document_count、word_counts等常用的信息。

3、sequences_to_texts(sequences):将数字序列转换成文本,形式为[[4], [3], [2], [2]]或者[[4, 3, 2, 2]]的列表或者numpy数组。

4、texts_to_sequences(texts):将文本转换成数字序列。

5、word_index:一个将文本映射为数字的字典

6、index_word:一个将数字映射为文本的字典

函数使用
# 根据字符划分
# 创建一个分词器
>>> tokenizer = tf.keras.preprocessing.text.Tokenizer()
>>> text = "hello tensorflow"
# 根据文本更新内部分词器信息
>>> tokenizer.fit_on_texts(text)
# 获取配置信息
>>> config = tokenizer.get_config()
>>> config
{
'num_words': None,
'filters': '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
'lower': True, 
'split': ' ', 
'char_level': False, 
'oov_token': None, 
'document_count': 16,
'word_counts': '{"h": 1, "e": 2, "l": 3, "o": 3, "t": 1, "n": 1, "s": 1, "r": 1, "f": 1, "w": 1}',
'word_docs': '{"h": 1, "e": 2, "l": 3, "o": 3, "t": 1, "n": 1, "s": 1, "r": 1, "f": 1, "w": 1}', 
'index_docs': '{"4": 1, "3": 2, "1": 3, "2": 3, "5": 1, "6": 1, "7": 1, "8": 1, "9": 1, "10": 1}', 
'index_word': '{"1": "l", "2": "o", "3": "e", "4": "h", "5": "t", "6": "n", "7": "s", "8": "r", "9": "f", "10": "w"}', 
'word_index': '{"l": 1, "o": 2, "e": 3, "h": 4, "t": 5, "n": 6, "s": 7, "r": 8, "f": 9, "w": 10}'
}
# 获取word_index字典
>>> tokenizer.word_index
'{"l": 1, "o": 2, "e": 3, "h": 4, "t": 5, "n": 6, "s": 7, "r": 8, "f": 9, "w": 10}'
# 有时需要获取词汇表的vocab_size
>>> vocab_size = len(tokenizer.word_index)
>>> vacab_size
10
# 文本转换成序列
>>> seq = tokenizer.texts_to_sequences("hello")
>>> seq
[[4], [3], [1], [1], [2]]
# 序列转换成文本,三种情况
>>> texts = tokenizer.sequences_to_texts([[4],[3],[1],[1],[2]])
>>> texts
['h', 'e', 'l', 'l', 'o']
>>> texts = tokenizer.sequences_to_texts([[4, 3, 1, 1, 2]])
>>> texts
['h e l l o']
>>> texts = tokenizer.sequences_to_texts(np.array([[4, 3, 1, 1, 2]]))
>>> texts
['h e l l o']

# 根据单词划分
>>> tokenizer = tf.keras.preprocessing.text.Tokenizer()
>>> texts = "hello tensorflow"
>>> text_list = tf.keras.preprocessing.text.text_to_word_sequence(texts)
>>> text_list
['hello', 'tensorflow']
>>> tokenizer.fit_on_texts(text_list)
>>> tokenizer.texts_to_sequences(text_list)
[[1], [2]]
>>> texts = "hello tensorflow"
>>> tokenizer.texts_to_sequences([texts])
[[1, 2]]
>>> tokenizer.word_index
{'hello': 1, 'tensorflow': 2}
# 设置参数oov_token
>>> tokenizer = tf.keras.preprocessing.text.Tokenizer(oov_token="mask")
>>> tokenizer.fit_on_texts(text_list)
>>> tokenizer.sequences_to_texts([[1, 2]])
['mask hello']
>>> tokenizer.word_index
{'mask': 1, 'hello': 2, 'tensorflow': 3}
import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler, OneHotEncoder import tensorflow from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Dense, Embedding, LSTM, Concatenate, Dropout, BatchNormalization from tensorflow.keras.optimizers import Adam from sklearn.model_selection import train_test_split from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau # 1.数据预处理与特征工程 # 加载数据集 df = pd.read_csv("training_data.csv") # 数值特征标准化 num_features = ['position', 'quality'] scaler = MinMaxScaler() df[num_features] = scaler.fit_transform(df[num_features]) # 序列特征编码 tokenizer = Tokenizer(char_level=True, num_words=4) # 仅A,C,G,T四种碱基 tokenizer.fit_on_texts(df['context']) sequences = tokenizer.texts_to_sequences(df['context']) max_length = max(len(seq) for seq in sequences) padded_sequences = pad_sequences(sequences, maxlen=max_length, padding='post') # 标签提取 labels = df['label'].values # 2.双输入混合模型架构 # 序列输入分支 sequence_input = Input(shape=(max_length,), name='sequence_input') embedding = Embedding(input_dim=5, output_dim=8, input_length=max_length)(sequence_input) # 5=4碱基+填充 lstm_out = LSTM(32, return_sequences=False)(embedding) # 数值特征输入分支 numeric_input = Input(shape=(len(num_features),), name='numeric_input') dense_numeric = Dense(16, activation='relu')(numeric_input) bn_numeric = BatchNormalization()(dense_numeric) # 合并分支 concatenated = Concatenate()([lstm_out, bn_numeric]) dense1 = Dense(64, activation='relu')(concatenated) dropout1 = Dropout(0.3)(dense1) dense2 = Dense(32, activation='relu')(dropout1) output = Dense(1, activation='sigmoid')(dense2) # 构建模型 model = Model(inputs=[sequence_input, numeric_input], outputs=output) model.compile( optimizer=Adam(learning_rate=0.001), loss='binary_crossentropy', metrics=['accuracy', 'AUC'] ) model.summary() # 3.模型训练与评估 # 划分训练集和测试集 X_seq_train, X_seq_test, X_num_train, X_num_test, y_train, y_test = train_test_split( padded_sequences, df[num_features].values, labels, test_size=0.2, stratify=labels ) # 回调函数 callbacks = [ EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True), ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=1e-6) ] # 训练模型 history = model.fit( [X_seq_train, X_num_train], y_train, validation_data=([X_seq_test, X_num_test], y_test), epochs=100, batch_size=64, callbacks=callbacks, class_weight={0: 1, 1: 2} # 处理类别不平衡 ) # 评估模型 test_loss, test_acc, test_auc = model.evaluate( [X_seq_test, X_num_test], y_test ) print(f"测试准确率: {test_acc:.4f}, AUC: {test_auc:.4f}") 请优化该代码 tensorflow.keras.preprocessing.text tensorflow.keras.preprocessing.sequence tensorflow.keras.models tensorflow.keras.layers tensorflow.keras.optimizers tensorflow.keras.callbacks 无法导入
最新发布
07-19
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不负韶华ღ

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

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

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

打赏作者

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

抵扣说明:

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

余额充值