【问题标题】:Pass single rows from a dataframe to predict with a loop从数据框中传递单行以使用循环进行预测
【发布时间】:2018-08-02 12:44:19
【问题描述】:

我使用iloc 传递行索引并使用n 指定位置。相反,如何修改代码以传递来自class_zero 的行,并打印它的每个预测。

import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier


X, y = make_classification(n_samples=1000,
                           n_features=6,
                           n_informative=3,
                           n_classes=2,
                           random_state=0,
                           shuffle=False)

# Creating a dataFrame
df = pd.DataFrame({'Feature 1':X[:,0],
                                  'Feature 2':X[:,1],
                                  'Feature 3':X[:,2],
                                  'Feature 4':X[:,3],
                                  'Feature 5':X[:,4],
                                  'Feature 6':X[:,5],
                                  'Class':y})

y_train = df['Class']
X_train = df.drop('Class', axis=1)
class_zero = df.loc[df['Class'] == 0]

n = 5  #instead of specifying 5 which is where class_zero = 0, I want to pass directly the class_zero from the list I created
#and print for each one

rf = RandomForestClassifier()
rf.fit(X_train, y_train)
instances = X_train.iloc[n].values.reshape(1, -1)

predictValue = rf.predict(instances)
actualValue = y_train.iloc[n]

print('##')
print(n)
print(predictValue)
print(actualValue)
print('##')

【问题讨论】:

    标签: python pandas numpy machine-learning scikit-learn


    【解决方案1】:

    您可以将 class==0 的行的索引用作iloc() 中的列表

    像这样改变class_zero:

    class_zero = df.index[df['Class'] == 0].tolist()
    

    而且你做错了重塑。保持这样:

    instances = X_train.iloc[class_zero].values
    

    编辑评论:

    for n in class_zero:
        instances = X_train.iloc[n].values.reshape(1,-1)
    
        predictValue = rf.predict(instances)
        actualValue = y_train.iloc[n]
    
        print('##')
        print(n)
        print(predictValue)
        print(actualValue)
        print('##')
    

    【讨论】:

    • 谢谢,不过我如何将它作为 for 循环传递。也就是说,在每个循环中,它一次性传递一个 n 的值,而不是所有这些值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2021-09-12
    • 2011-10-19
    • 2021-07-16
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多