首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >ValueError: X has 2 features, but DecisionTreeClassifier is expecting 1 features as input?

ValueError: X has 2 features, but DecisionTreeClassifier is expecting 1 features as input?

提问于 2023-10-05 06:44:05
回答 0关注 0查看 460

按照书上的代码将我自己的数据分为X,y。再代入书上的后续的回归代码。出现报错。

import csv

import pandas

import numpy as np

import matplotlib.pyplot as plt

with open('data.csv','r')as f:

reader_N2 = csv.reader(f)

data_N2 = []

for row in reader_N2:

float_row = [float (value) for value in row]

data_N2.append(float_row)

print(data_N2)

X_train = [row[:10] for row in data_N2]

Y_train = [row[10:] for row in data_N2]

print(X_train,Y_train)

X_train = np.array(X_train)

Y_train = np.array(Y_train)

X_train,X_test,Y_train,Y_test = X_train[:1600],X_train[1600:],Y_train[:1600],Y_train[1600:]

print(X_train.shape)

print(Y_train.shape)

print(X_test.shape)

print(Y_test.shape)

X_train_1 = np.hsplit(X_train,10)[0]

X_train_2 = np.hsplit(X_train,10)[1]

X_train_3 = np.hsplit(X_train,10)[2]

X_train_4 = np.hsplit(X_train,10)[3]

X_train_5 = np.hsplit(X_train,10)[4]

X_train_6 = np.hsplit(X_train,10)[5]

X_train_7 = np.hsplit(X_train,10)[6]

X_train_8 = np.hsplit(X_train,10)[7]

X_train_9 = np.hsplit(X_train,10)[8]

X_train_10 = np.hsplit(X_train,10)[9]

Y_train = Y_train.flatten()

print(Y_train)

Y_test = Y_test.flatten()

print(Y_test)

Y_train = np.where(Y_train > 0, 1, -1)

Y_test = np.where(Y_test > 0, 1, -1)

from sklearn.ensemble import BaggingClassifier

from sklearn.tree import DecisionTreeClassifier

bag_clf = BaggingClassifier(

DecisionTreeClassifier(random_state=42), n_estimators=500,

max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)

bag_clf.fit(X_train_1, Y_train.astype("int"))

y_pred = bag_clf.predict(X_test_1)

from sklearn.metrics import accuracy_score

print(accuracy_score(Y_test.astype("int"), y_pred))

tree_clf = DecisionTreeClassifier(random_state=42)

tree_clf.fit(X_train_1, Y_train.astype("int"))

y_pred_tree = tree_clf.predict(X_test_1)

print(accuracy_score(Y_test.astype("int"), y_pred_tree))

from matplotlib.colors import ListedColormap

def plot_decision_boundary(clf, X_train_1, Y_train, axes=[-3, 3, -1, 1], alpha=0.5, contour=True):

x1s = np.linspace(axes[0], axes[1], 100)

x2s = np.linspace(axes[2], axes[3], 100)

x1, x2 = np.meshgrid(x1s, x2s)

X_new = np.c_[x1.ravel(), x2.ravel()]

y_pred = clf.predict(X_new).reshape(x1.shape)

custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])

plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)

if contour:

custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])

plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)

plt.plot(X_train_1[:, 0][Y_train == -1], X_train_1[:, 1][Y_train == -1], "yo", alpha = alpha)

plt.plot(X_train_1[:, 0][Y_train == 1], X_train_1[:, 1][Y_train == 1], "bs", alpha = alpha)

plt.axis(axes)

plt.xlabel(r"$x_1$", fontsize=18)

plt.ylabel(r"$x_2$", fontsize=18, rotation=0)

程序到这里都运行正常,结果在下面一步显示报错。请问有前辈可以指点一下吗?

plt.figure(figsize=(11,4))

plt.subplot(121)

plot_decision_boundary(tree_clf, X_train_1, Y_train)

plt.title("Decision Tree", fontsize=14)

plt.subplot(122)

plot_decision_boundary(bag_clf, X_train_1, Y_train)

plt.title("Decision Trees with Bagging", fontsize=14)

save_fig("decision_tree_without_and_with_bagging_plot")

plt.show()

回答

