Python 如何通过遍历行来预测数据帧中的每一行?

Python 如何通过遍历行来预测数据帧中的每一行?,python,pandas,loops,iterator,iteration,Python,Pandas,Loops,Iterator,Iteration,我建立了一个伯特模型,现在我有了一个块,可以很好地对文本列中的每一行逐一进行分类。熊猫数据帧如下所示: text 0 working add oil 1 @KristianaNKOTB you're welcome 2 is going to bed, work in the morning boo but t... 3 @sparky_habbo - uni & assignments happened... 4 Can't wait to have

我建立了一个伯特模型,现在我有了一个块,可以很好地对文本列中的每一行逐一进行分类。熊猫数据帧如下所示:

    text
0   working add oil
1   @KristianaNKOTB you're welcome
2   is going to bed, work in the morning boo but t...
3   @sparky_habbo - uni & assignments happened...
4   Can't wait to have chinese food! Still disappo...
    emotion
0   1  
文本列中每个特定行的分类代码如下:

text = [df[0]]

pred_tokens = map(tokenizer.tokenize, text)
pred_tokens = map(lambda tok: ["[CLS]"] + tok + ["[SEP]"], pred_tokens)
pred_token_ids = list(map(tokenizer.convert_tokens_to_ids, pred_tokens))

pred_token_ids = map(lambda tids: tids +[0]*(data.max_seq_len-len(tids)),pred_token_ids)
pred_token_ids = np.array(list(pred_token_ids))

predictions = model.predict(pred_token_ids).argmax(axis=-1)

df = pd.DataFrame(predictions, columns = ['emotion'])
df
例如,如果我们想对if
df.text[0]
进行分类,那么
'working add oil'
是1还是0,我使用此代码,结果如下:

    text
0   working add oil
1   @KristianaNKOTB you're welcome
2   is going to bed, work in the morning boo but t...
3   @sparky_habbo - uni & assignments happened...
4   Can't wait to have chinese food! Still disappo...
    emotion
0   1  

但是现在我如何通过遍历行来预测数据帧中的每一行呢?

下面是一段代码,它演示了可以用来预测数据帧中的文本并保存它的过程

输入数据:

df=pd.DataFrame({"text":['working add oil',"@KristianaNKOTB you're welcome","is going to bed, work in the morning boo but t..."]})
定义一个函数。你可以根据你的程序调整它。您可以注释我的代码并取消注释您的代码

import random
def predict_emotion(input_text):
    text = input_text
    
    ''' uncomment this and remove my return statement
    pred_tokens = map(tokenizer.tokenize, text)
    pred_tokens = map(lambda tok: ["[CLS]"] + tok + ["[SEP]"], pred_tokens)
    pred_token_ids = list(map(tokenizer.convert_tokens_to_ids, pred_tokens))

    pred_token_ids = map(lambda tids: tids +[0]*(data.max_seq_len-len(tids)),pred_token_ids)
    pred_token_ids = np.array(list(pred_token_ids))

    predictions = model.predict(pred_token_ids).argmax(axis=-1)
    return predictions
    '''
    return_int=random.randint(1,8)
    print(f"text:{input_text},emotion:{return_int}")
    return return_int
为每行输入文本调用函数

df['emotion']=df['text'].apply(predict_emotion)
输出:

情绪必须为1或0,这是一项分类任务。我在3个随机行上测试了这段代码,结果是这样的,有很多1和0:
text emotion 1 you's welcome[0,0,1,0,0,1,1,0,0,0,0,0]5为今天下午的试镜做准备。从wh…[0,1,0,0,1,0,0,1,1,0,1,1,0,1,1,…7现在开始面对我的考试[0,1,1,1,0,0,1,1,0,0,0,1,1,0,0,1,…
图片链接:这是我所做的步骤:这是模型的问题,它有14个作为输出,所以肯定不是一个二元分类模型。这个答案是用于运行预测的,它工作正常。请在模型上提出一个新问题。我已经发布:谢谢,我也会查看它。请访问请回答这个问题。谢谢