Метод подгонки DecisionTreeClassifier в Scikit-learn дает ValueError: Не удалось передать входной массив из формы (10,35) в форму (10) - PullRequest
0 голосов
/ 03 февраля 2020

Итак, я пытаюсь создать дерево решений, и моя цель - массив [0, 1] (двоичный «НЕТ» или «ДА»), а мой вход training_set - трехмерный массив с первыми элементами, все примеры «НЕТ» ( 10) и с 35 функциями, одинаковыми с «Да». но я получаю эту ошибку.

    file1 = open(file1.txt) # examples of 'No' class
    file2 = open(file2.txt) # examples of 'Yes' class
    x = vectorizer.fit_transform(file1)
    y = vectorizer.fit_transform(file2)    

    x_array = x.toarray()    
    y_array = y.toarray()    


    x_train, x_test, y_train, y_test = train_test_split(x_array, y_array, 
    test_size=0.2)    
    target = [0, 1] # 0 encoded as 'No' and 1 as 'Yes
    train = [x_train, y_train]

    decisiontree = DecisionTreeClassifier(random_state=0, max_depth=5)
    decisiontree = decisiontree.fit(train, target)    

Спасибо за помощь.

Редактировать: я загружаю данные из текстового файла, и это текстовые данные, я пытался распечатать некоторую часть массива и вот оно

[[0 0 0 ... 0 0 0]    
 [0 0 0 ... 0 0 0]     
 [0 0 0 ... 0 0 0]     
 [0 0 0 ... 0 0 0]]    

1 Ответ

0 голосов
/ 03 февраля 2020

Я думаю, причина в том, что вы путаете с методом подгонки в decisiontree.fit.

Для decisiontree.fit(X,Y) он ожидает, что X будут точками данных, а Y - метками. То есть, если X имеет форму N x 32, тогда Y должен иметь форму N (где N - количество точек данных).

Вы должны объединить x_array и y_array как весь набор данных, разделите его и выполните fit с соответствующими метками.

Примите во внимание следующее:

# from sklearn.model_selection import train_test_split
# from sklearn.tree import DecisionTreeClassifier
import numpy as np

file1 = open(file1.txt)
file2 = open(file2.txt)
x = vectorizer.fit_transform(file1)
y = vectorizer.fit_transform(file2)    

x_array = x.toarray()    
y_array = y.toarray()

# ------------------------------------------------------------
# combine the positive and negative examples
data = np.concatenate([x_array, y_array], axis=0)
# create corresponding labels (based on the data's length)
labels = np.concatenate([np.zeros(x_array.shape[0]), 
                          np.ones(y_array.shape[0])], axis=0)

# split into train and test set
train_data, test_data, train_labels, test_labels = train_test_split(
    data, labels, test_size=0.2)

decisiontree = DecisionTreeClassifier(random_state=0, max_depth=5)
decisiontree = decisiontree.fit(train_data, train_labels)

# ------------------------------------------------------------
# this is how you can test model performance with the test set
correct_predictions = np.count_nonzero(
    decisiontree.predict(test_data) == test_labels
  )

print("Correct prediction in test set: {}/{}".format(correct_predictions,
                                                       test_labels.shape[0]))
...