利用sklearn来选择和训练模型,微调模型

选择和训练模型

线性回归模型

from sklearn.linear_model import LinearRegression

lin_reg = LinearRegression()
lin_reg.fit(housing_prepared, housing_labels)

现在就构建好了一个可以工作的线性回归模型。
可以使用sklearn的mean_squared_error函数来测量整个训练集上回归模型的RMSE:

from sklearn.metrics import mean_squared_error
housing_predictions = lin_reg.predict(housing_prepared)
lin_mse = mean_squared_error(housing_labels, housing_predictions)
lin_rmse = np.sqrt(lin_mse)      # 68628.413493824875

决策树模型

它能够从数据中找到复杂的非线性关系。

from sklearn.tree import DecisionTreeRegressor

tree_reg = DecisionTreeRegressor()
tree_reg.fit(housing_prepared, housing_labels)

housing_predicions = tree_reg.predict(housing_prepared)
tree_mse = mean_squared_error(housing_labels, housing_predicions)
tree_rmse = np.sqrt(tree_mse)      # 0.0

我们可以看到结果是完全没有错误,说明这个模型对数据严重过拟合。
现在来改进一下评估的策略

使用交叉验证来更好的进行评估

使用sklearn的交叉验证功能。以下是执行k-折交叉验证的代码:它将训练集随机分割成10个不同的子集,每个子集称为一个折叠,然后对决策树模型进行10此训练和评估——每次挑选一个折叠进行评估, 使用另外9个折叠进行训练。产出的结果是一个包含10次评估分数的数组:

from sklearn.model_selection import cross_val_score
scores = cross_val_score(tree_reg, housing_prepared, housing_labels,
                         scoring="neg_mean_squared_error", cv=10)
rmse_scores = np.sqrt(-scores)

sklearn的交叉验证功能更倾向于使用效用函数(越大越好)而不是成本函数(越小越好),所以计算分数的函数实际上是负的MSE

def display_scores(scores):
    print("Scores:", scores)
    print("Mean:", scores.mean())
    print("Standard deviation:", scores.std())

随机森林

from sklearn.ensemble import RandomForestRegressor
forest_reg = RandomForestRegressor()
forest_reg.fit(housing_prepared, housing_labels)
forest_scores = cross_val_score(forest_reg, housing_prepared, housing_labels,
                             scoring="neg_mean_squared_error", cv=10)
forest_rmse_scores = np.sqrt(-forest_scores)

随机森林:
Scores: [49565.79529588 47337.80993895 50185.64303548 52405.39139117
49600.49582891 53273.54270025 48704.41836964 47764.91984528
52851.82081761 50215.74587276]
Mean: 50190.55830959307
Standard deviation: 1961.179867922108

决策树:
Scores: [69626.46134399 67991.90860685 71566.04190367 70032.02237379
70596.49995302 74664.05771371 70091.6453497 71805.24386367
78157.17712767 69618.17027461]
Mean: 71414.92285106823
Standard deviation: 2804.7690022906345

线性回归:

Scores: [66877.52325028 66608.120256 70575.91118868 74179.94799352
67683.32205678 71103.16843468 64782.65896552 67711.29940352
71080.40484136 67687.6384546 ]
Mean: 68828.99948449328
Standard deviation: 2662.7615706103393

使用python 的pickel模块或是joblib库可以轻松保存sklearn模型,这样可以更有效。

import joblib
joblib.dump(my_model, "my_model.pkl")

my_model_loaded = joblib.load("my_model.pkl")

微调模型

网格搜索

可以使用sklearn的GridSearchCV来替你进行搜索。

from sklearn.model_selection import GridSearchCV

param_grid = [
    {'n_estimators' : [3, 10, 30], 'max_features' : [2, 4, 6, 8]},
    {'bootstrap' : [False], 'n_estimators' : [3, 10], 'max_features' : [2, 3, 4]},
]

forest_reg = RandomForestRegressor()
grid_search = GridSearchCV(forest_reg, param_grid, cv=5, scoring='neg_mean_squared_error')
grid_search.fit(housing_prepared, housing_labels)

最佳的参数组合:
grid_search.best_params_
最好的估算器:
grid_search.best_estimator_
评估分数

cvres = grid_search.cv_results_
for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]):
    print(np.sqrt(-mean_score), params

随机搜索

当搜索的组合数量较少——网格搜索是不错的;但是当搜索的范围较大时,通常会优先选择使用RandomizedSearchCV,它不会尝试所有可能的组合,而是在每次迭代中为每个超参数选择一个随机值,然后对一定数量的随机组合进行评估。

feature_importances = grid_search.best_estimator_.feature_importances_

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
好的,以下是一个用向量机模型微调pkuseg模型的例子: 1.准备数据集 首先需要准备好数据集,包括训练集和测试集。训练集需要标注好每个词语的分词结果,测试集则只需要包含待分词的文本。 2.加载pkuseg模型 使用Python中的pkuseg库,加载pkuseg模型并设置合适的参数。例如: ``` import pkuseg seg = pkuseg.pkuseg() ``` 3.将数据集分词 使用pkuseg模型训练集和测试集中的文本分词,并将结果转化为向量表示。可以使用Python中的numpy库来实现。 ``` import numpy as np train_text = ['这是一条训练集样本', '这是另一条训练集样本', ...] test_text = ['这是一条测试集样本', '这是另一条测试集样本', ...] train_seg = [seg.cut(text) for text in train_text] test_seg = [seg.cut(text) for text in test_text] train_vec = np.array([np.mean([model[word] for word in sentence if word in model] or [np.zeros(100)], axis=0) for sentence in train_seg]) test_vec = np.array([np.mean([model[word] for word in sentence if word in model] or [np.zeros(100)], axis=0) for sentence in test_seg]) ``` 这里使用的是word2vec模型,将每个词语转化为向量,并将整个文本的向量表示为每个词向量的均值。需要注意的是,如果某个词语不在word2vec模型中,则使用全零向量代替。 4.微调向量机模型 使用Python中的sklearn库,微调向量机模型训练并预测测试集的结果。例如: ``` from sklearn.svm import SVC svm = SVC(kernel='linear') svm.fit(train_vec, train_label) test_pred = svm.predict(test_vec) ``` 这里使用的是线性核函数的支持向量机模型,可以根据需要进行调整。 5.评估结果 使用Python中的sklearn库,计算模型在测试集上的准确率、召回率、F1值等指标。例如: ``` from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score acc = accuracy_score(test_label, test_pred) pre = precision_score(test_label, test_pred) rec = recall_score(test_label, test_pred) f1 = f1_score(test_label, test_pred) ``` 根据实际情况,可以选择不同的评估指标来衡量模型的性能。 以上就是一个用向量机模型微调pkuseg模型的示例,希望对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

evil心安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值