OpenCV python sklearn隨機(jī)超參數(shù)搜索的實(shí)現(xiàn)
更新時(shí)間:2020年01月17日 09:46:42 作者:廷益--飛鳥
這篇文章主要介紹了OpenCV python sklearn隨機(jī)超參數(shù)搜索的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
本文介紹了OpenCV python sklearn隨機(jī)超參數(shù)搜索的實(shí)現(xiàn),分享給大家,具體如下:
"""
房價(jià)預(yù)測數(shù)據(jù)集 使用sklearn執(zhí)行超參數(shù)搜索
"""
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.打印導(dǎo)入模塊的版本
print(tf.__version__)
print(sys.version_info)
for module in mpl, np, sklearn, pd, tf, keras:
print("%s version:%s" % (module.__name__, module.__version__))
# 顯示學(xué)習(xí)曲線
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.加載數(shù)據(jù)集 california 房價(jià)
housing = fetch_california_housing()
print(housing.DESCR)
print(housing.data.shape)
print(housing.target.shape)
# 2.拆分?jǐn)?shù)據(jù)集 訓(xùn)練集 驗(yàn)證集 測試集
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.數(shù)據(jù)集歸一化
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)
# 創(chuàng)建keras模型
def build_model(hidden_layers=1, # 中間層的參數(shù)
layer_size=30,
learning_rate=3e-3):
# 創(chuàng)建網(wǎng)絡(luò)層
model = keras.models.Sequential()
model.add(keras.layers.Dense(layer_size, activation="relu",
input_shape=x_train.shape[1:]))
# 隱藏層設(shè)置
for _ in range(hidden_layers - 1):
model.add(keras.layers.Dense(layer_size,
activation="relu"))
model.add(keras.layers.Dense(1))
# 優(yōu)化器學(xué)習(xí)率
optimizer = keras.optimizers.SGD(lr=learning_rate)
model.compile(loss="mse", optimizer=optimizer)
return model
def main():
# RandomizedSearchCV
# 1.轉(zhuǎn)化為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.定義超參數(shù)集合
# 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.執(zhí)行超搜索參數(shù)
# cross_validation:訓(xùn)練集分成n份, n-1訓(xùn)練, 最后一份驗(yàn)證.
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.顯示超參數(shù)
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.打印模型訓(xùn)練過程
plot_learning_curves(history)
if __name__ == '__main__':
main()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- python numpy 常用隨機(jī)數(shù)的產(chǎn)生方法的實(shí)現(xiàn)
- numpy中生成隨機(jī)數(shù)的幾種常用函數(shù)(小結(jié))
- Sklearn調(diào)優(yōu)之網(wǎng)格搜索與隨機(jī)搜索原理詳細(xì)分析
- Numpy隨機(jī)抽樣的實(shí)現(xiàn)
- Numpy的np.random隨機(jī)模塊詳解
- Python?sklearn庫中的隨機(jī)森林模型詳解
- numpy中幾種隨機(jī)數(shù)生成函數(shù)的用法
- Numpy創(chuàng)建數(shù)組和隨機(jī)數(shù)組的方法小結(jié)
- Pandas+Numpy+Sklearn隨機(jī)取數(shù)的實(shí)現(xiàn)示例
相關(guān)文章
Python文件操作和數(shù)據(jù)格式詳解(簡單簡潔)
文本處理是腳本語言的強(qiáng)項(xiàng),下面這篇文章主要給大家介紹了關(guān)于Python文件操作和數(shù)據(jù)格式的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05
對python中 math模塊下 atan 和 atan2的區(qū)別詳解
今天小編就為大家分享一篇對python中 math模塊下 atan 和 atan2的區(qū)別詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python 標(biāo)準(zhǔn)庫原理與用法詳解之os.path篇
os.path模塊主要用于文件的屬性獲取,在編程中經(jīng)常用到,本文將帶你熟悉這個(gè)模塊并掌握它的用法,感興趣的朋友跟小編來看看吧2021-10-10
PyQt實(shí)現(xiàn)計(jì)數(shù)器的方法示例
這篇文章主要介紹了PyQt實(shí)現(xiàn)計(jì)數(shù)器的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
關(guān)于Python中定制類的比較運(yùn)算實(shí)例
今天小編就為大家分享一篇關(guān)于Python中定制類的比較運(yùn)算實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python WXPY實(shí)現(xiàn)微信監(jiān)控報(bào)警功能的代碼
本篇文章主要介紹了Python WXPY實(shí)現(xiàn)微信監(jiān)控報(bào)警功能的代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10

