Я работаю над проблемой бинарной классификации, где мой набор данных имеет категориальные и численные столбцы. < /P>
Тем не менее, некоторые категориальных столбцов имеет сочетание числовых и строковых значений. Тем не менее, они указывают только имя категории. и т. д.
Я думаю, что приведенная ниже ошибка добавлена из -за таких значений, как 4 и 5 .
Поэтому я попробовал ниже. Конвертировать их в категорию dataType. (но все же это не работает) < /p>
Код: Выделить всё
cols=X_train.select_dtypes(exclude='int').columns.to_list()
X_train[cols]=X_train[cols].astype('category')
< /code>
И моя информация о данных выглядит ниже < /p>
Int64Index: 683 entries, 21 to 965
Data columns (total 9 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Feature_A 683 non-null category
1 Product Classification 683 non-null category
2 Industry 683 non-null category
3 DIVISION 683 non-null category
4 biz_category 683 non-null category
5 Country 683 non-null category
6 Product segment 683 non-null category
7 SUBREGION 683 non-null category
8 Quantity 1st year 683 non-null int64
dtypes: category(8), int64(1)
< /code>
Итак, после преобразования dtype, когда я пробую приведенную смесь, я получаю ошибку < /p>
print("Before OverSampling, counts of label '1': {}".format(sum(y_train == 1)))
print("Before OverSampling, counts of label '0': {} \n".format(sum(y_train == 0)))
cat_index = [0,1,2,3,4,5,6,7]
# import SMOTE module from imblearn library
# pip install imblearn (if you don't have imblearn in your system)
from imblearn.over_sampling import SMOTE, SMOTENC
sm = SMOTENC(categorical_features=cat_index,random_state = 2,sampling_strategy = 'minority')
X_train_res, y_train_res = sm.fit_resample(X_train, y_train)
< /code>
Это приводит к ошибке, как показано ниже < /p>
----------------- ------------------------------------------------------ ------------ TypeError Traceback (самый последний звонок
last)
~ ~ appdata\raming\python\python39\site-packages \sklearn\tils_encode.py
в _unique_python (values, return_inverse)
134
-> 135 Uniques = sorted (Uniques_set)
136 Uniques.extend (missing_values.to_list ()) < /p>
typeerror: '
Во время обработки вышеуказанного исключения произошло другое исключение: < /p>
typeError traceback (самый последний звонок
last)
c:lasers \Sathap~1\ imblearn.over_sampling importmote, Smotenc
7 sm = smotenc (categorical_features = cat_index, random_state = 2, sampling_strategy = 'minority')
----> 8 x_train_res, y_train_res = sm.fit_resample (x_train y_train)
9
10 print ('после перевозки, форма train_x: {}'. Format (x_train_res.shape)) < /p>
~ \ appdata \ roaming \ Python \ python39 \ site-packages \ imblearn \ base.py в
fit_resample (self, x, y)
81)
82
---> 83 output = self . Пакеты \ imblearn \ over_sampling_smote \ base.py
in fit_resample (self, x, y)
511
512 # Ввод Onehotencoder должен быть плотным
-- -> 513 x_ohe = self.ohe < /em> .fit_transform (
514 x_categorical.toarray () if sparse.issparse (x_categorical) else x_categorical
515) < /p>
~ \ Appdata \ roaming \ python \ python39 \ site-packages \ sklearn \ preprocessing_encoders.py
in fit_transform (self, x, y)
486 ""
487 self._validate_keywords (br /> 486 ""
487 )
-> 488 return super (). fit_transform (x, y)
489
490 def transform (self, x): < /p>
~ \ Appdata \ roaming \ python \ python39 \ site-packages \ sklearn \ base.py в
fit_transform (self, x, y, ** fit_params)
850, если y не:
851 # Способный метод Arity 1 (неконтролируемое преобразование)
-> 852 return self.fit (x, ** fit_params) .transform (x)
853 else:
854 # Метод подключения Arity 2 (контролируемое преобразование) br /> 459 "" "
460 self._validate_keywords ()
-> 461 self. fit (x, harder_unknown = self.handle_unknow /> 462 self.drop_idx < /em> = self._compute_drop_idx ()
463 return self < /p>
~ \ appdata \ roaming \ python \ python39 \ site-packages \ sklearn \ preprocessing_encoders.py
in _fit (self, x, harder_unknown, force_all_finite)
92 xi = x_list [i]
93 if self.categories == "Auto":
- -> 94 Cats = _unique (xi)
95 els > ~ \ Appdata \ roaming \ python \ python39 \ site-packages \ sklearn \ utils_encode.py
in _unique (values, return_inverse)
29 "" "
30 if values.dtype == Объект:
---> 31 return _unique_python (values, return_inverse = return_inverse)
32 # numerical
33 out = np.unique (значения, return_inverse = return_inverse) < /p>
~ aappdata\raaming\python\python39\site-packages \Sklearn\tils_encode.py
in _unique_python (values, return_inverse)
138, кроме типа:
139 типы = отсортирован (t. QualName < /strong> для t в set (type (v) для v в значениях))
-> 140 reage typeError (
141 "Энкодеры требуют, чтобы их ввод был равномерно "
142 f" или струны или числа. Получил {types} "< /p>
typeerror: кодеры требуют, чтобы их ввод был равномерно строк или
. >
Должен ли я преобразовать y_train
Подробнее здесь: https://stackoverflow.com/questions/711 ... umbers-got