机器学习——K折交叉验证

K折交叉验证

通过测试、验证,进而评估你的算法是否能够做你想做的。

sklearn中的K折交叉验证

在这里插入图片描述
可通过简单的方式随机化 Sklearn k 折 CV 中的事件,就是将 shuffle 标志设置为 true。

之后,代码将从如下所示:

cv = KFold( len(authors), 2 )

可变为如下所示:

cv = KFold( len(authors), 2, shuffle=True )

shuffle=True 可避免所有某一特定类型的事件都属于训练集,而另一特定类型的事件则属于测试集,在这种情况下,针对一种类型事件的训练不会帮助我们成功地对另一类型的事件进行分类

from sklearn.cross_validation import KFold
t0= time()
cv = KFold( len(authors), 2, shuffle=True ) #将 shuffle 标志设置为 true来随机化 Sklearn K-fold cross validation 中的事件
for train_indices,test_indices in kf:
    # make training and testing datasets
    features_train = [word_data[ii] for ii in train_indices] #利用索引进入特征和标签
    features_test = [word_data[ii] for ii in test_indices]
    authors_train = [authors[ii] for ii in train_indices]
    authors_test = [authors[ii] for ii in train_indices]

    # TFIDF and feature selection
    vectorizer = TfidfVectorizer(sublinear_tf = True,max_df=0.5,
                                 stop_words = 'english')
    feature_train_transformed = vectorizer.fit_transform(features_train)
    feature_test_transformed = vectorizer.transform(features_test)
    selector = SelectPercentile(f_classif,percentile = 10)
    selector.fit(features_train_transformed,authors_train)
    features_train_transformed = selector.transform(features_train_transformed).toarray()
    features_test_transformed = selector.transform(features_test_transformed).toarray()

clf = GaussianNB()
clf.fit(features_train_transformed,authors_train)
print "training time:" ,round(time() - t0,3),'s'
t0=time()
pred = clf.predict(features_test_transfomed)
print "predicting time",round(time() - t0,3),'s'
acc = accuracy_score(pred,authors_test)
print "accuracy:", round(acc,3)

sklearn中的GridSearchCV

GridSearchCV 用于系统地遍历多种参数组合,通过交叉验证确定最佳效果参数。它的好处是,只需增加几行代码,就能遍历多种组合。

下面是来自 sklearn 文档 的一个示例:

parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
svr = svm.SVC()
clf = grid_search.GridSearchCV(svr, parameters)
clf.fit(iris.data, iris.target)

让我们逐行进行说明。

parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}

参数字典以及他们可取的值。在这种情况下,他们在尝试找到 kernel(可能的选择为 ‘linear’ 和 ‘rbf’ )和 C(可能的选择为1和10)的最佳组合。

这时,会自动生成一个不同(kernel、C)参数值组成的“网格”:

('rbf', 1)	('rbf', 10)
('linear', 1)	('linear', 10)

各组合均用于训练 SVM,并使用交叉验证对表现进行评估。

svr = svm.SVC()

这与创建分类器有点类似,就如我们从第一节课一直在做的一样。但是请注意,“clf” 到下一行才会生成—这儿仅仅是在说采用哪种算法。另一种思考方法是,“分类器”在这种情况下不仅仅是一个算法,而是算法加参数值。请注意,这里不需对 kernel 或 C 做各种尝试;下一行才处理这个问题。

clf = grid_search.GridSearchCV(svr, parameters)

这是第一个不可思议之处,分类器创建好了。 我们传达算法 (svr) 和参数 (parameters) 字典来尝试,它生成一个网格的参数组合进行尝试。

clf.fit(iris.data, iris.target)

第二个不可思议之处。 拟合函数现在尝试了所有的参数组合,并返回一个合适的分类器,自动调整至最佳参数组合。现在您便可通过 clf.best_params_ 来获得参数值。

SVM 的哪些参数使用特征脸示例中的 GridSearchCV 进行自动调谐?
C和gamma

你的首个(过拟合)POI 标识符的准确度是多少?

将先开始构建想象得到的最简单(未经过验证的)POI 识别符。 本节课的初始代码 (validation/validate_poi.py) 相当直白——它的作用就是读入数据,并将数据格式化为标签和特征的列表。 创建决策树分类器(仅使用默认参数),在所有数据(你将在下一部分中修复这个问题!)上训练它,并打印出准确率。 这是一颗过拟合树,不要相信这个数字!尽管如此,准确率是多少?


import pickle
import sys
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit

sort_keys = '../tools/python2_lesson13_keys.pkl'
data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") )

### first element is our labels, any added elements are predictor
### features. Keep this the same for the mini-project, but you'll
### have a different feature list when you do the final project.
features_list = ["poi", "salary"]

data = featureFormat(data_dict, features_list)
labels, features = targetFeatureSplit(data)

from sklearn import tree
clf = tree.DecisionTreeClassifier()
clf.fit(features, labels)
pred_dt = clf.predict(features)

from sklearn.metrics import accuracy_score
acc_dt = accuracy_score(pred_dt, labels)
print acc_dt  # 0.989473684211

适当部署的测试范围的准确度

现在,你将添加训练和测试,以便获得一个可靠的准确率数字。 使用 sklearn.cross_validation 中的 train_test_split 验证; 将 30% 的数据用于测试,并设置 random_state 参数为 42(random_state 控制哪些点进入训练集,哪些点用于测试;将其设置为 42 意味着我们确切地知道哪些事件在哪个集中; 并且可以检查你得到的结果)。更新后的准确率是多少?

适当部署的测试范围的准确度是多少?



import pickle
import sys
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit

sort_keys = '../tools/python2_lesson13_keys.pkl'
data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") )

### first element is our labels, any added elements are predictor
### features. Keep this the same for the mini-project, but you'll
### have a different feature list when you do the final project.
features_list = ["poi", "salary"]

data = featureFormat(data_dict, features_list)
labels, features = targetFeatureSplit(data)
from sklearn i
mport tree
from sklearn.model_selection import train_test_split

features_train, features_test, labels_train, labels_test = \
train_test_split(features, labels, test_size = 0.3, random_state = 42)
clf = tree.DecisionTreeClassifier()
clf.fit(features_train, labels_train)
pred_dt = clf.predict(features_test)

from sklearn.metrics import accuracy_score
acc_dt = accuracy_score(pred_dt, labels_test)
print acc_dt  # 0.724137931034

0.724137931034

在上次测验中99%的准确率之后,测试数据让我们回到了现实中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章