当前位置:   article > 正文

Python进行参数调优GridSearchCV和RandomizedSearchCV_tuned_parameters

tuned_parameters
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Sep 6 14:30:24 2017
  4. @author: 飘的心
  5. """
  6. from sklearn.datasets import load_digits
  7. from sklearn.linear_model import LogisticRegression
  8. from sklearn.model_selection import GridSearchCV
  9. from sklearn.metrics import classification_report
  10. from sklearn.model_selection import train_test_split
  11. from sklearn import metrics
  12. data=load_digits()
  13. x=data.data
  14. y=data.target
  15. x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=0,test_size=0.25,
  16. stratify=y)
  17. #采用暴力搜索,所有参数进行组合,然后选择最好的参数
  18. tuned_parameters=[{'penalty':['l1','l2'],
  19. 'C':[0.01,0.05,0.1,0.5,1,5,10,50,100],
  20. 'solver':['liblinear'],
  21. 'multi_class':['ovr']},
  22. {'penalty':['l2'],
  23. 'C':[0.01,0.05,0.1,0.5,1,5,10,50,100],
  24. 'solver':['lbfgs'],
  25. 'multi_class':['ovr','multinomial']}]
  26. clf=GridSearchCV(LogisticRegression(tol=1e-6),tuned_parameters,cv=10)
  27. clf.fit(x_train,y_train)
  28. print('Best parameters set found:',clf.best_params_)
  29. print(classification_report(y_test,clf.predict(x_test)))
  30. print(metrics.confusion_matrix(y_test,clf.predict(x_test)))
  31. from sklearn.datasets import load_digits
  32. from sklearn.linear_model import LogisticRegression
  33. from sklearn.model_selection import RandomizedSearchCV
  34. from sklearn.metrics import classification_report
  35. from sklearn.model_selection import train_test_split
  36. import scipy
  37. digits=load_digits()
  38. x=digits.data
  39. y=digits.target
  40. x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=0,test_size=0.25,
  41. stratify=y)
  42. #采用随机搜索,给参数一个范围,然后系统随机选择参数,进行检验,然后选择最好的
  43. tuned_parameters={'C':scipy.stats.expon(scale=100),
  44. 'multi_class':['ovr','multinomial']}
  45. clf=RandomizedSearchCV(LogisticRegression(penalty='l2',solver='lbfgs',tol=1e-6),
  46. tuned_parameters,cv=10,scoring='accuracy',n_iter=100)
  47. clf.fit(x_train,y_train)
  48. print('best parameters:',clf.best_estimator_)
  49. print(classification_report(y_test,clf.predict(x_test)))
  50. print(metrics.confusion_matrix(y_test,clf.predict(x_test)))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/285443
推荐阅读
  

闽ICP备14008679号