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

詳解tensorflow之過(guò)擬合問(wèn)題實(shí)戰(zhàn)

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

過(guò)擬合問(wèn)題實(shí)戰(zhàn)

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

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

import matplotlib.pyplot as plt
# 導(dǎo)入數(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

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

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

 # 從 moon 分布中隨機(jī)采樣 1000 個(gè)點(diǎn),并切分為訓(xùn)練集-測(cè)試集
 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ù)樣本的坐標(biāo) X 和樣本的標(biāo)簽 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 坐標(biāo), y 為數(shù)據(jù)點(diǎn)的標(biāo)簽
 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)
 # 繪制散點(diǎn)圖,根據(jù)標(biāo)簽區(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)絡(luò)層數(shù)的影響

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

def network_layers_influence(X_train, y_train):
 # 構(gòu)建 5 種不同層數(shù)的網(wǎng)絡(luò)
 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'))
  # 模型裝配與訓(xùn)練
  model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
  model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
  # 繪制不同層數(shù)的網(wǎng)絡(luò)決策邊界曲線
  # 可視化的 x 坐標(biāo)范圍為[-2, 3]
  xx = np.arange(-2, 3, 0.01)
  # 可視化的 y 坐標(biāo)范圍為[-1.5, 2]
  yy = np.arange(-1.5, 2, 0.01)
  # 生成 x-y 平面采樣網(wǎng)格點(diǎn),方便可視化
  XX, YY = np.meshgrid(xx, yy)
  preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
  print(preds)
  title = "網(wǎng)絡(luò)層數(shù):{0}".format(2 + n)
  file = "網(wǎng)絡(luò)容量_%i.png" % (2 + n)
  make_plot(X_train, y_train, title, file, XX, YY, preds, output_dir=OUTPUT_DIR + '/network_layers')

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

3.Dropout的影響

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

def dropout_influence(X_train, y_train):
 # 構(gòu)建 5 種不同數(shù)量 Dropout 層的網(wǎng)絡(luò)
 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)絡(luò)層數(shù)固定為 5
  for _ in range(5):
   model.add(layers.Dense(64, activation='relu'))
  # 添加 n 個(gè) 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'])
  # 訓(xùn)練
  model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
  # 繪制不同 Dropout 層數(shù)的決策邊界曲線
  # 可視化的 x 坐標(biāo)范圍為[-2, 3]
  xx = np.arange(-2, 3, 0.01)
  # 可視化的 y 坐標(biāo)范圍為[-1.5, 2]
  yy = np.arange(-1.5, 2, 0.01)
  # 生成 x-y 平面采樣網(wǎng)格點(diǎn),方便可視化
  XX, YY = np.meshgrid(xx, yy)
  preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
  title = "無(wú)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ù)𝜆對(duì)網(wǎng)絡(luò)模型訓(xùn)練的影響,我們采用 L2 正則化方式,構(gòu)建了 5 層的神經(jīng)網(wǎng)絡(luò),其中第 2,3,4 層神經(jīng)網(wǎng)絡(luò)層的權(quán)值張量 W 均添加 L2 正則化約束項(xiàng):

def build_model_with_regularization(_lambda):
 # 創(chuàng)建帶正則化項(xiàng)的神經(jīng)網(wǎng)絡(luò)
 model = Sequential()
 model.add(layers.Dense(8, input_dim=2, activation='relu')) # 不帶正則化項(xiàng)
 # 2-4層均是帶 L2 正則化項(xiàng)
 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

下面我們首先來(lái)實(shí)現(xiàn)一個(gè)權(quán)重可視化的函數(shù)

def plot_weights_matrix(model, layer_index, plot_name, file_name, output_dir=OUTPUT_DIR):
 # 繪制權(quán)值范圍函數(shù)
 # 提取指定層的權(quán)值矩陣
 weights = model.layers[layer_index].get_weights()[0]
 shape = weights.shape
 # 生成和權(quán)值矩陣等大小的網(wǎng)格坐標(biāo)
 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')
 # 繪制權(quán)值矩陣范圍
 ax.plot_surface(X, Y, weights, cmap=plt.get_cmap('rainbow'), linewidth=0)
 # 設(shè)置坐標(biāo)軸名
 ax.set_xlabel('網(wǎng)格x坐標(biāo)', fontsize=16, rotation=0, fontproperties='SimHei')
 ax.set_ylabel('網(wǎng)格y坐標(biāo)', fontsize=16, rotation=0, fontproperties='SimHei')
 ax.set_zlabel('權(quán)值', fontsize=16, rotation=90, fontproperties='SimHei')
 # 保存矩陣范圍圖
 plt.savefig(output_dir + "/" + file_name + ".svg")
 plt.close(fig)

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

def regularizers_influence(X_train, y_train):
 for _lambda in [1e-5, 1e-3, 1e-1, 0.12, 0.13]: # 設(shè)置不同的正則化系數(shù)
  # 創(chuàng)建帶正則化項(xiàng)的模型
  model = build_model_with_regularization(_lambda)
  # 模型訓(xùn)練
  model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
  # 繪制權(quán)值范圍
  layer_index = 2
  plot_title = "正則化系數(shù):{}".format(_lambda)
  file_name = "正則化網(wǎng)絡(luò)權(quán)值_" + str(_lambda)
  # 繪制網(wǎng)絡(luò)權(quán)值范圍圖
  plot_weights_matrix(model, layer_index, plot_title, file_name, output_dir=OUTPUT_DIR + '/regularizers')
  # 繪制不同正則化系數(shù)的決策邊界線
  # 可視化的 x 坐標(biāo)范圍為[-2, 3]
  xx = np.arange(-2, 3, 0.01)
  # 可視化的 y 坐標(biāo)范圍為[-1.5, 2]
  yy = np.arange(-1.5, 2, 0.01)
  # 生成 x-y 平面采樣網(wǎng)格點(diǎn),方便可視化
  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)

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

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

相關(guān)文章

  • django-rest-swagger對(duì)API接口注釋的方法

    django-rest-swagger對(duì)API接口注釋的方法

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

    關(guān)于jieba.cut與jieba.lcut的區(qū)別及說(shuō)明

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

    Python中subprocess模塊的用法詳解

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

    詳解Python自動(dòng)化之文件自動(dòng)化處理

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

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

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

    python數(shù)據(jù)分析數(shù)據(jù)標(biāo)準(zhǔn)化及離散化詳解

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

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

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

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

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

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

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

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

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

最新評(píng)論

阿城市| 泽普县| 永修县| 赤水市| 喀喇沁旗| 凤山市| 安远县| 阿拉善盟| 通许县| 北安市| 南昌县| 根河市| 千阳县| 郧西县| 西充县| 九江市| 二连浩特市| 平果县| 丹江口市| 云阳县| 集贤县| 清镇市| 专栏| 西充县| 大宁县| 天全县| 简阳市| 旬邑县| 深水埗区| 威信县| 彩票| 秦皇岛市| 潼南县| 宣汉县| 宜都市| 行唐县| 洞头县| 康平县| 鸡泽县| 陇西县| 昌平区|