文本挖掘模型整合
网格搜索算法是一种通过遍历给定的参数组合来优化模型表现的方法。
以决策树为例,当我们确定了要使用决策树算法的时候,为了能够更好地拟合和预测,我们需要调整它的参数。在决策树算法中,我们通常选择的参数是决策树的较大深度。
于是我们会给出一系列的较大深度的值,比如 {'max_depth': [1,2,3,4,5]},我们会尽可能包含最优较大深度。
不过,我们如何知道哪一个较大深度的模型是较好的呢?我们需要一种可靠的评分方法,对每个较大深度的决策树模型都进行评分,这其中非常经典的一种方法就是交叉验证,下面我们就以K折交叉验证为例,详细介绍它的算法过程。
首先我们先看一下数据集是如何分割的。我们拿到的原始数据集首先会按照一定的比例划分成训练集和测试集。比如下图,以8:2分割的数据集:
训练集用来训练我们的模型,它的作用就像我们平时做的练习题;测试集用来评估我们训练好的模型表现如何,它的作用像我们做的高考题,这是要保密不能提前被模型看到的。
因此,在K折交叉验证中,我们用到的数据是训练集中的所有数据。我们将训练集的所有数据平均划分成K份(通常选择K=10),取第K份作为验证集,它的作用就像我们用来估计高考分数的模拟题,余下的K-1份作为交叉验证的训练集。
对于我们最开始选择的决策树的5个较大深度 ,以 max_depth=1 为例,我们先用第2-10份数据作为训练集训练模型,用第1份数据作为验证集对这次训练的模型进行评分,得到第一个分数;然后重新构建一个 max_depth=1 的决策树,用第1和3-10份数据作为训练集训练模型,用第2份数据作为验证集对这次训练的模型进行评分,得到第二个分数……以此类推,最后构建一个 max_depth=1 的决策树用第1-9份数据作为训练集训练模型,用第10份数据作为验证集对这次训练的模型进行评分,得到第十个分数。于是对于 max_depth=1 的决策树模型,我们训练了10次,验证了10次,得到了10个验证分数,然后计算这10个验证分数的平均分数,就是 max_depth=1 的决策树模型的最终验证分数。
对于 max_depth = 2,3,4,5 时,分别进行和 max_depth=1 相同的交叉验证过程,得到它们的最终验证分数。然后我们就可以对这5个较大深度的决策树的最终验证分数进行比较,分数较高的那一个就是最优较大深度,对应的模型就是最优模型。
code:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn import svm
import lightgbm as lgb
from sklearn.metrics import f1_score
from sklearn.externals import joblib
from sklearn.model_selection import GridSearchCV
dataPath = 'H:/nlp/new_data/train_set_0.csv'
df_train = pd.read_csv(dataPath)
vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=3, max_df=0.9, sublinear_tf=True)
vectorizer.fit(df_train['word_seg'])
x_train = vectorizer.transform(df_train['word_seg'])
x_train,x_test,y_train,y_test = train_test_split(x_train,df_train['class'],test_size=0.3)
clf = LogisticRegression(C=120, dual=True)
#clf = svm.LinearSVC(C=5, dual=False)
clf.fit(x_train, y_train)
y_prediction = clf.predict(x_test)
f1 = f1_score(y_test, y_prediction, average='micro')
print('The F1 Score: ' + str("%.2f" % f1))
gbm = lgb.sklearn.LGBMClassifier(num_leaves=31,learning_rate=0.05,n_estimators=20)
gbm.fit(x_train,y_train)
gbm_predictions = gbm.predict(x_test)
gbm_f1 = f1_score(y_test, gbm_predictions, average='weighted')
print("The gbm F1 Score: {:.2f}".format(gbm_f1))
algorithms = [LogisticRegression(C=120, dual=True), svm.LinearSVC(C=5, dual=False)]
predictions = []
for algLRSVM algorithms:
algLRSVM.fit(x_train, y_train)
prediction = algLRSVM.decision_function(x_test.astype(float))
predictions.append(prediction)
y_prediction = (predictions[0] + predictions[1]) / 2
y_prediction = np.argmax(y_prediction, axis=1)+1
f1 = f1_score(y_test, y_prediction, average='micro')
f1:0.7013
参考:
1.http://f.dataguru.cn/thread-911758-1-1.html
2.https://blog.****.net/selous/article/details/70229180
3.https://blog.****.net/qq_23953717/article/details/80439601
4.https://www.cnblogs.com/nwpuxuezha/p/6618205.html
5.https://blog.****.net/weixin_41988628/article/details/83098130