使用 sklearn.model_selection.GridSearchCV 进行模型超参数优化
是的,可以使用 sklearn.model_selection.GridSearchCV 进行模型超参数的计算。\n\n首先,需要导入相关的库和模块:\npython\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\n\n\n然后,准备好训练数据和目标变量:\npython\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\n\n接下来,定义要进行超参数搜索的模型和参数网格:\npython\nmodel = SVC()\nparam_grid = {'C': [1, 10, 100], 'gamma': [0.1, 0.01, 0.001]}\n\n\n然后,创建GridSearchCV对象,并进行模型训练和超参数搜索:\npython\ngrid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=5)\ngrid_search.fit(X_train, y_train)\n\n\n最后,可以查看最佳的超参数组合和对应的模型评分:\npython\nprint(grid_search.best_params_)\nprint(grid_search.best_score_)\n\n\n通过GridSearchCV对象的best_params_属性可以获取最佳的超参数组合,通过best_score_属性可以获取对应的模型评分。\n\n注意,上述代码中的X和y分别代表特征变量和目标变量的数据,需要根据具体的问题进行替换。另外,param_grid参数网格中的参数和取值范围也需要根据具体的模型和问题进行设置。
原文地址: https://www.cveoy.top/t/topic/pR9L 著作权归作者所有。请勿转载和采集!