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

我使用 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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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