討論如何使用 Python 中的 Keras 函式式 API 建立層
Tensorflow 是 Google 提供的一個機器學習框架。它是一個開源框架,與 Python 結合使用以實現演算法、深度學習應用程式等等。它用於研究和生產目的。它具有最佳化技術,有助於快速執行復雜的數學運算。
可以使用以下程式碼行在 Windows 上安裝“tensorflow”包:
pip install tensorflow
Keras 在希臘語中意為“角”。Keras 是作為 ONEIROS(開放式神經電子智慧機器人作業系統)專案研究的一部分開發的。Keras 是一個用 Python 編寫的深度學習 API。它是一個高階 API,具有高效的介面,有助於解決機器學習問題。它執行在 Tensorflow 框架之上。它是為了幫助快速進行實驗而構建的。它提供了開發和封裝機器學習解決方案所需的必要抽象和構建塊。
Keras 已經存在於 Tensorflow 包中。可以使用以下程式碼行訪問它。
import tensorflow from tensorflow import keras
Keras 函式式 API 有助於建立比使用順序 API 建立的模型更靈活的模型。函式式 API 可以處理具有非線性拓撲的模型,可以共享層,並處理多個輸入和輸出。深度學習模型通常是一個包含多個層的 有向無環圖 (DAG)。函式式 API 有助於構建圖層圖。
我們正在使用 Google Colaboratory 來執行以下程式碼。Google Colab 或 Colaboratory 有助於在瀏覽器上執行 Python 程式碼,並且無需任何配置即可免費訪問 GPU(圖形處理單元)。Colaboratory 是構建在 Jupyter Notebook 之上的。以下是程式碼片段,其中我們將看到如何使用 Keras 函式式 API 使用 Python 建立層:
示例
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers inputs = keras.Input(shape=(784,)) print("Demonstration") img_inputs = keras.Input(shape=(32, 32, 3)) print("Dimensions of input") print(inputs.shape) print("The type of input") print(inputs.dtype) print("Layers in the model") dense = layers.Dense(64, activation="relu") x = dense(inputs) x = layers.Dense(64, activation="relu")(x) outputs = layers.Dense(10)(x) print("Model is being built") model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model") print("More information about the model") model.summary()
程式碼來源 - https://www.tensorflow.org/guide/keras/functional
輸出
解釋
建立一個輸入節點,並將資料形狀設定為 784 維向量。
返回的輸入包含有關先前饋送到模型的輸入資料的“形狀”和“資料型別”的資訊。
透過指定輸入和輸出建立模型。