我正在Kaggle上测试Titanic数据集。我使用dropna()使其保持简单,还删除了几列。但是,调用fit()方法时,出现“ TypeError:类型为'CategoricalDtype'的对象没有len()“消息。
我尝试使用不同的分类器,但出现相同的错误。我想我的数据准备工作有问题。
df = pd.read_csv('train.csv')
df.drop('PassengerId', axis=1, inplace=True)
df.drop('Ticket', axis=1, inplace=True)
df.drop('Cabin', axis=1, inplace=True)
df.drop('Embarked', axis=1, inplace=True)
df=df.dropna()
mapping = {'male': 0, 'female': 1}
df = df.replace({'Sex': mapping})
paramlist=['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']
X, y = df[paramlist], df.Survived.astype('category')
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
classifier = KNeighborsClassifier(n_neighbors=3)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
confusion_table = confusion_matrix(y_test, y_pred)
print("KNN regression using: "+ str(paramlist))
print(confusion_table)
print(classification_report(y_test, y_pred))
print(f"Accuracy: {accuracy_score(y_test, y_pred)}")
print("=======================================")
```python
Error trace -
File "<ipython-input-2-e6618b2ba888>", line 1, in <module>
runfile('C:/Users/vvnat/Documents/Vaibhav/Dropbox/Kaggle/Titanic/Titanic.py', wdir='C:/Users/vvnat/Documents/Vaibhav/Dropbox/Kaggle/Titanic')
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/vvnat/Documents/Vaibhav/Dropbox/Kaggle/Titanic/Titanic.py", line 222, in <module>
classifier.fit(X_train, y_train)
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\neighbors\base.py", line 891, in fit
X, y = check_X_y(X, y, "csr", multi_output=True)
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 759, in check_X_y
dtype=None)
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 480, in check_array
if hasattr(array, "dtypes") and len(array.dtypes):
TypeError: object of type 'CategoricalDtype' has no len()
答案 0 :(得分:1)
此错误意味着数据框中某些列的dtype为'类别',因此您应首先使用df.info检查每列的dtype,然后尝试检查每列的合适dtype并使用astype()更改错误列的dtype,例如“ np.int64”或“ np.float64”。祝你好运
答案 1 :(得分:0)
尝试在train_test_split()之前创建X和y个np.array,id est X = np.array(X)和y = np.array(y)