使用循环从数据框中传递单行进行预测

我使用 iloc 传递行索引,并通过 n 指定位置。请问如何修改代码以从 class_zero 中传递行,并打印每个预测结果。

import numpy as npimport pandas as pdfrom sklearn.datasets import make_classificationfrom sklearn.ensemble import RandomForestClassifierX, y = make_classification(n_samples=1000,                           n_features=6,                           n_informative=3,                           n_classes=2,                           random_state=0,                           shuffle=False)# 创建数据框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  # 不是指定5,即class_zero = 0的地方,我想直接从我创建的列表中传递class_zero# 并为每个打印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('##')

回答:

你可以在 iloc() 中使用 class==0 的行索引作为列表

像这样修改 class_zero:

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

并且你对 reshape 的使用是错误的。保持如下形式:

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('##')

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注