发布于2019-08-22 19:38 阅读(922) 评论(0) 点赞(1) 收藏(2)
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
作者:j878
链接:https://www.pythonheidong.com/blog/article/53463/ca5341a4262c109025e5/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!