如何获得BERT的preproc

时间:2019-10-29 07:38:42

标签: python keras

我正在使用stackoverflow选项卡分类csv数据集,已将其加载到数据框中:

X = df.post
y = df.tags
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state = 42)

除了其他一些分类模型外,我还想运行BERT,但是它需要变量preproc。我不确定哪个函数可以实现:

import ktrain
from ktrain import text
model = text.text_classifier('bert', (x_train, y_train), preproc=preproc)
learner = ktrain.get_learner(model,train_data=(x_train, y_train), val_data=(x_test, y_test), batch_size=6)

在某些文档中,我看到人们使用text.texts_from_folder(),但是我已经在数据框中拥有了所有内容。文字中还有其他功能吗?那会帮助我获得预治疗吗?

2 个答案:

答案 0 :(得分:1)

有关可用预处理功能的完整列表,请参见 ktrain text classification tutorial。例如,在您的情况下,您可以使用texts_from_dftexts_from_array。这些功能将以模型期望的方式预处理文本文档。有关使用texts_from_df的示例,请参见this example notebook。或者,您可以在 ktrain 中使用Transformer API

答案 1 :(得分:0)

我也找不到,所以我写了一个将csv拆分为txt文件的函数:

import time
import os
from joblib import Parallel, delayed
from tqdm import tqdm_notebook as tqdm

treads=12
path = os.getcwd()
train_path = path + '/' + 'train_df' + '/'
test_path = path + '/' + 'test_df' + '/'

train_len = range(len(train_df['text']))
texts = train_df['text'].tolist()
ids = train_df['id'].tolist()
classes= train_df['class'].tolist()

def create_directory(directory):
    try:
        os.mkdir(directory)
    except OSError:
        print('OSError')
    else:
        print('Error')

def write_txt(text_, id_, class_, path, i):
    cur_path = path + '/' + str(id_) + '/'
    create_directory(cur_path)
    with open(cur_path + f'{class_}_{i}.txt', 'w', encoding='utf-8') as f:
        f.write(text_)

Parallel(n_jobs=treads)(delayed(write_txt)(texts[i], ids[i], classes[i], path, i) for i in tqdm(train_len))