成为首答用户。去 写回答
相关文章
​python features
1. overview paradigm 过程式: 模块化 结构化 程序 = 数据结构 + 算法 函数式: 函数是一等公民, 不可变数据 面向对象: 封装继承多态 import this 2. control flow for for i in iterable_object: # do something pass else: # for 语句块中没有执行过break的时候执行的代码块 pass if >> switch var = input("please enter
devecor
2019/11/25
4780
torch.nn.Linear(in_features, out_features, bias=True)[source]
对到来的数据使用线性变换: 参数: in_features – 每个输入样本的大小 out_features – 每个输出样本的大小 bias – 如果设置为False,层将不会学习添加偏差。默认值:True 形状: 输入: 其中∗*∗ 的含义为附加维的任何数值,并且 输出: , 除了最后一个维度外,其他所有维度都与输入相同,并且 . 变量: ~Linear.weight – shape (out_features,in_features)模块的可
狼啸风云
2022/08/18
5840
torch.nn.Linear(in_features, out_features, bias=True)[source]
Taking advantage of context features
In the featurization tutorial we incorporated multiple features beyond just user and movie identifiers into our models, but we haven't explored whether those features improve model accuracy.
XianxinMao
2021/07/30
2340
idea的Learn IDE Features
阿超
2023/06/23
2890
idea的Learn IDE Features
C++17 New Features
如果说 C++11 和 C++20 是两个改动大、影响比较深远的"大版本",那么我感觉 C++17 算是一个小版本。(推荐 vs2019,gcc8,clang10,支持 C++17)
JIFF
2020/06/09
1.1K0
Features of .Net Development Platform
.Net Framework has been probably the best advancement by Microsoft for web applications, work area applications and site improvement. .Net designers and individuals who have been in steady interface with this stage definitely realize that it has its own library of dialects, structure and further turns of events. Novices and entrepreneurs should realize that from a straightforward design, .Net system has advanced to a total environment offering help and improvement procedures for a wide range of uses
saurabhkumawat
2021/02/24
3710
Features of .Net Development Platform
Get an Application Required Features
How to get application’s required features? Actually the aapt really does a great help. 1 2 3 4 5 6
技术小黑屋
2018/09/04
5420
Get Android System Available Features
An easy way to get system available features.
技术小黑屋
2018/09/04
7330
快速学习-RocketMQ特性(features)
消息的发布是指某个生产者向某个topic发送消息;消息的订阅是指某个消费者关注了某个topic中带有某些tag的消息,进而从该topic消费数据。
cwl_java
2020/09/21
7100
C++20 New Features
New keywords: char8_t, co_await, co_return, co_yield, concept, consteval, constinit, import*, module*, requires
JIFF
2020/05/20
6420
Using side features: feature preprocessing
One of the great advantages of using a deep learning framework to build recommender models is the freedom to build rich, flexible feature representations.
XianxinMao
2021/07/30
4380
Spark Extracting,transforming,selecting features
官方文档链接:https://spark.apache.org/docs/2.2.0/ml-features.html
HoLoong
2020/09/27
21.9K0
Android Q 60 New Features
No more desert name — it's just Android 10 A true system-wide dark mode New swipe gestures replace the home, back, and recent apps buttons New gesture for screen pinning Project Mainline brings security updates to the Play Store Generic System Images can b
用户9732312
2022/05/13
3410
[翻译]Learning Deep Features for Discriminative Localization
摘要 在这项工作中, 我们重新审视了《 Network in network》中提出的全局平均 池化层(global average pooling),并阐明了它是如何通过图片标签就能让卷积神经网络具有卓越的定位能力。虽然这项技术以前被当做正则化训练的一种方法,但是我们发现它实际构建了一种通用的适用于各种任务的能定位的深度表示。尽管global average pooling很简单,我们仍然能够在2014年的ILSVRC物体定位比赛中得到37.1%的top-5错误率,与CNN的34.2%top-5错误率非常接近。我们证明了我们的网络能在各种任务中区分图像区域进行定位,尽管没有经过(定位)训练。
刘开心_1266679
2019/02/14
7430
[翻译]Learning Deep Features for Discriminative Localization
Top 10 Features of Angular 8
In the first quarter of 2019, Google launched Angular 8 which was much awaited by the community, the expectations were really high for Angular 8 as it was initially said that Angular 10 will be the final version of the framework. The skyrocketed hype demands huge performance improvements in Angular 8 which was quite matched with mainly focusing on the toolchain and also making Angular easier for users to create different types of application along with other performance improvements.
用户4822892
2019/08/22
7030
Top 10 Features of Angular 8
Node.js Backend Development: Features, Benefits
Node.js backend development has become extremely popular among software developers. In order to keep up with modern technologies, it is necessary to know what is Node.js, what are the reasons to use it, where to hire developers, etc. Answers to these questions will be discovered in this article.
用户8617680
2021/05/27
9460
Node.js Backend Development: Features, Benefits
IBM i Systems - Facts and New Features
The history of IBM i starts with the launch of the very famous AS400 systems in 1980. It is exceptional and quite interesting to know that IBM i operating system is still very popular and extensively used in many organizations across the globe. Unlike any other legacy technology that lost its importance over time due to failure in some or the other aspect, IBM i has evolved with time and comes integrated with all the latest updates.
saurabhkumawat
2020/03/31
6820
IBM i Systems - Facts and New Features
The complete list of new features in MySQL 8.0
原文出处:https://mysqlserverteam.com/the-complete-list-of-new-features-in-mysql-8-0/
老叶茶馆
2020/08/12
6600
Binarizing label features二值化标签特征
In this recipe, we'll look at working with categorical variables in a different way. In the event that only one or two categories of the feature are important, it might be wise to avoid the extra dimensionality, which might be created if there are several categories.
到不了的都叫做远方
2019/10/29
8620
UE4 ContentExamples:Network_Features
最近一直没有弄过UE4了 和同事沟通的时候,看了下 Network_Features 今天自己简单记录一下 等 微积分 复习完,再考虑别的
dodo_lihao
2018/09/12
1.1K0
UE4 ContentExamples:Network_Features

相似问题

Istagram的access_token会失效吗?

1222

活体人脸审核通过后多久会失效?

1154

服务器到期,使用备案授权码备案的域名会失效吗?

11.2K

为什么使用'new'会导致内存泄漏?

2222

为什么使用'new'会导致内存泄漏?

2301
相关问答用户
腾讯云TDP | TDP会员擅长3个领域
平安资管 | 架构师擅长4个领域
擅长5个领域
擅长3个领域
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档