最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解tensorflow之過擬合問題實戰(zhàn)

 更新時間:2020年11月01日 16:37:18   作者:逐夢er  
這篇文章主要介紹了詳解tensorflow之過擬合問題實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

過擬合問題實戰(zhàn)

1.構建數(shù)據(jù)集

我們使用的數(shù)據(jù)集樣本特性向量長度為 2,標簽為 0 或 1,分別代表了 2 種類別。借助于 scikit-learn 庫中提供的 make_moons 工具我們可以生成任意多數(shù)據(jù)的訓練集。

import matplotlib.pyplot as plt
# 導入數(shù)據(jù)集生成工具
import numpy as np
import seaborn as sns
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers, Sequential, regularizers
from mpl_toolkits.mplot3d import Axes3D

為了演示過擬合現(xiàn)象,我們只采樣了 1000 個樣本數(shù)據(jù),同時添加標準差為 0.25 的高斯噪聲數(shù)據(jù):

def load_dataset():
 # 采樣點數(shù)
 N_SAMPLES = 1000
 # 測試數(shù)量比率
 TEST_SIZE = None

 # 從 moon 分布中隨機采樣 1000 個點,并切分為訓練集-測試集
 X, y = make_moons(n_samples=N_SAMPLES, noise=0.25, random_state=100)
 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=TEST_SIZE, random_state=42)
 return X, y, X_train, X_test, y_train, y_test

make_plot 函數(shù)可以方便地根據(jù)樣本的坐標 X 和樣本的標簽 y 繪制出數(shù)據(jù)的分布圖:

def make_plot(X, y, plot_name, file_name, XX=None, YY=None, preds=None, dark=False, output_dir=OUTPUT_DIR):
 # 繪制數(shù)據(jù)集的分布, X 為 2D 坐標, y 為數(shù)據(jù)點的標簽
 if dark:
  plt.style.use('dark_background')
 else:
  sns.set_style("whitegrid")
 axes = plt.gca()
 axes.set_xlim([-2, 3])
 axes.set_ylim([-1.5, 2])
 axes.set(xlabel="$x_1$", ylabel="$x_2$")
 plt.title(plot_name, fontsize=20, fontproperties='SimHei')
 plt.subplots_adjust(left=0.20)
 plt.subplots_adjust(right=0.80)
 if XX is not None and YY is not None and preds is not None:
  plt.contourf(XX, YY, preds.reshape(XX.shape), 25, alpha=0.08, cmap=plt.cm.Spectral)
  plt.contour(XX, YY, preds.reshape(XX.shape), levels=[.5], cmap="Greys", vmin=0, vmax=.6)
 # 繪制散點圖,根據(jù)標簽區(qū)分顏色m=markers
 markers = ['o' if i == 1 else 's' for i in y.ravel()]
 mscatter(X[:, 0], X[:, 1], c=y.ravel(), s=20, cmap=plt.cm.Spectral, edgecolors='none', m=markers, ax=axes)
 # 保存矢量圖
 plt.savefig(output_dir + '/' + file_name)
 plt.close()
def mscatter(x, y, ax=None, m=None, **kw):
 import matplotlib.markers as mmarkers
 if not ax: ax = plt.gca()
 sc = ax.scatter(x, y, **kw)
 if (m is not None) and (len(m) == len(x)):
  paths = []
  for marker in m:
   if isinstance(marker, mmarkers.MarkerStyle):
    marker_obj = marker
   else:
    marker_obj = mmarkers.MarkerStyle(marker)
   path = marker_obj.get_path().transformed(
    marker_obj.get_transform())
   paths.append(path)
  sc.set_paths(paths)
 return sc
X, y, X_train, X_test, y_train, y_test = load_dataset()
make_plot(X,y,"haha",'月牙形狀二分類數(shù)據(jù)集分布.svg')

在這里插入圖片描述

2.網(wǎng)絡層數(shù)的影響

為了探討不同的網(wǎng)絡深度下的過擬合程度,我們共進行了 5 次訓練實驗。在𝑛 ∈ [0,4]時,構建網(wǎng)絡層數(shù)為n + 2層的全連接層網(wǎng)絡,并通過 Adam 優(yōu)化器訓練 500 個 Epoch

def network_layers_influence(X_train, y_train):
 # 構建 5 種不同層數(shù)的網(wǎng)絡
 for n in range(5):
  # 創(chuàng)建容器
  model = Sequential()
  # 創(chuàng)建第一層
  model.add(layers.Dense(8, input_dim=2, activation='relu'))
  # 添加 n 層,共 n+2 層
  for _ in range(n):
   model.add(layers.Dense(32, activation='relu'))
  # 創(chuàng)建最末層
  model.add(layers.Dense(1, activation='sigmoid'))
  # 模型裝配與訓練
  model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
  model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
  # 繪制不同層數(shù)的網(wǎng)絡決策邊界曲線
  # 可視化的 x 坐標范圍為[-2, 3]
  xx = np.arange(-2, 3, 0.01)
  # 可視化的 y 坐標范圍為[-1.5, 2]
  yy = np.arange(-1.5, 2, 0.01)
  # 生成 x-y 平面采樣網(wǎng)格點,方便可視化
  XX, YY = np.meshgrid(xx, yy)
  preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
  print(preds)
  title = "網(wǎng)絡層數(shù):{0}".format(2 + n)
  file = "網(wǎng)絡容量_%i.png" % (2 + n)
  make_plot(X_train, y_train, title, file, XX, YY, preds, output_dir=OUTPUT_DIR + '/network_layers')

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

