ValueError: X has 2 features, but DecisionTreeClassifier is expecting 22 features as input.

大家好,我的代码报错,靠自己不能解决,望善良友友帮忙一下~

img


```python
from pyexpat import features
import pandas as pd
import pandas as pd
import numpy as np

from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn import tree
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
mushroom = 'D:/桌面/decision_tree (1)/decision_tree/mushrooms.csv'
mushroom = pd.read_csv(mushroom, sep=',', decimal='.')
mushroom=pd.DataFrame(mushroom)
# print(type(mushroom))
# print(mushroom)
X = mushroom.iloc[:,1:]
y = mushroom["class"]
#将数据进行数值化
i = 0
while(i<22):
    y_flag = X.iloc[:,i].unique()
    X.iloc[:,i] = X.iloc[:,i].apply(lambda x : y_flag.tolist().index(x))
    i = i+1
# print(X.head())
y = y.map(dict(zip(['e','p'],[0,1])))


test_data = np.array(X)
test_datay=np.array(y)
print(y)
print(test_datay)

x_train, x_test, y_train, y_test = train_test_split(X,y,test_size=0.3,random_state=4)
# 创建决策树对象,使用信息熵作为依据
# print(x_test)
# print(y_test)
clf = tree.DecisionTreeClassifier(max_depth=4)
#criterion='entropy',max_depth=5
clf.fit(x_train,y_train)
#查看评分即准确率
score=clf.score(x_test,y_test)
print("决策树的准确率为:",score)

# 生成所有测试样本点
def make_meshgrid(x, y, h=.02):
    x_min, x_max = x.min() - 1, x.max() + 1
    y_min, y_max = y.min() - 1, y.max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                np.arange(y_min, y_max, h))
    return xx, yy

# 对测试样本进行预测,并显示
def plot_test_results(ax, clf, xx, yy, **params):
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    ax.contourf(xx, yy, Z, **params)

title = ('TreeClassifier CART')

fig, ax = plt.subplots(figsize = (5, 5))
plt.subplots_adjust(wspace=0.4, hspace=0.4)
#
X0, X1 = test_data[:, 0], test_data[:, 1]
# 生成所有测试样本点
xx, yy = make_meshgrid(X0, X1)

# 显示测试样本的分类结果
plot_test_results(ax, clf, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
# 显示训练样本
ax.scatter(X0, X1, c=test_datay, cmap=plt.cm.coolwarm, s=20, edgecolors='k')
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_xticks(())
ax.set_yticks(())
ax.set_title(title)
plt.show()

```

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 以下回答来自chatgpt:

    根据问题描述,可以知道数据集中只有两个特征,但是DecisionTreeClassifier需要22个特征作为输入,那么可以考虑以下几种情况:

    1. 检查数据集是否正确导入,是否出现了数据缺失、数据格式异常等问题导致误判特征数量。

    2. 检查决策树模型的参数,是否设置了不正确的特征数量、拆分器等参数导致误判特征数量。

    3. 检查训练集和测试集是否一致,是否出现了拼接、数据类型不一致等问题。

    针对以上情况,可以采取以下方法进行排查和解决:

    1. 确认数据集的特征数量是否是实际特征数量,可以通过使用pandas等工具进行数据预处理和初步探索。

    2. 检查决策树模型的参数,特别是max_features、splitter等参数是否设置不正确,可以考虑调整参数进行测试。

    3. 确认训练集和测试集是否一致,是否出现了拼接、数据类型不一致等问题,建议使用sklearn中的train_test_split函数进行数据集拆分。

    下面给出一个例子,展示如何使用DecisionTreeClassifier进行分类:

    from sklearn.datasets import load_iris
    from sklearn.model_selection import train_test_split
    from sklearn.tree import DecisionTreeClassifier
    from sklearn.metrics import accuracy_score
    
    
    # 导入数据
    iris = load_iris()
    X = iris.data[:, :2]  # 取前两个特征
    y = iris.target
    
    
    # 数据集拆分
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
    
    
    # 创建决策树模型
    tree_model = DecisionTreeClassifier(criterion="gini", max_depth=3, random_state=0)
    
    
    # 模型拟合
    tree_model.fit(X_train, y_train)
    
    
    # 预测
    y_pred = tree_model.predict(X_test)
    
    
    # 准确率评估
    acc = accuracy_score(y_test, y_pred)
    print("测试集准确率:", acc)
    

    可以根据实际情况进行参数调整,比如max_depth设置为较小的值可以避免过拟合,max_features设置为较小的值可以避免特征过于复杂等。同时还需要确认训练集和测试集的数据类型和特征数量是否一致。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^