【问题标题】:Python sklearn decision tree classifier with multiple features?具有多种功能的 Python sklearn 决策树分类器?
【发布时间】:2017-08-13 11:27:01
【问题描述】:

我正在尝试对具有四个特征的训练数据进行预测;我的代码:

from sklearn.cross_validation import train_test_split

X = iris.data
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.33, random_state=42)

# Train
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)

# Plot the decision boundary
plt.subplot(2, 3, pairidx + 1)

x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                     np.arange(y_min, y_max, plot_step))

Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)

plt.xlabel(iris.feature_names[pair[0]])
plt.ylabel(iris.feature_names[pair[1]])
plt.axis("tight")

# Plot the training points
for i, color in zip(range(n_classes), plot_colors):
    idx = np.where(y == i)
    plt.scatter(X[idx, 0], X[idx, 1], c=color, label=iris.target_names[i],
                cmap=plt.cm.Paired)

plt.axis("tight")

plt.suptitle("Decision surface of a decision tree using paired features")
plt.legend()
plt.show()

在我的预测行:Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) 我收到以下错误:

Number of features of the model must match the input. Model n_features is 4 and input n_features is 2

虹膜数据是一个 150x4 的数据集。我如何让它适用于 4 个功能?

【问题讨论】:

  • 你为什么使用 ravel()。你在关注任何网络教程吗?发布链接。什么是plot_steppairidx

标签: python scikit-learn decision-tree


【解决方案1】:
  • 在训练期间,您提供的特征数为 4
  • 但是当您进行预测时,您提供的样本有 2 个要预测的特征
  • 在训练中使用的特征数量必须在进行预测时使用相同数量的特征
  • 如果您执行以下操作:print(np.c_[xx.ravel(), yy.ravel()]),它会给您一个形状:(30, 2) 如果您的 plot_step 是 1
  • 作为参数提供给 predict 函数的 numpy 数组必须具有以下形状:(x, 4) 其中 x 可以是任何正整数,但 numpy 数组中的列数必须为 4强>

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 2018-10-20
    • 2018-09-06
    • 2020-10-11
    • 2020-10-23
    • 2014-03-12
    • 2016-07-29
    • 1970-01-01
    • 2018-04-22
    相关资源
    最近更新 更多