如何使用 TensorFlow 實現邏輯迴歸函式?


TensorFlow 是 Google 提供的一個機器學習框架。它是一個開源框架,與 Python 結合使用,用於實現演算法、深度學習應用程式等等。它用於研究和生產目的。它具有最佳化技術,有助於快速執行復雜的數學運算。

可以使用以下程式碼行在 Windows 上安裝“tensorflow”包:

pip install tensorflow

張量是 TensorFlow 中使用的一種資料結構。它有助於連線流圖中的邊。此流圖稱為“資料流圖”。張量只不過是多維陣列或列表。它們可以使用三個主要屬性來識別

- 它告訴我們張量的維度。可以理解為張量的階數或已定義的張量中的維度數。

型別 - 它告訴我們與張量元素關聯的資料型別。它可以是一維、二維或 n 維張量。

形狀 - 它是行數和列數的總和。

我們使用 Google Colaboratory 來執行以下程式碼。Google Colab 或 Colaboratory 幫助透過瀏覽器執行 Python 程式碼,並且無需任何配置,並且可以免費訪問 GPU(圖形處理單元)。Colaboratory 建立在 Jupyter Notebook 之上。

以下是一個示例:

示例

def logistic_reg(x):
   return tf.nn.softmax(tf.matmul(x, A) + b)
def cross_entropy(y_pred, y_true):
   y_true = tf.one_hot(y_true, depth=num_classes)
   y_pred = tf.clip_by_value(y_pred, 1e-9, 1.)
   return tf.reduce_mean(-tf.reduce_sum(y_true * tf.math.log(y_pred),1))
def accuracy_val(y_pred, y_true):
   correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64))
   return tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
optimizer = tf.optimizers.SGD(learning_rate)
def run_optimization(x, y):
   with tf.GradientTape() as g:
      pred = logistic_reg(x)
      loss = cross_entropy(pred, y)
   gradients = g.gradient(loss, [A, b])
   optimizer.apply_gradients(zip(gradients, [A, b]))

程式碼來源 -  https://github.com/aymericdamien/TensorFlow-Examples/blob/master/tensorflow_v2/notebooks/2_BasicModels/logistic_regression.ipynb

輸出

Once the functions are called, the optimization process begins.
Here, we are using the stochastic gradient descent optimizer.
This means, the optimal values for the ‘weight’ and ‘bias’ are tried to be computed.
Once these gradients are computed, the ‘weight’ and ‘bias’ values are updated.

解釋

  • 定義了一個名為“logistic_reg”的函式,該函式給出輸入資料的 softmax 值。

  • 它將 logits 標準化為包含機率分佈。

  • 定義了交叉熵損失函式,它將標籤編碼為獨熱向量。

  • 預測值被格式化以減少 log(0) 錯誤。

  • 需要計算準確性指標,因此定義了一個函式。

  • 定義了隨機梯度下降最佳化器。

  • 定義了一個用於最佳化的函式,該函式計算梯度並更新權重和偏差的值。

更新於: 2021年1月19日

150 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.