探索TensorFlow Probability:使用概率編程實現深度學習

一、TensorFlow Probability 簡介

TensorFlow Probability 是通過概率編程實現深度學習的開源庫。

在傳統深度學習中,模型參數通常是確定性或固定的。但是,在模型和訓練數據不充分或存在噪聲時,也許最佳參數的不確定性就會開始出現問題。此時,傳統深度學習模型會將噪聲視為訓練集的一部分,但是概率編程可以處理這種不確定性並將其視為噪聲源作為輸入。

TensorFlow Probability 建立在 TensorFlow 的基礎上,並使用可微分正則概率分布表示神經網絡的權重和偏差。

二、概率編程的基本思想

概率編程可以看作是一種建立在概率理論基礎上的編程範式。通過概率編程,開發者可以使用概率建模和推斷進行靈活計算,能夠處理如下問題:

1、在有限的數據集上推斷參數

2、解決樣本規模很小的問題

3、處理缺失數據集

4、在觀測到有限數據時提高模型的不確定性

三、TensorFlow Probability 實現深度學習的方法

1、使用正則化的分布建議網絡的權重

import tensorflow as tf
import tensorflow_probability as tfp

model = tf.keras.Sequential([
  tf.keras.layers.Dense(
      10, activation=tf.nn.relu, input_shape=(n_features,)),
  # Apply the L2 regularization with a factor of 1/lambda
  tfp.layers.DenseVariational(
      1, posterior_mean_field, prior_trainable),  # input_shape=(10,)
])

2、將權重和偏差使用正則化的分布建議

def build_normal_predictive_distribution(layer):
  """Create the predictive distribution of a layer output."""
  def normal_predictive_distribution(distribution):
    """Create the predictive distribution of a distribution."""
    return tfp.distributions.Normal(distribution.mean(), distribution.stddev())
  return tfp.layers.DistributionLambda(
      make_distribution_fn=normal_predictive_distribution,
      convert_to_tensor_fn=tfp.distributions.Distribution.sample,
      name=f'{layer.name}_distribution')

model = tf.keras.Sequential([
  tfp.layers.DenseVariational(
      10,
      posterior_mean_field,
      prior_trainable,
      activation=tf.nn.relu,
      input_shape=(n_features,),
      ),
  build_normal_predictive_distribution(model.layers[-1]),
  tfp.layers.DistributionLambda(
      make_distribution_fn=lambda t: tfp.distributions.Normal(
          t, scale=1),
      name='y_distribution'),
])

3、使用可微分概率分布進行推斷

model.compile(
    optimizer=tf.optimizers.Adam(lr=learning_rate),
    loss=neg_log_likelihood,
    metrics=[neg_log_likelihood, accuracy])

history = model.fit(
    x_train,
    y_train,
    batch_size=batch_size,
    epochs=n_epochs,
    validation_data=(x_test, y_test),
    verbose=0)

四、TensorFlow Probability 實現深度學習的實例

下面的代碼實現了在 MNIST 數據集上對手寫數字進行分類的概率編程方法——使用 CNN(MLP) + dropout-MLP 模型。

import tensorflow as tf
import tensorflow_probability as tfp
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split

tfd = tfp.distributions

# Load data
X, y = fetch_openml('mnist_784', version=1, return_X_y=True)
X, y = X[:5000, ...].astype('float32'), y[:5000]
X /= 255.
y = y.astype('int32')

x_train, x_test, y_train, y_test = train_test_split(X, y, train_size=0.8, random_state=42)

n_samples = 50
n_epochs = 100
batch_size = 128
n_features = x_train.shape[-1]
n_classes = 10

def convolutional_input_encoder(x, input_shape):
  """Pre-process the inputs of the convolutional encoder."""
  x = tf.reshape(x, [-1] + list(input_shape) + [1])
  return x

def convolutional_output_decoder(x):
  """Re-format and flatten the outputs of the convolutional decoder."""
  _, h, w, c = x.shape.as_list()

  x = tf.reshape(x, [-1, h*w*c])
  return x

