我已經在這里、這里和這里提到了這些帖子。不要將其標記為重復。
我正在研究一個二進制分類問題,其中我的資料集具有分類和數字列。
但是,某些分類列混合了數字和字串值。盡管如此,它們僅指示類別名稱。
例如,我有一個名為的列,其中包含諸如etcbiz_category之類的值。A,B,C,4,5
我猜下面的錯誤是由于像4 and 5.
因此,我嘗試將它們轉換為category資料型別。(但它仍然不起作用)
cols=X_train.select_dtypes(exclude='int').columns.to_list()
X_train[cols]=X_train[cols].astype('category')
我的資料資訊如下所示
<class 'pandas.core.frame.DataFrame'>
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)
所以,在 dtype 轉換之后,當我嘗試下面的 SMOTENC 時,我得到一個錯誤
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)
這會導致錯誤,如下所示
-------------------------------------------------- ------------------------- TypeError Traceback(最近一次呼叫最后)~\AppData\Roaming\Python\Python39\site-packages\sklearn\utils_encode .py in _unique_python(values, return_inverse) 134 --> 135 uniques = sorted(uniques_set) 136 uniques.extend(missing_values.to_list())
TypeError:“str”和“int”的實體之間不支持“<”
在處理上述例外的程序中,又出現了一個例外:
TypeError Traceback(最近一次呼叫最后)C:\Users\SATHAP~1\AppData\Local\Temp/ipykernel_31168/1931674352.py in 6 from imblearn.over_sampling import SMOTE, 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('OverSampling后,train_X的形狀:{}'.format(X_train_res.shape))
~\AppData\Roaming\Python\Python39\site-packages\imblearn\base.py in fit_resample(self, X, y) 81 ) 82 ---> 83 output = self. fit_resample(X, y) 84 85 y = (
~\AppData\Roaming\Python\Python39\site-packages\imblearn\over_sampling_smote\base.py in fit_resample(self, X, y) 511 512 # OneHotEncoder 的輸入需要密集 --> 513 X_ohe = self. ohe .fit_transform(514 X_categorical.toarray() if sparse.issparse(X_categorical) else X_categorical 515)
~\AppData\Roaming\Python\Python39\site-packages\sklearn\preprocessing_encoders.py in fit_transform(self, X, y) 486 """ 487 self._validate_keywords() --> 488 return super().fit_transform(X , y) 489 490 def 變換(self, X):
~\AppData\Roaming\Python\Python39\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params) 850 if y is None: 851 # fit method of arity 1 (unsupervised transformation) - -> 852 return self.fit(X, **fit_params).transform(X) 853 else: 854 # arity 2 的擬合方法(監督變換)
~\AppData\Roaming\Python\Python39\site-packages\sklearn\preprocessing_encoders.py in fit(self, X, y) 459 """ 460 self._validate_keywords() --> 461 self.fit(X, handle_unknown= self.handle_unknown, force_all_finite="allow-nan") 462 self.drop_idx = self._compute_drop_idx() 463 return self
~\AppData\Roaming\Python\Python39\site-packages\sklearn\preprocessing_encoders.py in _fit(self, X, handle_unknown, force_all_finite) 92 Xi = X_list[i] 93 if self.categories == "auto": -- -> 94 只貓 = _unique(Xi) 95 其他:96 只貓 = np.array(self.categories[i], dtype=Xi.dtype)
~\AppData\Roaming\Python\Python39\site-packages\sklearn\utils_encode.py in _unique(values, return_inverse) 29 """ 30 if values.dtype == object: ---> 31 return _unique_python(values, return_inverse =return_inverse) 32 # 數值 33 out = np.unique(values, return_inverse=return_inverse)
~\AppData\Roaming\Python\Python39\site-packages\sklearn\utils_encode.py in _unique_python(values, return_inverse) 138 除了 TypeError: 139 types = sorted(t. qualname for t in set(type(v) for v in values)) --> 140 raise TypeError( 141 "編碼器要求其輸入統一為 " 142 f" 字串或數字。得到 {types}"
TypeError:編碼器要求其輸入統一為字串或數字。得到 ['int', 'str']
我y_train也應該轉換為分類嗎?目前,它是int64.
請幫忙
uj5u.com熱心網友回復:
問題的原因
SMOTE要求每個分類/數值列中的值具有統一的資料型別。本質上,在這種情況下,您的biz_category列中的任何列中都不能有混合資料型別。此外,僅將列轉換為分型別別并不一定意味著該列中的值將具有統一的資料型別。
可能的解決方案
這個問題的一種可能的解決方案是重新編碼那些具有混合資料型別的列中的值,例如你可以使用 lableencoder 但我認為在你的情況下簡單地改變dtypetostring也可以。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/429592.html
標籤:Python 熊猫 机器学习 scikit-学习 打击
上一篇:在熊貓資料框中將列名轉換為字串
