OpenCV python sklearn随机超参数搜索的实现


Posted in Python onJanuary 17, 2020

本文介绍了OpenCV python sklearn随机超参数搜索的实现,分享给大家,具体如下:

"""
房价预测数据集 使用sklearn执行超参数搜索
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import tensorflow as tf
from tensorflow_core.python.keras.api._v2 import keras # 不能使用 python
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split, RandomizedSearchCV
from scipy.stats import reciprocal

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
assert tf.__version__.startswith('2.')

# 0.打印导入模块的版本
print(tf.__version__)
print(sys.version_info)
for module in mpl, np, sklearn, pd, tf, keras:
  print("%s version:%s" % (module.__name__, module.__version__))


# 显示学习曲线
def plot_learning_curves(his):
  pd.DataFrame(his.history).plot(figsize=(8, 5))
  plt.grid(True)
  plt.gca().set_ylim(0, 1)
  plt.show()


# 1.加载数据集 california 房价
housing = fetch_california_housing()

print(housing.DESCR)
print(housing.data.shape)
print(housing.target.shape)

# 2.拆分数据集 训练集 验证集 测试集
x_train_all, x_test, y_train_all, y_test = train_test_split(
  housing.data, housing.target, random_state=7)
x_train, x_valid, y_train, y_valid = train_test_split(
  x_train_all, y_train_all, random_state=11)

print(x_train.shape, y_train.shape)
print(x_valid.shape, y_valid.shape)
print(x_test.shape, y_test.shape)

# 3.数据集归一化
scaler = StandardScaler()
x_train_scaled = scaler.fit_transform(x_train)
x_valid_scaled = scaler.fit_transform(x_valid)
x_test_scaled = scaler.fit_transform(x_test)


# 创建keras模型
def build_model(hidden_layers=1, # 中间层的参数
        layer_size=30,
        learning_rate=3e-3):
  # 创建网络层
  model = keras.models.Sequential()
  model.add(keras.layers.Dense(layer_size, activation="relu",
                 input_shape=x_train.shape[1:]))
 # 隐藏层设置
  for _ in range(hidden_layers - 1):
    model.add(keras.layers.Dense(layer_size,
                   activation="relu"))
  model.add(keras.layers.Dense(1))

  # 优化器学习率
  optimizer = keras.optimizers.SGD(lr=learning_rate)
  model.compile(loss="mse", optimizer=optimizer)

  return model


def main():
  # RandomizedSearchCV

  # 1.转化为sklearn的model
  sk_learn_model = keras.wrappers.scikit_learn.KerasRegressor(build_model)

  callbacks = [keras.callbacks.EarlyStopping(patience=5, min_delta=1e-2)]

  history = sk_learn_model.fit(x_train_scaled, y_train, epochs=100,
                 validation_data=(x_valid_scaled, y_valid),
                 callbacks=callbacks)
  # 2.定义超参数集合
  # f(x) = 1/(x*log(b/a)) a <= x <= b
  param_distribution = {
    "hidden_layers": [1, 2, 3, 4],
    "layer_size": np.arange(1, 100),
    "learning_rate": reciprocal(1e-4, 1e-2),
  }

  # 3.执行超搜索参数
  # cross_validation:训练集分成n份, n-1训练, 最后一份验证.
  random_search_cv = RandomizedSearchCV(sk_learn_model, param_distribution,
                     n_iter=10,
                     cv=3,
                     n_jobs=1)
  random_search_cv.fit(x_train_scaled, y_train, epochs=100,
             validation_data=(x_valid_scaled, y_valid),
             callbacks=callbacks)
  # 4.显示超参数
  print(random_search_cv.best_params_)
  print(random_search_cv.best_score_)
  print(random_search_cv.best_estimator_)

  model = random_search_cv.best_estimator_.model
  print(model.evaluate(x_test_scaled, y_test))

  # 5.打印模型训练过程
  plot_learning_curves(history)


if __name__ == '__main__':
  main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
在Python中编写数据库模块的教程
Apr 29 Python
python 计算文件的md5值实例
Jan 13 Python
Python绑定方法与非绑定方法详解
Aug 18 Python
python实现媒体播放器功能
Feb 11 Python
解决python os.mkdir创建目录失败的问题
Oct 16 Python
python可视化实现代码
Jan 15 Python
详解Python安装tesserocr遇到的各种问题及解决办法
Mar 07 Python
python启动应用程序和终止应用程序的方法
Jun 28 Python
解决Python图形界面中设置尺寸的问题
Mar 05 Python
Python reduce函数作用及实例解析
May 08 Python
Python操作Excel把数据分给sheet
May 20 Python
详解python算法常用技巧与内置库
Oct 17 Python
python numpy 矩阵堆叠实例
Jan 17 #Python
Python利用Scrapy框架爬取豆瓣电影示例
Jan 17 #Python
Python下利用BeautifulSoup解析HTML的实现
Jan 17 #Python
pytorch forward两个参数实例
Jan 17 #Python
Python实现CNN的多通道输入实例
Jan 17 #Python
Python面向对象编程基础实例分析
Jan 17 #Python
通过python实现windows桌面截图代码实例
Jan 17 #Python
You might like
PHP表单验证的3个函数ISSET()、empty()、is_numeric()的使用方法
2011/08/22 PHP
解析ajax事件的调用顺序
2013/06/17 PHP
php curl模拟post提交数据示例
2013/12/31 PHP
ThinkPHP使用smarty模板引擎的方法
2014/07/01 PHP
php使用PDO方法详解
2014/12/27 PHP
PHP 正则表达式小结
2015/02/12 PHP
php源码分析之DZX1.5字符串截断函数cutstr用法
2015/06/17 PHP
PHP防止图片盗用(盗链)的方法小结
2016/11/11 PHP
php把字符串指定字符分割成数组的方法
2018/03/12 PHP
javascript数字数组去重复项的实现代码
2010/12/30 Javascript
JS中Iframe之间传值的方法
2013/03/11 Javascript
js内存泄露的几种情况详细探讨
2013/05/31 Javascript
JavaScript中使用Substring删除字符串最后一个字符
2013/11/03 Javascript
简单的Jquery全选功能
2013/11/07 Javascript
js实现按钮加背景图片常用方法
2014/11/01 Javascript
Bootstrap每天必学之导航组件
2016/04/25 Javascript
jQuery Validate表单验证插件的基本使用方法及功能拓展
2017/01/04 Javascript
Node.js服务器开启Gzip压缩教程
2017/08/11 Javascript
JavaScript实现获取select下拉框中第一个值的方法
2018/02/06 Javascript
详解如何写出一个利于扩展的vue路由配置
2019/05/16 Javascript
vue实现一个获取按键展示快捷键效果的Input组件
2021/01/13 Vue.js
python检查指定文件是否存在的方法
2015/07/06 Python
CentOS中升级Python版本的方法详解
2017/07/10 Python
Python数据分析之如何利用pandas查询数据示例代码
2017/09/01 Python
python 多线程中子线程和主线程相互通信方法
2018/11/09 Python
python爬虫工具例举说明
2020/11/30 Python
解决pytorch下出现multi-target not supported at的一种可能原因
2021/02/06 Python
Skyscanner阿联酋:全球领先的旅游搜索平台
2017/11/25 全球购物
Bluebella德国官网:英国性感内衣和睡衣品牌
2019/11/08 全球购物
如何用Java判断一个文件或目录是否存在
2012/11/19 面试题
管理科学大学生求职信
2013/11/13 职场文书
技校生自我鉴定
2013/12/08 职场文书
聘任书的写作格式及范文
2014/03/29 职场文书
企业标语口号
2014/06/10 职场文书
大客户经理岗位职责
2015/04/09 职场文书
经典哲理警句:志不真则心不热,心不热则功不贤
2019/11/14 职场文书