Python分类和回归树的错误

时间:2016-01-13 05:45:34

标签: python tree classification regression

我正在学习如何在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'

我不确定为什么会出现这个错误。如果我使用示例中的虹膜数据集,它可以正常工作。最终,我需要能够在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

1 个答案:

答案 0 :(得分:0)

在该示例中导入的dataset对象不是纯数据表。这是一个使用datatarget等属性设置的特殊对象,因此可以按照示例中的说明使用它。如果您有自己的数据,则需要确定要用作数据和目标的内容。在您的示例中,您似乎想要model.fit(X, y)