使用 BERT 进行文本分类的简单代码示例

好的,这是一个使用 BERT 进行文本分类的简单代码示例:

首先,导入所需的库:

import tensorflow as tf
import tensorflow_hub as hub

from tensorflow.keras import layers

然后,加载 BERT 预训练模型:

bert_model = "https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1"
bert_layer = hub.KerasLayer(bert_model, trainable=True)

接下来,构建模型的输入层:

input_ids = layers.Input(shape=(None,),dtype=tf.int64, name="input_ids")
input_mask = layers.Input(shape=(None,), dtype=tf.int64, name="input_mask")
segment_ids = layers.Input(shape=(None,), dtype=tf.int64, name="segment_ids")

对输入文本使用 BERT 层进行编码:

pooled_output, sequence_output = bert_layer([input_ids, input_mask, segment_ids])

接下来,你可以使用序列输出或者池化输出来构建你的分类模型。

例如,如果你想使用池化输出,你可以这样做:

x = layers.Dropout(0.1)(pooled_output)
x = layers.Dense(64, activation='relu')(x)
x = layers.Dropout(0.1)(x)
predictions = layers.Dense(2, activation='softmax')(x)

最后,你可以使用 Model 类来实例化你的模型:

model = tf.keras.Model(inputs=[input_ids, input_mask, segment_ids], outputs=predictions)

你可以使用传统的机器学习方法对模型进行编译和训练。

```python model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值