首页 > 其他分享 >利用Tensorflow使用BERT模型+输出句向量和字符向量

利用Tensorflow使用BERT模型+输出句向量和字符向量

时间:2023-05-06 22:31:58浏览次数:46  
标签:bert BERT 模型 input Tensorflow model data 向量


文章目录

  • 1.前言
  • 2.BERT模型
  • 2.1 下载预训练好的模型
  • 2.2 导入BERT模型
  • 2.3 数据下载和预处理
  • 2.4 模型训练
  • 2.5 直接输出BERT模型的句向量或者是字符向量

1.前言

最近想着如何利用tensorflow调用BERT模型,发现其源码已经有比较详细的调用代码,具体的链接如下:https://github.com/google-research/bert/blob/master/predicting_movie_reviews_with_bert_on_tf_hub.ipynb

因此结合上面的例子,主要来构造调用BERT模型。

2.BERT模型

2.1 下载预训练好的模型

我们可以在BERT的github源码中找到已经训练好的模型,其链接如下:https://github.com/google-research/bert

利用Tensorflow使用BERT模型+输出句向量和字符向量_深度学习


可以看到上面有许多已经训练好的模型,可以根据自己的需求找到适合自己的进行下载。下载下来的文件是一个压缩包,解压之后可以看到几个具体文件:

利用Tensorflow使用BERT模型+输出句向量和字符向量_自然语言处理_02

  • bert_config.json:保存的是BERT模型的一些主要参数设置
  • bert_model.ckpt.xxxx:这里有两个文件,但导入模型只需要bert_model.ckpt这个前缀就可以了
  • vocab.txt:用来预训练时的词典

这时候就可以利用这三个文件来导入BERT模型。这三个文件地址可以表示为:

BERT_INIT_CHKPNT="./bert_pretrain_model/bert_model.ckpt"
BERT_VOCAB="./bert_pretrain_model/vocab.txt"
BERT_CONFIG="./bert_pretrain_model/bert_config.json"

2.2 导入BERT模型

首先需要安装好bert-tensorflow和tensorflow-hub,安装bert-tensorflow的命令为:

pip install bert-tensorflow

接着利用bert-tensorflow中的modeling模块导入参数设置和文件:

from bert import modeling

bert_config = modeling.BertConfig.from_json_file(hp.BERT_CONFIG)
model = modeling.BertModel(
    config=bert_config,
    is_training=is_training,
    input_ids=input_ids,
    input_mask=input_mask,
    token_type_ids=segment_ids,
    use_one_hot_embeddings=use_one_hot_embeddings)

2.3 数据下载和预处理

这次的训练数据集是电影评论情感分类,其具有两个类别标签:0(positive)和1(negative)。

具体代码:

import pandas as pd
import tensorflow as tf
import os
import re


# Load all files from a directory in a DataFrame.
def load_directory_data(directory):
    data = {}
    data["sentence"] = []
    data["sentiment"] = []
    for file_path in os.listdir(directory):
        with tf.gfile.GFile(os.path.join(directory, file_path), "r") as f:
            data["sentence"].append(f.read())
            data["sentiment"].append(re.match("\d+_(\d+)\.txt", file_path).group(1))
    return pd.DataFrame.from_dict(data)


# Merge positive and negative examples, add a polarity column and shuffle.
def load_dataset(directory):
    pos_df = load_directory_data(os.path.join(directory, "pos"))
    neg_df = load_directory_data(os.path.join(directory, "neg"))
    pos_df["polarity"] = 1
    neg_df["polarity"] = 0
    return pd.concat([pos_df, neg_df]).sample(frac=1).reset_index(drop=True)


# Download and process the dataset files.
def download_and_load_datasets(force_download=False):
    dataset = tf.keras.utils.get_file(
        fname="aclImdb.tar.gz",
        origin="http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz",
        extract=True)

    train_df = load_dataset(os.path.join(os.path.dirname(dataset), "aclImdb", "train"))
    test_df = load_dataset(os.path.join(os.path.dirname(dataset), "aclImdb", "test"))

    return train_df, test_df


if __name__ == "__main__":
    train, test = download_and_load_datasets()

接下来对特征进行标记化,转换成BERT模型能够识别的特征:

# Convert our train and test features to InputFeatures that BERT understands.
label_list = [int(i) for i in hp.label_list.split(",")]
train_features = run_classifier.convert_examples_to_features(train_InputExamples, label_list, hp.MAX_SEQ_LENGTH,
                                                                      tokenizer)
test_features = run_classifier.convert_examples_to_features(test_InputExamples, label_list, hp.MAX_SEQ_LENGTH,
                                                                     tokenizer)

比如它能够将句子:“This here’s an example of using the BERT tokenizer”转换为:

利用Tensorflow使用BERT模型+输出句向量和字符向量_深度学习_03

2.4 模型训练

(1)可以利用tf.estimator训练:https://github.com/llq20133100095/bert_use/blob/master/model_estimator.py

(2)利用传统的sess和tf.data进行训练:
https://github.com/llq20133100095/bert_use/blob/master/train.py

