【问题标题】:Array to columns in dataframe数组到数据框中的列
【发布时间】:2021-06-27 00:53:23
【问题描述】:

我已经按照this tutorial 构建了一个有效的分类模型。 我引入了一个 csv,然后将每一行的文本值传递给一个调用分类模型进行预测的函数。该函数返回一个数组,我需要将其放入数据框中的列中。

功能:

def get_top_k_predictions(model,X_test,k):

# get probabilities instead of predicted labels, since we want to collect top 3
np.set_printoptions(suppress=True)
probs = model.predict_proba(X_test)

# GET TOP K PREDICTIONS BY PROB - note these are just index
best_n = np.argsort(probs, axis=1)[:,-k:]

# GET CATEGORY OF PREDICTIONS
preds = [
[(model.classes_[predicted_cat], distribution[predicted_cat])
 for predicted_cat in prediction]
for distribution, prediction in zip(probs, best_n)]


preds=[ item[::-1] for item in preds]
return preds

函数调用:

for index, row in df.iterrows():
category_test_features=category_loaded_transformer.transform(df['Text'].values.astype('U'))
df['PREDICTION'] = get_top_k_predictions(category_loaded_model,category_test_features,9)

这是函数的输出:

[[('Learning Activities', 0.001271131465669718),
  ('Communication', 0.002696299964802842),
  ('Learning Objectives', 0.002774964762863968),
  ('Learning Technology', 0.003557563051027678),
  ('Instructor/TAs', 0.004512712287403168),
  ('General', 0.006675929282872587),
  ('Learning Materials', 0.013051869950436862),
  ('Course Structure', 0.02781481160602757),
  ('Community', 0.9376447176288959)]]

我希望输出最终看起来像 like this

【问题讨论】:

    标签: python arrays pandas machine-learning logistic-regression


    【解决方案1】:

    您的函数返回一个包含元组列表的列表?为什么是双嵌套列表?我能想到的一种方法:

    tmp = {}
    for index, row in df.iterrows():
        predictions = get_top_k_predictions(...)
        tmp[index] = {
            key: value for key, value in predictions[0]
        }
    
    tmp = pd.DataFrame(tmp).T
    df.join(tmp)
    

    【讨论】:

    • 双嵌套列表正是我遵循的教程所做的。如果有更好的方法来构造函数,我绝对愿意接受!
    • 我将您的代码添加到我的项目中,它为我提供了正确的格式,但它将第一行的相同输出复制到所有其他行。 tmp = {} 用于索引,df.iterrows() 中的行: category_test_features=category_loaded_transformer.transform(df['Text'].values.astype('U')) predictions = get_top_k_predictions(category_loaded_model,category_test_features,9) tmp[index ] = { key: key 的值,预测中的值[0] } tmp = pd.DataFrame(tmp).T df = df.join(tmp)
    猜你喜欢
    • 2023-01-13
    • 2020-10-20
    • 1970-01-01
    • 2017-02-23
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多