3.Dropout的影響

為了探討 Dropout 層對網(wǎng)絡訓練的影響,我們共進行了 5 次實驗,每次實驗使用 7 層的全連接層網(wǎng)絡進行訓練,但是在全連接層中間隔插入 0~4 個 Dropout 層并通過 Adam優(yōu)化器訓練 500 個 Epoch

def dropout_influence(X_train, y_train):
 # 構建 5 種不同數(shù)量 Dropout 層的網(wǎng)絡
 for n in range(5):
  # 創(chuàng)建容器
  model = Sequential()
  # 創(chuàng)建第一層
  model.add(layers.Dense(8, input_dim=2, activation='relu'))
  counter = 0
  # 網(wǎng)絡層數(shù)固定為 5
  for _ in range(5):
   model.add(layers.Dense(64, activation='relu'))
  # 添加 n 個 Dropout 層
   if counter < n:
    counter += 1
    model.add(layers.Dropout(rate=0.5))

  # 輸出層
  model.add(layers.Dense(1, activation='sigmoid'))
  # 模型裝配
  model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
  # 訓練
  model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
  # 繪制不同 Dropout 層數(shù)的決策邊界曲線
  # 可視化的 x 坐標范圍為[-2, 3]
  xx = np.arange(-2, 3, 0.01)
  # 可視化的 y 坐標范圍為[-1.5, 2]
  yy = np.arange(-1.5, 2, 0.01)
  # 生成 x-y 平面采樣網(wǎng)格點,方便可視化
  XX, YY = np.meshgrid(xx, yy)
  preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
  title = "無Dropout層" if n == 0 else "{0}層 Dropout層".format(n)
  file = "Dropout_%i.png" % n
  make_plot(X_train, y_train, title, file, XX, YY, preds, output_dir=OUTPUT_DIR + '/dropout')

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

4.正則化的影響

為了探討正則化系數(shù)𝜆對網(wǎng)絡模型訓練的影響,我們采用 L2 正則化方式,構建了 5 層的神經(jīng)網(wǎng)絡,其中第 2,3,4 層神經(jīng)網(wǎng)絡層的權值張量 W 均添加 L2 正則化約束項:

def build_model_with_regularization(_lambda):
 # 創(chuàng)建帶正則化項的神經(jīng)網(wǎng)絡
 model = Sequential()
 model.add(layers.Dense(8, input_dim=2, activation='relu')) # 不帶正則化項
 # 2-4層均是帶 L2 正則化項
 model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(_lambda)))
 model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(_lambda)))
 model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(_lambda)))
 # 輸出層
 model.add(layers.Dense(1, activation='sigmoid'))
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # 模型裝配
 return model

下面我們首先來實現(xiàn)一個權重可視化的函數(shù)

def plot_weights_matrix(model, layer_index, plot_name, file_name, output_dir=OUTPUT_DIR):
 # 繪制權值范圍函數(shù)
 # 提取指定層的權值矩陣
 weights = model.layers[layer_index].get_weights()[0]
 shape = weights.shape
 # 生成和權值矩陣等大小的網(wǎng)格坐標
 X = np.array(range(shape[1]))
 Y = np.array(range(shape[0]))
 X, Y = np.meshgrid(X, Y)
 # 繪制3D圖
 fig = plt.figure()
 ax = fig.gca(projection='3d')
 ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
 ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
 ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
 plt.title(plot_name, fontsize=20, fontproperties='SimHei')
 # 繪制權值矩陣范圍
 ax.plot_surface(X, Y, weights, cmap=plt.get_cmap('rainbow'), linewidth=0)
 # 設置坐標軸名
 ax.set_xlabel('網(wǎng)格x坐標', fontsize=16, rotation=0, fontproperties='SimHei')
 ax.set_ylabel('網(wǎng)格y坐標', fontsize=16, rotation=0, fontproperties='SimHei')
 ax.set_zlabel('權值', fontsize=16, rotation=90, fontproperties='SimHei')
 # 保存矩陣范圍圖
 plt.savefig(output_dir + "/" + file_name + ".svg")
 plt.close(fig)

在保持網(wǎng)絡結(jié)構不變的條件下,我們通過調(diào)節(jié)正則化系數(shù) 𝜆 = 0.00001,0.001,0.1,0.12,0.13 來測試網(wǎng)絡的訓練效果,并繪制出學習模型在訓練集上的決策邊界曲線

