我是scikit-learn的新手,我正在尝试训练一个分类器来预测给定特定输入后最可能的汽车类型:
我的数据看起来像这样:
18.0 8 307.0 130.0 3504. 12.0 70 1 chevrolet
15.0 8 350.0 165.0 3693. 11.5 70 1 buick
18.0 8 318.0 150.0 3436. 11.0 70 1 plymouth
17.0 8 302.0 140.0 3449. 10.5 70 1 ford torino
15.0 8 429.0 198.0 4341. 10.0 70 1 ford galaxie 500
14.0 8 454.0 220.0 4354. 9.0 70 1 chevrolet impala
14.0 8 440.0 215.0 4312. 8.5 70 1 plymouth fury iii
其中每一列数据代表汽车的一个特定特征:每加仑英里数(mpg)、气缸数、马力、加速度等。
我用数字形式表示这些汽车:
cars = [0, 1, 2, 3, 3, 0, 2]
其中0代表雪佛兰,1代表别克,等等。
这是我的程序代码:
data = np.loadtxt("my_data") mpg = data[:,0] cylinders = data[:,1] displacement = data[:,2] horsepower = data[:,3] weight = data[:,4] acceleration = data[:,5] modelyear = data[:,6] origin = data[:,7] X = [mpg, cylinders, displacement, horsepower, weight, acceleration, acceleration, modelyear, origin] car_type = [1, 2, 3, 2, 6, 1, 0, 2, 5, 4, 2, 0, 3, 3, 2, 1, 0] clf = tree.DecisionTreeClassifier() clf.fit(X, car_type)
但当我尝试运行它时,我得到了这个错误:
Traceback (most recent call last): File "scikitlearn_practice.py", line 21, in <module> clf.fit(X, car_type) File "/Library/Python/2.7/site-packages/sklearn/tree/tree.py", line 739, in fit X_idx_sorted=X_idx_sorted) File "/Library/Python/2.7/site-packages/sklearn/tree/tree.py", line 240, in fit "number of samples=%d" % (len(y), n_samples)) ValueError: Number of labels=17 does not match number of samples=8
我该如何修复这个错误,使标签数量与样本数量匹配?
谢谢
回答:
你的问题出在X的声明上。根据文档,X的形状必须是[n_samples, n_features],而在你的代码中,你的数组形状是[n_features, n_samples],即[[18.0,15.0,…,14.0], [8,8,…,8],…,[1,1,…,1]]。
你实际上需要的是一个每行描述一个样本的数组,即[[18.0,8,307.0,130.0,3504.,12.0,70,1],…,[14.0,8,440.0,215.0,4312.,8.5,70,1]]。这已经是你data数组中的内容了。
利用这些信息,你可以重写代码如下:
X = np.loadtxt("my_data")car_type = [1, 2, 3, 2, 6, 1, 0, 2, 5, 4, 2, 0, 3, 3, 2, 1, 0]clf = tree.DecisionTreeClassifier()clf.fit(X, car_type)
然而,执行这段代码仍然会导致错误,Number of labels=17 does not match number of samples=7
这是因为你的标签数组包含17个标签(对应17个样本),而你的样本数组只包含7个样本(即由其特征描述的7辆汽车)。
car_type数组应该包含与你的X数组中样本数量相同的标签,所以错误出在你的数据上。
我不知道car_types应该是什么,但你的cars数组包含7个样本,并且似乎与你my_data中的数据相对应,所以你可能想要做的是:
X = np.loadtxt("my_data")cars = [0, 1, 2, 3, 3, 0, 2] clf = tree.DecisionTreeClassifier()clf.fit(X, cars)
这样做,我能够用你的数据拟合模型。希望这对你有帮助。