sklearn 学习笔记2
学习资源
https://tianchi.aliyun.com/course/courseConsole?courseId=41138
学习内容
- 模型分割 from sklearn.model_selection import train_test_split
- 标准化 from sklearn.preprocessing import StandardScaler
- 参数优化(grid search)
from sklearn.model_selection import GridSearchCV
起飞
In[1]:
import numpy as np
from sklearn import datasets
iris=datasets.load_iris()
In[2]:
X=iris.data
y=iris.target
In[3]:
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(iris.data,iris.target,test_size=0.2,random_state=666)
In[4]:
from sklearn.preprocessing import StandardScaler
standardScaler=StandardScaler()
In[5]:
#得先fit再transform
standardScaler.fit(X_train)
In[6]:
standardScaler.mean_
In[7]:
standardScaler.transform(X_train)
In[8]:
X_train = standardScaler.transform(X_train)
In[9]:
#standardScaler是用训练集fit的参数
X_test_standard = standardScaler.transform(X_test)
In[10]:
from sklearn.neighbors import KNeighborsClassifier
knn_clf = KNeighborsClassifier(n_neighbors=3)
knn_clf.fit(X_train,y_train)
In[11]:
knn_clf.score(X_test_standard,y_test)
In[12]:
knn_clf.score(X_test,y_test)
In[13]:
knn_clf.predict(X_test_standard[-1:,:])
##2 网格搜索
In[14]:
digits = datasets.load_digits()
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(digits.data,digits.target,test_size=0.2,random_state=666)
In[15]:
sk_knn_clf = KNeighborsClassifier(n_neighbors=4,weights='uniform')
sk_knn_clf.fit(X_train,y_train)
sk_knn_clf.score(X_test,y_test)
In[16]:
param_grid=[
{
'weights':['uniform'],
'n_neighbors':[i for i in range(1,11)]
},
{
'weights':['distance'],
'n_neighbors':[i for i in range(1,11)]
}
]
In[17]:
knn_clf = KNeighborsClassifier()
In[18]:
from sklearn.model_selection import GridSearchCV
grid_search = GridSearchCV(knn_clf,param_grid)
In[19]:
grid_search.fit(X_train,y_train)
In[20]:
knn_clf = grid_search.best_estimator_
knn_clf
In[21]:
grid_search.best_score_
In[22]:
grid_search.best_params_
In[23]:
knn_clf.score(X_test,y_test)
看起来有点乱notebook我也上传了但是可能时间久了要积分吧