【问题标题】:How to feed data into random forest classifier and see prediction如何将数据输入随机森林分类器并查看预测
【发布时间】:2020-10-02 11:30:08
【问题描述】:

我已经使用 scikit learn 和 python 构建了一个随机森林分类器,但我在实际输入数据以查看预测时遇到了麻烦。我想查看输出的格式,并将其转换为 json 文件。我附上了随机森林的代码和数据的样子。我相信我需要使用 'y_pred',但我不确定输入数据需要采用什么格式。

X = dataset.iloc[:, 2:4].values
y = dataset["pages"]
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators=20, random_state = 0)
classifier = classifier.fit(X_train,y_train)
y_pred = classifier.predict(X_test)
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

【问题讨论】:

  • 您能详细说明您的期望吗? classifier.predict() 的输入是一个 numpy 数组,其维数与 X_train(或 X_test)相同。
  • 现在,使用 classifier.predict() 为我提供了我输入的测试数据的所有“页面”预测列表,格式为 [1,1,2,2,1, 1,2,1]。我想将其更改为还包含该行中 json 格式的数据,例如:{seconds:50, size2:12, pages:1},而不是仅包含输出的列表。
  • 不要将 cmets 空间用于此类附加信息 - 改为编辑和更新您的帖子。

标签: python machine-learning scikit-learn random-forest


【解决方案1】:

您可以简单地将预测值与特征矩阵连接起来。

另请注意,管道正是为此目的,当您首先要转换数据然后应用一些分类器时。

这应该适合你:

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.ensemble import RandomForestClassifier
import pandas as pd

X = dataset.iloc[:, 2:4].values
y = dataset["pages"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
classifier = make_pipeline(StandardScaler(), RandomForestClassifier(n_estimators=20, random_state=0))
classifier = classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)

pred = pd.concat([X_test, pd.Series(y_pred, name="pages")], axis=1)

【讨论】:

  • 非常感谢!
  • 我试过了,得到了错误 'TypeError: cannot concatenate object of type '';只有 Series 和 DataFrame obj 是有效的',你知道为什么会这样吗?
  • 可能X_test 不是pd.DataFrame,在这种情况下,只需将其转换为pd.DataFrame。如果答案是您正在寻找的,请考虑接受它。 :)
猜你喜欢
  • 2014-08-07
  • 2020-04-27
  • 2020-07-06
  • 2018-02-18
  • 2021-03-21
  • 2019-05-04
  • 2013-12-31
  • 2015-07-26
相关资源
最近更新 更多