model = tf.keras.Sequential([
  tf.keras.layers.Lambda(
      lambda x: convolutional_input_encoder(
          x, input_shape=(28, 28)),
      input_shape=(28, 28)),
  tf.keras.layers.Conv2D(
      32, [5, 5], strides=[1, 1],
      padding='same', activation=tf.nn.relu),
  tf.keras.layers.MaxPooling2D(
      pool_size=[2, 2], strides=[2, 2],
      padding='same'),
  tf.keras.layers.Conv2D(
      64, [5, 5], strides=[1, 1],
      padding='same', activation=tf.nn.relu),
  tf.keras.layers.MaxPooling2D(
      pool_size=[2, 2], strides=[2, 2],
      padding='same'),
  tf.keras.layers.Lambda(
      lambda x: convolutional_output_decoder(x)),
  tfp.layers.DenseFlipout(
      256, activation=tf.nn.relu),
  tf.keras.layers.Dropout(0.5),
  tfp.layers.DenseFlipout(
      10),
  tfp.layers.DistributionLambda(
      lambda t: tfd.Categorical(logits=t),
      name='y_dist')
])

def neg_log_likelihood(y_true, y_pred):
    return -tf.reduce_mean(y_pred.log_prob(tf.squeeze(y_true)))

model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.001), loss=neg_log_likelihood)

history = model.fit(
    x_train, y_train,
    batch_size=batch_size,
    epochs=n_epochs,
    verbose=0,
    validation_data=(x_test, y_test))

_, test_acc = model.evaluate(x_test, y_test, verbose=0)
print(f'Test accuracy: {test_acc:.4f}')

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/195640.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-02 20:36
下一篇 2024-12-02 20:36

相關推薦

  • TensorFlow Serving Java:實現開發全功能的模型服務

    TensorFlow Serving Java是作為TensorFlow Serving的Java API,可以輕鬆地將基於TensorFlow模型的服務集成到Java應用程序中。…

    編程 2025-04-29
  • 深度查詢宴會的文化起源

    深度查詢宴會,是指通過對一種文化或主題的深度挖掘和探究,為參與者提供一次全方位的、深度體驗式的文化品嘗和交流活動。本文將從多個方面探討深度查詢宴會的文化起源。 一、宴會文化的起源 …

    編程 2025-04-29
  • TensorFlow和Python的區別

    TensorFlow和Python是現如今最受歡迎的機器學習平台和編程語言。雖然兩者都處於機器學習領域的主流陣營,但它們有很多區別。本文將從多個方面對TensorFlow和Pyth…

    編程 2025-04-28
  • Python下載深度解析

    Python作為一種強大的編程語言,在各種應用場景中都得到了廣泛的應用。Python的安裝和下載是使用Python的第一步,對這個過程的深入了解和掌握能夠為使用Python提供更加…

    編程 2025-04-28
  • Python遞歸深度用法介紹

    Python中的遞歸函數是一個函數調用自身的過程。在進行遞歸調用時,程序需要為每個函數調用開闢一定的內存空間,這就是遞歸深度的概念。本文將從多個方面對Python遞歸深度進行詳細闡…

    編程 2025-04-27
  • Spring Boot本地類和Jar包類加載順序深度剖析

    本文將從多個方面對Spring Boot本地類和Jar包類加載順序做詳細的闡述,並給出相應的代碼示例。 一、類加載機制概述 在介紹Spring Boot本地類和Jar包類加載順序之…

    編程 2025-04-27
  • 深度解析Unity InjectFix

    Unity InjectFix是一個非常強大的工具,可以用於在Unity中修復各種類型的程序中的問題。 一、安裝和使用Unity InjectFix 您可以通過Unity Asse…

    編程 2025-04-27
  • 深度剖析:cmd pip不是內部或外部命令

    一、問題背景 使用Python開發時,我們經常需要使用pip安裝第三方庫來實現項目需求。然而,在執行pip install命令時,有時會遇到“pip不是內部或外部命令”的錯誤提示,…

    編程 2025-04-25
  • 動手學深度學習 PyTorch

    一、基本介紹 深度學習是對人工神經網絡的發展與應用。在人工神經網絡中,神經元通過接受輸入來生成輸出。深度學習通常使用很多層神經元來構建模型,這樣可以處理更加複雜的問題。PyTorc…

    編程 2025-04-25
  • 深度解析Ant Design中Table組件的使用

    一、Antd表格兼容 Antd是一個基於React的UI框架,Table組件是其重要的組成部分之一。該組件可在各種瀏覽器和設備上進行良好的兼容。同時,它還提供了多個版本的Antd框…

    編程 2025-04-25

發表回復

登錄後才能評論