如何修复在机器学习中训练模型时y_train导致的ValueError错误?

当我在运行时尝试使用y_train时,出现了ValueError错误。我检查了y_test和y_train的形状,发现其中一个是(2000,),而另一个不是。有什么方法可以修复这个错误呢?

import pandas as pddf = pd.read_csv('iris.csv')df.head()df.shapedf.loc[df["species"] == "setosa", "species"] = 0df.loc[df["species"] == "versicolor", "species"] = 1df.loc[df["species"] == "virginica", "species"] = 2from sklearn.model_selection import train_test_splitX=df.drop('species',axis=1)y=df['species']X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2, random_state=156)from sklearn.tree import DecisionTreeClassifiermy_model = DecisionTreeClassifier(random_state=0)result = my_model.fit(X_train,y_train)

回答:

您的方法如下:

df.loc[df["species"] == "setosa", "species"] = 0df.loc[df["species"] == "versicolor", "species"] = 1df.loc[df["species"] == "virginica", "species"] = 2

使得df['species']成为object类型,这不被DecisionTreeClassifier所支持。相反,您应该这样做:

df['species'] = df['species'].map({'setosa':0, 'versicolor':1, 'virginica':2})

Related Posts

如何对SVC进行超参数调优?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

如何在初始训练后向模型添加训练数据?

我想在我的scikit-learn模型已经训练完成后再…

使用Google Cloud Function并行运行带有不同用户参数的相同训练作业

我正在寻找一种方法来并行运行带有不同用户参数的相同训练…

加载Keras模型,TypeError: ‘module’ object is not callable

我已经在StackOverflow上搜索并阅读了文档,…

在计算KNN填补方法中特定列中NaN值的”距离平均值”时

当我从头开始实现KNN填补方法来处理缺失数据时,我遇到…

使用巨大的S3 CSV文件或直接从预处理的关系型或NoSQL数据库获取数据的机器学习训练/测试工作

已关闭。此问题需要更多细节或更清晰的说明。目前不接受回…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注