创建for-loop循环列表- Python



对于大多数专业人士来说,这可能是一个简单的问题。我已经奇迹般地设法在一些数据上调整了一个ELECTRA模型,并获得了一些不错的f分,现在我希望将我的模型应用于其他一些文本;这是一个多标签分类模型。

我是这样写的:

test_comment = ["We’re exceptionally proud of the 62,000 employees who work in our restaurants, along with the hundreds of Russian suppliers who support our business, and our local franchisees. "]

# tokenizing comment ^
encoding = tokenizer.encode_plus(
test_comment,
add_special_tokens=True,
max_length=512,
return_token_type_ids=False,
padding="max_length",
return_attention_mask=True,
return_tensors='pt',
)
# returning probability values for each label
_, test_prediction = trained_model(encoding["input_ids"], encoding["attention_mask"])
test_prediction = test_prediction.flatten().numpy()
for label, prediction in zip(LABEL_COLUMNS, test_prediction):
print(f"{label}: {prediction}",)
#[0 if x <= 0.5 else 1 for x in test_prediction]

返回

morality_binary: 0.12542158365249634
emotion_binary: 0.16170987486839294
positive_binary: 0.13724404573440552
negative_binary: 0.06993409991264343
care_binary: 0.06901352107524872
fairness_binary: 0.0649697408080101
authority_binary: 0.05470539629459381
sanctity_binary: 0.03908411040902138
harm_binary: 0.05327978357672691
injustice_binary: 0.057351987808942795
betrayal_binary: 0.03698693960905075
subversion_binary: 0.05460885167121887
degradation_binary: 0.04987286403775215
现在,假设我有一个结构为

的数据集
ID      sample_text
1       lorem ipsum dala dulu
2       lorem ipsum dala dulu etc
3       lorem ipsum dala dulu etc
4       lorem ipsum dala dulu etc
5       lorem ipsum dala dulu etc

我希望模型对每一行进行预测,并将每个预测作为新列添加,如

ID      sample_text                 morality_binary    positive_binary   negative_binary 
1       lorem ipsum dala dulu       0.13455            0.43455           0.26455
2       lorem ipsum dala dulu etc   0.12145            0.43455           0.87455
3       lorem ipsum dala dulu etc   0.03455            0.63455           0.37455
4       lorem ipsum dala dulu etc   0.41455            0.83455           0.81455
5       lorem ipsum dala dulu etc   0.73455            0.93455           0.5455

我有一种感觉,它不是太难,我只是无法理解它。

非常感谢你提供的任何帮助!

由于您没有提供最小可重复的示例,因此我无法确定这是否可行,但理论上应该可行,假设您的输出是类似列表的。我还假设你的模型是一个黑盒:

首先,将模型封装在函数中:

# outputs some list-like result
def run_model(input_data):
...

然后,将函数应用于每行:

df[LABEL_COLUMNS] = df[['sample_text']].apply(run_model, axis=1, result_type='expand')

然而,你的模型是如何工作的,或者预期的输入是什么,以及你是否可以在多个输入上操作,这并不是很清楚。