2.5 直接输出BERT模型的句向量或者是字符向量

在BERT源码中,只要设置model.get_pooled_output和model.get_sequence_output就能得到句向量和字符向量:

def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, use_one_hot_embeddings, use_sentence):
    """Creates a classification model."""
    model = modeling.BertModel(
      config=bert_config,
      is_training=is_training,
      input_ids=input_ids,
      input_mask=input_mask,
      token_type_ids=segment_ids,
      use_one_hot_embeddings=use_one_hot_embeddings)

    # Use "pooled_output" for classification tasks on an entire sentence.
    # Use "sequence_outputs" for token-level output.
    if use_sentence:
        output_layer = model.get_pooled_output()
    else:
        output_layer = model.get_sequence_output()

    return output_layer

具体代码可以参考:https://github.com/llq20133100095/bert_use/blob/master/get_embedding.py


标签:bert,BERT,模型,input,Tensorflow,model,data,向量
From: https://blog.51cto.com/u_12243550/6251284

相关文章

  • 向量数据库
    1.向量概念向量是一种在数学和物理学中常用的概念,通常表示为一个有序的数值序列,可以用来表示空间中的位置、速度、加速度、力等物理量。多维度-->多个标量一个向量通常由多个标量组成,这些标量表示在不同维度上的数值。例如,在二维平面上,一个向量可以由两个标量x和y表示,其中x表示......
  • gpt bert
    Transformer的结构标准的Transformer模型主要由两个模块构成:Encoder(左边):负责理解输入文本,为每个输入构造对应的语义表示(语义特征),;Decoder(右边):负责生成输出,使用Encoder输出的语义表示结合其他输入来生成目标序列。这两个模块可以根据任务的需求而单独使用:纯Encoder......
  • 超越 PyTorch 和 TensorFlow,这个国产框架有点东西
    By超神经内容概要:都已经有这么多深度学习框架了,为什么还要搞个OneFlow?在机器学习领域,袁进辉看的比90%的人都长远。 关键词:开源  深度学习框架  OneFlow在深度学习领域,PyTorch、TensorFlow等主流框架,毫无疑问占据绝大部分市场份额,就连百度这样级别的公司,也是花费了大量......
  • 【论文解读】BERT和ALBERT
    文章目录1.前言2.BERT2.1引入2.2以前的工作2.2.1feature-based方法2.2.2fine-tuning方法2.2.3迁移学习方法2.3BERT架构2.3.1MLM2.3.2NSP2.4实验2.4.1BERT模型的效果2.4.2验证性实验3.ALBERT3.1引入3.2相关工作3.2.1cross-layerparametersharing(交叉层的参数共享......
  • 基于麻雀算法优化的相关向量机RVM回归预测算法
    基于麻雀算法优化的相关向量机RVM回归预测算法文章目录基于麻雀算法优化的相关向量机RVM回归预测算法1.RVM原理2.基于麻雀算法优化的相关向量机RVM3.算法实验与结果3.参考文献:4.MATLAB代码摘要:本文主要介绍相关向量机RVM的基本原理,以及在预测问题中的应用。1.RVM原理RVM算法是......
  • 灰狼/狼群算法优化支持向量机SVM分类预测matlab代码,支持多分类。
    灰狼/狼群算法优化支持向量机SVM分类预测matlab代码,支持多分类。Excel数据格式,直接运行。ID:22100625660395512......
  • 6.3.2—6.3.4 平面向量的坐标运算
    \({\color{Red}{欢迎到学科网下载资料学习}}\)[【基础过关系列】高一数学同步精品讲义与分层练习(人教A版2019)](https://www.zxxk.com/docpack/2921718.html)\({\color{Red}{跟贵哥学数学,so\quadeasy!}}\)必修第二册同步巩固,难度2颗星!基础知识正交分解及其坐标表示①......
  • 6.3.1 平面向量的基本定理
    \({\color{Red}{欢迎到学科网下载资料学习}}\)[【基础过关系列】高一数学同步精品讲义与分层练习(人教A版2019)](https://www.zxxk.com/docpack/2921718.html)\({\color{Red}{跟贵哥学数学,so\quadeasy!}}\)必修第二册同步巩固,难度2颗星!基础知识平面向量的基本定理设\(......
  • 6.2.4 向量的数量积
    \({\color{Red}{欢迎到学科网下载资料学习}}\)[【基础过关系列】高一数学同步精品讲义与分层练习(人教A版2019)](https://www.zxxk.com/docpack/2921718.html)\({\color{Red}{跟贵哥学数学,so\quadeasy!}}\)必修第二册同步巩固,难度2颗星!基础知识概念如果两个非零向量\(......
  • 6.2.2 向量的减法运算
    \({\color{Red}{欢迎到学科网下载资料学习}}\)[【基础过关系列】高一数学同步精品讲义与分层练习(人教A版2019)](https://www.zxxk.com/docpack/2921718.html)\({\color{Red}{跟贵哥学数学,so\quadeasy!}}\)必修第二册同步巩固,难度2颗星!基础知识相反向量我们规定,与向量......