1.划分训练测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
sample_train,label_train, test_size=0.3, random_state=0)
clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train) #建模
clf.score(X_test, y_test)#在测试集上输出得分
------------------
另一种分割方法(分层抽样)
from sklearn.model_selection import StratifiedShuffleSplit
df1["Fare"] = np.ceil(df1["Fare"])#数据取整
df1["Fare_ceng"] = np.where(df1["Fare"] > 4,4,df1["Fare"])#把大于4的归为一层
ssp = StratifiedShuffleSplit(n_splits=1,test_size=0.3,random_state=42)
for train_index,test_index in ssp.split(df1,df1["Fare_ceng"]):
X_train = df1.loc[train_index]
y_test = df1.loc[test_index]
------------------
clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train) #建模
predicet_y = clf.predict(X_train)
mean_squared_error(y_train,predicet_y)
#如果需要求rmse,则定义一个函数即可(见上一篇文章)
2.划分训练交叉验证
from sklearn.model_selection import cross_val_score
clf = svm.SVC(kernel='linear', C=1)
scores = cross_val_score(clf, X_train, y_train, cv=5)
scores
>>> array([0.96..., 1. ..., 0.96..., 0.96..., 1. ])
除了使用cross_val_score,也可以使用cross_validate,其可以指定多个评估指标
from sklearn.model_selection import cross_validate
from sklearn.model_selection import ShuffleSplit
scoring = ['precision_macro', 'recall_macro']
ss = ShuffleSplit(n_splits=3, test_size=0.1, random_state=1)#定义了一个交叉验证策略
clf = svm.SVC(kernel='linear', C=1, random_state=0)
scores = cross_validate(clf, X_train, y_train, scoring=scoring,cv=ss)
>>>{'fit_time': array([0.01800966, 0.01601005, 0.01500845, 0.01400208, 0.01299405]),
'score_time': array([0.00608897, 0.00397778, 0.00699639, 0.00700355, 0.00401688]),
'test_precision_macro': array([0.75409616, 0.81501832, 0.8212486 , 0.82296651, 0.8525641 ]),
'train_precision_macro': array([0.82061964, 0.81008636, 0.80972404, 0.80879461, 0.80566168]),
'test_recall_macro': array([0.75932018, 0.78666667, 0.81875 , 0.8375 , 0.82083333]),
'train_recall_macro': array([0.81333333, 0.81066584, 0.80334648, 0.79885624, 0.80734358])}
3.sklearn官方文档实在是太好用了
http://sklearn.apachecn.org/#/docs/30?id=_31-交叉验证:评估估算器的表现
4.注意
尽管 i.i.d (独立同分布)数据是机器学习理论中的一个常见假设,但在实践中很少成立。如果知道样本是使用时间相关的过程生成的,则使用 time-series aware cross-validation scheme 更安全。 同样,如果我们知道生成过程具有 group structure (群体结构)(从不同 subjects(主体) , experiments(实验), measurement devices (测量设备)收集的样本),则使用 group-wise cross-validation 更安全。
对于抽样方法:
1.如果是纯随机,则采用train_test_split
2.如果某些重要特征影响很大(如收入中位数对房价影响很大),则采用分层抽样
StratifiedshuffleSplit
3.如包含时间序列则采用TimeSeriesSplit