weixin_57079341 2023-06-07 21:11 采纳率: 0%
浏览 220

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

```

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-06-11 16:19
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:
    • 以下回答来自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设置为较小的值可以避免特征过于复杂等。同时还需要确认训练集和测试集的数据类型和特征数量是否一致。


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

报告相同问题?

问题事件

  • 创建了问题 6月7日

悬赏问题

  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)