我正在学习如何在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
在该示例中导入的dataset
对象不是简单的数据表。它是一个特殊的对象,设置了数据
和目标
等属性,以便可以如示例所示使用它。如果您有自己的数据,则需要决定使用什么作为数据和目标。从您的示例来看,您似乎希望执行model。安装(X,y)
。