def regularizers_influence(X_train, y_train):
 for _lambda in [1e-5, 1e-3, 1e-1, 0.12, 0.13]: # 設置不同的正則化系數(shù)
  # 創(chuàng)建帶正則化項的模型
  model = build_model_with_regularization(_lambda)
  # 模型訓練
  model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
  # 繪制權值范圍
  layer_index = 2
  plot_title = "正則化系數(shù):{}".format(_lambda)
  file_name = "正則化網(wǎng)絡權值_" + str(_lambda)
  # 繪制網(wǎng)絡權值范圍圖
  plot_weights_matrix(model, layer_index, plot_title, file_name, output_dir=OUTPUT_DIR + '/regularizers')
  # 繪制不同正則化系數(shù)的決策邊界線
  # 可視化的 x 坐標范圍為[-2, 3]
  xx = np.arange(-2, 3, 0.01)
  # 可視化的 y 坐標范圍為[-1.5, 2]
  yy = np.arange(-1.5, 2, 0.01)
  # 生成 x-y 平面采樣網(wǎng)格點,方便可視化
  XX, YY = np.meshgrid(xx, yy)
  preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
  title = "正則化系數(shù):{}".format(_lambda)
  file = "正則化_%g.svg" % _lambda
  make_plot(X_train, y_train, title, file, XX, YY, preds, output_dir=OUTPUT_DIR + '/regularizers')
regularizers_influence(X_train, y_train)

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

到此這篇關于詳解tensorflow之過擬合問題實戰(zhàn)的文章就介紹到這了,更多相關tensorflow 過擬合內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • django-rest-swagger對API接口注釋的方法

    django-rest-swagger對API接口注釋的方法

    今天小編就為大家分享一篇django-rest-swagger對API接口注釋的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • 關于jieba.cut與jieba.lcut的區(qū)別及說明

    關于jieba.cut與jieba.lcut的區(qū)別及說明

    這篇文章主要介紹了關于jieba.cut與jieba.lcut的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • Python中subprocess模塊的用法詳解

    Python中subprocess模塊的用法詳解

    這篇文章主要介紹了Python中subprocess模塊的用法詳解,subprocess是Python 2.4中新增的一個模塊,它允許你生成新的進程,連接到它們的 input/output/error 管道,并獲取它們的返回狀態(tài)碼,這個模塊的目的在于替換幾個舊的模塊和方法,需要的朋友可以參考下
    2023-08-08
  • 詳解Python自動化之文件自動化處理

    詳解Python自動化之文件自動化處理

    今天給大家?guī)淼氖顷P于Python的相關知識,文章圍繞著Python文件自動化處理展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • 基于SpringBoot構造器注入循環(huán)依賴及解決方式

    基于SpringBoot構造器注入循環(huán)依賴及解決方式

    這篇文章主要介紹了基于SpringBoot構造器注入循環(huán)依賴及解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • python數(shù)據(jù)分析數(shù)據(jù)標準化及離散化詳解

    python數(shù)據(jù)分析數(shù)據(jù)標準化及離散化詳解

    這篇文章主要為大家詳細介紹了python數(shù)據(jù)分析數(shù)據(jù)標準化及離散化,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-02-02
  • Python 發(fā)送SMTP郵件的簡單教程

    Python 發(fā)送SMTP郵件的簡單教程

    SMTP(Simple Mail Transfer Protocol)簡單郵件傳輸協(xié)議,Python內(nèi)置對SMTP的支持,可以發(fā)送純文本文件,HTML郵件以及附帶文件。本文講解如何使用python發(fā)送郵件
    2021-06-06
  • 詳解在OpenCV中如何使用圖像像素

    詳解在OpenCV中如何使用圖像像素

    像素是計算機視覺中圖像的重要屬性。它們是表示圖像中特定空間中光的顏色強度的數(shù)值,是圖像中數(shù)據(jù)的最小單位。本文將詳細為大家介紹如何在OpenCV中使用圖像像素,感興趣的可以了解一下
    2022-03-03
  • 如何使用PyCharm將代碼上傳到GitHub上(圖文詳解)

    如何使用PyCharm將代碼上傳到GitHub上(圖文詳解)

    這篇文章主要介紹了如何使用PyCharm將代碼上傳到GitHub上(圖文詳解),文中通過圖文介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-04-04
  • python中視頻音頻的剪輯與處理實現(xiàn)

    python中視頻音頻的剪輯與處理實現(xiàn)

    Python中輕松實現(xiàn)各種視頻處理操作,包括剪輯、合并、添加音頻、文本、特效等多種功能,主要介紹了python中視頻音頻的剪輯與處理實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2024-06-06

最新評論

新和县| 康马县| 北京市| 阳谷县| 昌平区| 抚顺市| 新巴尔虎右旗| 启东市| 文化| 巴林右旗| 拜泉县| 开阳县| 赞皇县| 汝州市| 仁寿县| 莱阳市| 渑池县| 林芝县| 大新县| 万宁市| 卢湾区| 平度市| 蒙阴县| 巨野县| 尼玛县| 花莲县| 兴仁县| 吴川市| 那坡县| 纳雍县| 江西省| 土默特左旗| 五指山市| 南丰县| 星子县| 长丰县| 化德县| 渝北区| 洪洞县| 黄陵县| 永仁县|