【问题标题】:Errors with Python Classification and Regression TreesPython 分类和回归树的错误
【发布时间】:2016-04-17 23:40:04
【问题描述】:

我正在学习如何在 python 中使用决策树。我修改了一个示例以导入 csv 文件,而不是使用来自该站点的 iris 数据集:

http://machinelearningmastery.com/get-your-hands-dirty-with-scikit-learn-now/

代码:

import numpy as np
import urllib
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
from sklearn import datasets
from sklearn import metrics

# URL for the Pima Indians Diabetes dataset (UCI Machine Learning Repository)
url = "http://goo.gl/j0Rvxq"
# download the file
raw_data = urllib.urlopen(url)
# load the CSV file as a numpy matrix
dataset = np.loadtxt(raw_data, delimiter=",")
#print(dataset.shape)
# separate the data from the target attributes
X = dataset[:,0:7]
y = dataset[:,8]
# fit a CART model to the data
model = DecisionTreeClassifier()
model.fit(dataset.data, dataset.target)
print model

错误:

Traceback (most recent call last):
  File "DatasetTest2.py", line 24, in <module>
    model.fit(dataset.data, dataset.target)
AttributeError: 'numpy.ndarray' object has no attribute 'target'

我不确定为什么会发生此错误。如果我使用示例中的 iris 数据集,它就可以正常工作。最终,我需要能够对 csv 文件执行决策树。

我也尝试过以下代码,但也会导致同样的错误:

# Import Python Modules
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
from sklearn import datasets
from sklearn import metrics
import pandas as pd
import numpy as np

#Import Data
raw_data = pd.read_csv("DataTest1.csv")
dataset = raw_data.as_matrix()
#print dataset.shape
#print dataset
# separate the data from the target attributes
X = dataset[:,[2,3,4,7,10]]
y = dataset[:,[1]]
#print X
# fit a CART model to the data
model = DecisionTreeClassifier()
model.fit(dataset.data, dataset.target)
print model

【问题讨论】:

    标签: python tree classification regression


    【解决方案1】:

    在该示例中导入的 dataset 对象不是普通的数据表。它是一个特殊对象,设置有datatarget 等属性,因此可以如示例中所示使用它。如果您有自己的数据,则需要决定使用什么作为数据和目标。从您的示例来看,您似乎想做model.fit(X, y)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-22
      • 2019-07-02
      • 2013-02-21
      • 2015-11-23
      • 1970-01-01
      • 2020-06-30
      • 2014-06-19
      • 1970-01-01
      相关资源
      最近更新 更多