首页 > 解决方案 > Unhashable 类型:使用 GridSearchCV 进行 KNN 超参数调整时出现“numpy.ndarray”错误

问题描述

所以我在导入所有必要的库后使用以下代码调整 n_neighbors 超参数

    import numpy as np
    import pandas as pd
    from sklearn.neighbors import KNeighborsClassifier
    from sklearn.model_selection import GridSearchCV

    df = pd.read_csv('path of file')
    df.head()

    # Creating feature "X" and target "y"
    X = df.drop('Species', axis=1).values
    y = df['Species'].values

    knn = KNeighborsClassifier()

    #This is where the error pops up

    param_grid = {'n_neighbors', np.arange(1,50)}

    #.................................................

    knn_cv = GridSearchCV(knn, param_grid, cv=5)
    knn_cv.fit(X,y)
    Print ('Best parameters: {}'.format{knn_cv.best_params_})
    Print ('Best score: {}'.format{knn_cv.best_score_})


   -------------------------------------------------------------------
    TypeError                      Traceback (most recent call last)
    <ipython-input-94-75a644fe3635> in <module>
          1 knn = KNeighborsClassifier()
    ----> 2 param_grid = {'n_neighbors', np.arange(1,50)}

    TypeError: unhashable type: 'numpy.ndarray'

执行错误时显示 Unhashable type: 'numpy.ndarray' 弹出。请帮忙。我是一名初学者,试图在 iris 数据集上练习一些监督学习。

标签: pythondata-sciencecss-gridknnhyperparameters

解决方案


推荐阅读