tensorflow tf.pad解析

tf.pad的作用是填充

它的表达式如下:

 

pad(
    tensor,
    paddings,
    mode='CONSTANT',
    name=None
)

tensor是要填充的张量

 

padings 也是一个张量,代表每一维填充多少行/列,但是有一个要求它的rank一定要和tensor的rank是一样的

mode 可以取三个值,分别是"CONSTANT" ,"REFLECT","SYMMETRIC"

mode="CONSTANT" 是填充0

mode="REFLECT"是映射填充,上下(1维)填充顺序和paddings是相反的,左右(零维)顺序补齐

mode="SYMMETRIC"是对称填充,上下(1维)填充顺序是和paddings相同的,左右(零维)对称补齐

 

本例使用的tensor都是rank=2的,注意paddings的rank也要等于2,否则报错

padding

{

for example:

t=[[2,3,4],[5,6,7]],paddings=[[1,1],[2,2]],mode="CONSTANT"

那么sess.run(tf.pad(t,paddings,"CONSTANT"))的输出结果为:

array([[0, 0, 0, 0, 0, 0, 0],
          [0, 0, 2, 3, 4, 0, 0],
          [0, 0, 5, 6, 7, 0, 0],
          [0, 0, 0, 0, 0, 0, 0]], dtype=int32)

可以看到,上,下,左,右分别填充了1,1,2,2行刚好和paddings=[[1,1],[2,2]]相等,零填充

 

 for example :

t=[[2,3,4],[5,6,7]], paddings=[[1,2],[2,3]],mode="CONSTANT"

sess.run(tf.pad(t,paddings,"CONSTANT"))的输出结果为:

 

array([[0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 2, 3, 4, 0, 0, 0],
          [0, 0, 5, 6, 7, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)

可以看到,上,下,左,右分别填充啦1,2,2,3行刚好和paddings=[[1,2],[2,3]]相等,零填充

}

 

mode

{

for example:

t=[[2,3,4],[5,6,7]], paddings=[[1,1],[2,2]], mode='REFLECT'

sess.run(tf.pad(t,paddings,"REFLECT"))的输出结果为:

array([[7, 6, 5, 6, 7, 6, 5],
           [4, 3, 2, 3, 4, 3, 2],
           [7, 6, 5, 6, 7, 6, 5],
           [4, 3, 2, 3, 4, 3, 2]], dtype=int32)

可以看到,上下左右的值进行了映射填充,上下值填充的顺序和t是相反的,左右值只是进行顺序补齐

 

 

for example:

t=[[2,3,4],[5,6,7]], paddings=[[1,1],[2,2]], mode='SYMMETRIC'

sess.run(tf.pad(t,paddings,"SYMMETRIC"))的输出结果为:

array([[3, 2, 2, 3, 4, 4, 3],
          [3, 2, 2, 3, 4, 4, 3],
          [6, 5, 5, 6, 7, 7, 6],
          [6, 5, 5, 6, 7, 7, 6]], dtype=int32)

可以看到,上下左右的值进行了对称填充,上下值是按照t相同顺序填充的,左右值只是进行对称补齐

}

``` from transformers import BertTokenizer, TFBertForSequenceClassification from tensorflow.keras.optimizers import Adam from tensorflow.keras.losses import SparseCategoricalCrossentropy # 加载BERT预训练模型和分词器 tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = TFBertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2) # 编译模型 model.compile(optimizer=Adam(learning_rate=3e-5), loss=SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) # 加载IMDB数据集 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(num_words=10000) # 数据预处理 maxlen = 100 x_train = pad_sequences(x_train, maxlen=maxlen) x_test = pad_sequences(x_test, maxlen=maxlen) # 将数据转换为BERT输入格式 def encode_data(texts, labels): input_ids = [] attention_masks = [] for text in texts: encoded = tokenizer.encode_plus( text, add_special_tokens=True, max_length=maxlen, pad_to_max_length=True, return_attention_mask=True, return_tensors='tf' ) input_ids.append(encoded['input_ids']) attention_masks.append(encoded['attention_mask']) return { 'input_ids': tf.concat(input_ids, axis=0), 'attention_mask': tf.concat(attention_masks, axis=0) }, tf.convert_to_tensor(labels) train_data, train_labels = encode_data(x_train, y_train) test_data, test_labels = encode_data(x_test, y_test) # 训练模型 model.fit(train_data, train_labels, epochs=3, batch_size=32, validation_data=(test_data, test_labels)) # 评估模型 test_loss, test_acc = model.evaluate(test_data, test_labels) print(f'迁移学习模型在IMDB测试集上的准确率: {test_acc}')```解释代码
最新发布
03-19
这段代码展示了如何利用BERT预训练模型结合TensorFlow框架完成文本分类任务,并以IMDB情感分析为例演示了具体的步骤。以下是详细的解释: --- ### **代码逐段解析** #### 1. 导入必要的库和模块 ```python from transformers import BertTokenizer, TFBertForSequenceClassification from tensorflow.keras.optimizers import Adam from tensorflow.keras.losses import SparseCategoricalCrossentropy ``` 这里导入了一些关键工具: - `BertTokenizer` 和 `TFBertForSequenceClassification` 来自 Hugging Face 的 `transformers` 库,用于加载 BERT 预训练模型及其对应的分词器。 - `Adam` 是一种优化算法,在深度学习中广泛使用。 - `SparseCategoricalCrossentropy` 是 TensorFlow 提供的一种损失函数,适用于多类别分类问题。 --- #### 2. 加载 BERT 模型及分词器 ```python tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = TFBertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2) ``` - 使用 `BertTokenizer.from_pretrained()` 载入了一个基于英文小写字母的 BERT 分词器 (`bert-base-uncased`)。 - 使用 `TFBertForSequenceClassification.from_pretrained()` 载入一个经过微调、可以进行序列分类的任务版本的 BERT 模型。其中 `num_labels=2` 表示这是一个二分类问题(例如正面 vs 反面情绪)。 --- #### 3. 编译模型 ```python model.compile(optimizer=Adam(learning_rate=3e-5), loss=SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) ``` - 设置模型的优化器为 Adam,初始学习率为 \( 3 \times 10^{-5} \)。 - 定义损失函数为稀疏交叉熵(适合标签为整数的情况),并指定 `from_logits=True` 表明模型输出的是未归一化的 logits 值而不是概率值。 - 监控指标设为了准确率 (`metrics=['accuracy']`)。 --- #### 4. 加载 IMDB 数据集 ```python (x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(num_words=10000) ``` 从 Keras 内置数据集中获取 IMDB 影评数据集,默认限制词汇表大小为前 10000 最常见的单词。 --- #### 5. 数据预处理 - 截断填充到固定长度 ```python maxlen = 100 x_train = pad_sequences(x_train, maxlen=maxlen) x_test = pad_sequences(x_test, maxlen=maxlen) ``` 将每个影评截断或补齐至统一的最大长度(本例设置为 100)。这一步是为了适应 BERT 输入的需求——所有输入句子需要有相同的长度。 --- #### 6. 自定义编码函数:将原始数据转化为 BERT 格式 ```python def encode_data(texts, labels): input_ids = [] attention_masks = [] for text in texts: encoded = tokenizer.encode_plus( text, add_special_tokens=True, max_length=maxlen, pad_to_max_length=True, return_attention_mask=True, return_tensors='tf' ) input_ids.append(encoded['input_ids']) attention_masks.append(encoded['attention_mask']) return { 'input_ids': tf.concat(input_ids, axis=0), 'attention_mask': tf.concat(attention_masks, axis=0) }, tf.convert_to_tensor(labels) ``` 该函数的作用是对每一条评论应用 BERT 的 tokenization 过程,生成模型所需的两个重要张量: - `input_ids`: 对应于分词后的 ID 列表; - `attention_mask`: 描述哪些位置有效(非填充部分为 1,其余为 0)。 随后返回打包好的字典以及标签张量。 **注意**: 此处直接传入了数字列表作为 `texts` 参数,但实际上应该先对索引形式的数据逆映射成字符串形式再传递给此函数! --- #### 7. 准备训练与测试数据 ```python train_data, train_labels = encode_data(x_train, y_train) test_data, test_labels = encode_data(x_test, y_test) ``` 通过上述编码函数分别准备出训练和验证阶段使用的特征矩阵以及对应的目标变量。 --- #### 8. 开始训练 ```python model.fit(train_data, train_labels, epochs=3, batch_size=32, validation_data=(test_data, test_labels)) ``` 启动模型拟合流程,迭代次数为 3 轮次,每次批量采样规模设定为 32 个样本;同时提供了一组独立的验证集合来监控性能变化趋势。 --- #### 9. 测试评价 ```python test_loss, test_acc = model.evaluate(test_data, test_labels) print(f'迁移学习模型在IMDB测试集上的准确率: {test_acc}') ``` 最后用最终版网络架构评估一次整体效果,打印结果中的正确预测比例即为目标精度数值。 --- ### **总结** 这段脚本完整地实现了端到端的情感分类建模工作流,包括但不限于数据读取 -> 文本向量化 -> 网络初始化 -> 微调整优等一系列环节操作。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值