【问题标题】:How do you form data to make an array of n features and n samples in scikit learn decision tree?在 scikit learn 决策树中,如何形成数据以制作包含 n 个特征和 n 个样本的数组?
【发布时间】:2017-05-08 13:45:45
【问题描述】:

我是 scikit learn 的新手,我正在尝试训练一个分类器来预测在给定特定输入的情况下最有可能使用哪种类型的汽车:

我的数据如下所示:

18.0 8 307.0 130.0 3504.12.0 70 1 雪佛兰

15.0 8 350.0 165.0 3693. 11.5 70 1 别克

18.0 8 318.0 150.0 3436. 11.0 70 1 普利茅斯

17.0 8 302.0 140.0 3449. 10.5 70 1 福特都灵

15.0 8 429.0 198.0 4341. 10.0 70 1 福特银河500

14.0 8 454.0 220.0 4354.9.0 70 1 雪佛兰黑斑羚

14.0 8 440.0 215.0 4312. 8.5 70 1 普利茅斯之怒 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

如何修复此错误以使标签与样本数量匹配?

谢谢

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    您在 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)
    

    这样做,我能够用您的数据拟合模型。 希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 2019-12-26
      • 2016-03-18
      • 2018-08-16
      • 2019-01-25
      • 2017-03-02
      • 2016-08-12
      • 1970-01-01
      • 2018-05-15
      相关资源
      最近更新 更多