Fasttext如何将.csv列加载到model.predict

时间:2019-09-24 13:08:56

标签: python fasttext

我是python和NLP的新手。

我已经按照本教程(https://fasttext.cc/docs/en/supervised-tutorial.html)在Python中训练了我的fasttxt监督模型。

我有一个带“文本”列的csv,我想预测标签从文件中移到哪一行。 我的问题是如何在预测输入中加载(转换)csv列并保存标签。

model.predict("Which baking dish is best to bake a banana bread ?", k=-1, threshold=0.5)

而不是此(““哪个烘焙...”中的文本),我想逐行加载并将标签最好保存在同一csv中的新列中。

我会提供任何帮助,也可能会提供我可以遵循的教程。

到目前为止,我已经尝试过将列转换为pandas和numpy数组的列表,但是都返回了“ AttributeError:'function'对象没有属性'find'”

1 个答案:

答案 0 :(得分:0)

以此CSV为例:

index;id;text;author 0;id26305;This process, however, afforded me no means of...;EAP 1;id17569;It never once occurred to me that the fumbling...;HPL 2;id11008;In his left hand was a gold snuff box, from wh...;EAP 3;id27763;How lovely is spring As we looked from Windsor...;MWS 4;id12958;Finding nothing else, not even gold, the Super...;HPL 5;id22965;A youth passed in solitude, my best years spen...;MWS 6;id09674;The astronomer, perhaps, at this point, took r...;EAP 7;id13515;The surcingle hung in ribands from my body. ;EAP 8;id19322;I knew that you could not say to yourself 'ste...;EAP 9;id00912;I confess that neither the structure of langua...;MWS

您可以使用以下代码:

import pandas as pd
import fastText as ft

# here you load the csv into pandas dataframe
df=pd.read_csv('csv_file.csv',sep=';')

# here you load your fasttext module
model=ft.load_model(MODELPATH)

# line by line, you make the predictions and store them in a list
predictions=[]
for line in df['text']:
    pred_label=model.predict(line, k=-1, threshold=0.5)[0][0]
    predictions.append(pred_label)

# you add the list to the dataframe, then save the datframe to new csv
df['prediction']=predictions
df.to_csv('csv_file_w_pred.csv',sep=';',index=False)