Как использовать случайный лес с разреженными данными?

#python #scikit-learn #classification #random-forest

#питон #scikit-учиться #классификация #случайный лес

Вопрос:

Я пытаюсь использовать случайный лесной классификатор SKLearn. У меня есть эта ошибка :

 ValueError: setting an array element with a sequence.
 

Не могу понять, откуда это берется. Вот мой код :

 ##import here

def get_data_target(lang):
    with open('vect/'   lang   '/vect_' lang, "rb") as f:
        vect = pickle.load(f)
        data, target = [], []
        i = 0
        for v in vect:
            for x, y in v.items():
                data.append(y)
                target.append(x)
                
        return np.asarray(data), np.asarray(target)

data_fr, target_fr = get_data_target('fr')


X_train, X_test, y_train, y_test = train_test_split(data_fr, target_fr, test_size=0.1, random_state=0)

random_forest = RandomForestClassifier(n_estimators=30, max_depth=10, random_state=1)
random_forest.fit(X_train, y_train)
 

Редактировать :

Ибо print(X_train[:10]) у меня есть :

 [<1x567 sparse matrix of type '<class 'numpy.int64'>'
    with 567 stored elements in Compressed Sparse Row format>
 <1x5574 sparse matrix of type '<class 'numpy.int64'>'
    with 5574 stored elements in Compressed Sparse Row format>
 <1x6419 sparse matrix of type '<class 'numpy.int64'>'
    with 6419 stored elements in Compressed Sparse Row format>
 <1x1477 sparse matrix of type '<class 'numpy.int64'>'
    with 1477 stored elements in Compressed Sparse Row format>
 <1x1347 sparse matrix of type '<class 'numpy.int64'>'
    with 1347 stored elements in Compressed Sparse Row format>
 <1x3588 sparse matrix of type '<class 'numpy.int64'>'
    with 3588 stored elements in Compressed Sparse Row format>
 <1x5856 sparse matrix of type '<class 'numpy.int64'>'
    with 5856 stored elements in Compressed Sparse Row format>
 <1x1080 sparse matrix of type '<class 'numpy.int64'>'
    with 1080 stored elements in Compressed Sparse Row format>
 <1x1600 sparse matrix of type '<class 'numpy.int64'>'
    with 1600 stored elements in Compressed Sparse Row format>
 <1x6781 sparse matrix of type '<class 'numpy.int64'>'
    with 6781 stored elements in Compressed Sparse Row format>]
 

И для моей ошибки трассировки стека у меня есть что-то вроде этого :

 ---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-35-526b5f56b73c> in <module>
      3 random_forest = RandomForestClassifier(n_estimators=30, max_depth=10, random_state=1)
      4 
----> 5 random_forest.fit(X_train, y_train)

D:Anacondalibsite-packagessklearnensembleforest.py in fit(self, X, y, sample_weight)
    247 
    248         # Validate or convert input data
--> 249         X = check_array(X, accept_sparse="csc", dtype=DTYPE)
    250         y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)
    251         if sample_weight is not None:

D:Anacondalibsite-packagessklearnutilsvalidation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    494             try:
    495                 warnings.simplefilter('error', ComplexWarning)
--> 496                 array = np.asarray(array, dtype=dtype, order=order)
    497             except ComplexWarning:
    498                 raise ValueError("Complex data not supportedn"

D:Anacondalibsite-packagesnumpycorenumeric.py in asarray(a, dtype, order)
    536 
    537     """
--> 538     return array(a, dtype, copy=False, order=order)
    539 
    540 

ValueError: setting an array element with a sequence.
 

Комментарии:

1. может быть, это потому, что у вас разреженная матрица?

2. Привет @Tuqay, да, возможно, в этом проблема, но я не знаю, что я могу сделать, чтобы использовать случайный лес в разреженной матрице..

3. преобразуйте его в обычную матрицу

4. Привет @Tuqay, я это сделал, но теперь у меня появилась новая проблема, которая : ValueError: could not broadcast input array from shape (3638) into shape (1)

5. Вы уверены, что не перепутали x и y?