跳至頁尾內容
PYTHON 幫助

Keras Python(開發者使用指南)

Keras是一個功能強大、易於使用的 Python 函式庫,用於開發和評估深度學習模型。 Keras 模型最初由 François Chollet 開發,因其簡單易用和用戶友好的介面而廣受歡迎,使其成為機器學習領域初學者和專家的絕佳選擇。

此外,我們還將研究IronPDF PDF 生成庫,以及如何將這兩個庫結合起來以產生結果並將其匯出為 PDF。

Keras 的主要特點

1.用戶友好且模組化

Keras 的口號是"為人類設計的深度學習",其設計理念是易於使用、模組化和可擴展。 Keras 模型能夠提供清晰且可操作的錯誤回饋,這有助於開發者有效率地除錯和最佳化模型。

2.支援多種後端

Keras 可以運行在各種深度學習框架之上,例如 TensorFlow、Theano 和 Microsoft Cognitive Toolkit (CNTK)。 這種靈活性使開發人員能夠選擇最適合他們需求的後端。

3.對神經網路的廣泛支持

Keras 支援多種神經網路層,包括卷積層、循環層和全連接層。 它還為複雜的架構(如多輸入多輸出模型、層共享和模型共享)提供支援。

4.預處理工具

Keras 包含用於資料預處理的實用程序,例如圖像和文字處理,可簡化訓練模型的資料集準備。

5.模型可視化和調試工具

Keras 提供了用於視覺化神經網路結構和監控訓練過程的工具。 這對於理解模型的行為並進行必要的調整至關重要。 最簡單的模型類型是 Sequential Keras 模型,它只是一個簡單的線性堆疊的層。

安裝

安裝 Keras 非常簡單。 您可以使用 pip 安裝它:

pip install keras
pip install tensorflow
pip install keras
pip install tensorflow
SHELL

使用 Keras 建立一個簡單的神經網絡

以下是使用 Keras 建立簡單前饋神經網路的範例:

import keras
import numpy as np
import matplotlib.pyplot as plt

# Function to read UCR formatted data
def readucr(filename):
    """
    Reads a UCR format file and returns the features and labels.

    Args:
    filename (str): Path to the data file

    Returns:
    x, y: Features and labels as numpy arrays
    """
    data = np.loadtxt(filename, delimiter="\t")
    y = data[:, 0]
    x = data[:, 1:]
    return x, y.astype(int)

# Define the root URL for the dataset
root_url = "https://raw.githubusercontent.com/hfawaz/cd-diagram/master/FordA/"
x_train, y_train = readucr(root_url + "FordA_TRAIN.tsv")
x_test, y_test = readucr(root_url + "FordA_TEST.tsv")

# Get unique classes from the dataset
classes = np.unique(np.concatenate((y_train, y_test), axis=0))

# Plot an example from each class
plt.figure()
for c in classes:
    c_x_train = x_train[y_train == c]
    plt.plot(c_x_train[0], label="class " + str(c))
plt.legend(loc="best")
plt.show()
plt.close()
import keras
import numpy as np
import matplotlib.pyplot as plt

# Function to read UCR formatted data
def readucr(filename):
    """
    Reads a UCR format file and returns the features and labels.

    Args:
    filename (str): Path to the data file

    Returns:
    x, y: Features and labels as numpy arrays
    """
    data = np.loadtxt(filename, delimiter="\t")
    y = data[:, 0]
    x = data[:, 1:]
    return x, y.astype(int)

# Define the root URL for the dataset
root_url = "https://raw.githubusercontent.com/hfawaz/cd-diagram/master/FordA/"
x_train, y_train = readucr(root_url + "FordA_TRAIN.tsv")
x_test, y_test = readucr(root_url + "FordA_TEST.tsv")

# Get unique classes from the dataset
classes = np.unique(np.concatenate((y_train, y_test), axis=0))

# Plot an example from each class
plt.figure()
for c in classes:
    c_x_train = x_train[y_train == c]
    plt.plot(c_x_train[0], label="class " + str(c))
plt.legend(loc="best")
plt.show()
plt.close()
PYTHON

輸出

Keras Python(開發者使用指南):圖 1 - 輸出的神經網路模型

實際應用

1.影像分類

Keras廣泛應用於影像分類任務。 例如,使用 Keras 建構的捲積神經網路 (CNN) 可以實現對影像中物體的高精度辨識。

2.自然語言處理

Keras 提供用於建立能夠處理和理解人類語言的模型的工具。 Keras 中的循環神經網路 (RNN) 和長短期記憶 (LSTM) 網路通常用於情緒分析和機器翻譯等任務。

3.生成模型

Keras 可用於開發生成模型,例如生成對抗網路 (GAN),用於產生與訓練資料相似的新資料樣本。

IronPDF簡介

Keras Python(開發者使用指南):圖 2 - IronPDF for Python 網頁

IronPDF是由 Iron Software 開發和維護的強大的 Python 程式庫。 它允許開發人員在 Python 專案中創建、編輯和提取 PDF 內容。 以下是IronPDF的一些主要功能:

  1. PDF 生成:

    • 您可以從各種來源產生 PDF,包括 HTML、URL、JavaScript、CSS 和圖像格式。

    • 可為產生的 PDF 檔案新增頁首、頁尾、簽名、附件和安全功能。

2.性能優化:

* IronPDF 支援完全多執行緒和非同步操作。

3.跨平台相容性:

* 它適用於 Windows、macOS、Linux、Docker、Azure 和 AWS 上的 Python 3.7+。

首先,使用 pip 安裝 IronPDF:

pip install ironpdf
pip install ironpdf
SHELL

安裝完成後,您可以使用 HTML 內容或 URL 建立 PDF 檔案。 以下是一些例子:

  1. HTML 轉 PDF:
from ironpdf import ChromePdfRenderer

# Create a PDF renderer
renderer = ChromePdfRenderer()

# Render HTML content as a PDF
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
pdf.SaveAs("ironAwesome.pdf")
from ironpdf import ChromePdfRenderer

# Create a PDF renderer
renderer = ChromePdfRenderer()

# Render HTML content as a PDF
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
pdf.SaveAs("ironAwesome.pdf")
PYTHON
  1. PDF文件的URL:
from ironpdf import ChromePdfRenderer

# Create a PDF renderer
renderer = ChromePdfRenderer()

# Render a URL as a PDF
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/python/")
pdf.SaveAs("ironAwesome.pdf")
from ironpdf import ChromePdfRenderer

# Create a PDF renderer
renderer = ChromePdfRenderer()

# Render a URL as a PDF
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/python/")
pdf.SaveAs("ironAwesome.pdf")
PYTHON

IronPDF 和 Keras Python:生成模型的 PDF

安裝

pip install ironpdf
pip install keras
pip install tensorflow
pip install ironpdf
pip install keras
pip install tensorflow
SHELL

現在使用以下程式碼產生模型圖並將其匯出為 PDF 檔案:

import keras
import numpy as np
import matplotlib.pyplot as plt
from ironpdf import License, ImageToPdfConverter

# Apply your license key
License.LicenseKey = "your key goes here"

def readucr(filename):
    """Read and parse UCR formatted data."""
    data = np.loadtxt(filename, delimiter="\t")
    y = data[:, 0]
    x = data[:, 1:]
    return x, y.astype(int)

# Define the root URL for the dataset
root_url = "https://raw.githubusercontent.com/hfawaz/cd-diagram/master/FordA/"
x_train, y_train = readucr(root_url + "FordA_TRAIN.tsv")
x_test, y_test = readucr(root_url + "FordA_TEST.tsv")

# Extract unique classes from the dataset
classes = np.unique(np.concatenate((y_train, y_test), axis=0))

# Plot example data for each class
plt.figure()
for c in classes:
    c_x_train = x_train[y_train == c]
    plt.plot(c_x_train[0], label="class " + str(c))
plt.legend(loc="best")
plt.savefig('data.png') 
plt.show()
plt.close()

# Convert the saved image to a PDF
ImageToPdfConverter.ImageToPdf("data.png").SaveAs("plot.pdf")
import keras
import numpy as np
import matplotlib.pyplot as plt
from ironpdf import License, ImageToPdfConverter

# Apply your license key
License.LicenseKey = "your key goes here"

def readucr(filename):
    """Read and parse UCR formatted data."""
    data = np.loadtxt(filename, delimiter="\t")
    y = data[:, 0]
    x = data[:, 1:]
    return x, y.astype(int)

# Define the root URL for the dataset
root_url = "https://raw.githubusercontent.com/hfawaz/cd-diagram/master/FordA/"
x_train, y_train = readucr(root_url + "FordA_TRAIN.tsv")
x_test, y_test = readucr(root_url + "FordA_TEST.tsv")

# Extract unique classes from the dataset
classes = np.unique(np.concatenate((y_train, y_test), axis=0))

# Plot example data for each class
plt.figure()
for c in classes:
    c_x_train = x_train[y_train == c]
    plt.plot(c_x_train[0], label="class " + str(c))
plt.legend(loc="best")
plt.savefig('data.png') 
plt.show()
plt.close()

# Convert the saved image to a PDF
ImageToPdfConverter.ImageToPdf("data.png").SaveAs("plot.pdf")
PYTHON

程式碼解釋

1.導入庫:

* 程式碼首先導入必要的函式庫:
    * Keras:一個流行的深度學習庫。
    * numpy(作為 np):用於數值運算。
    * matplotlib.pyplot(作為 plt):用於建立圖表。
    * ironpdf:用於處理 PDF 的 IronPDF 庫。

2.設定許可證密鑰:

* `License.LicenseKey = &quot;your key&quot;`這行程式碼設定 IronPDF 的授權金鑰。

3.讀取資料:

* `readucr`函數從具有特定格式(製表符分隔值)的檔案中讀取資料。
它從資料中提取標籤(y)和特徵(x)。

4.載入訓練和測試資料:

* 程式碼為與"FordA"資料集相關的訓練和測試資料檔案建立 URL。
它使用`readucr`函數載入資料。

5.繪製數據圖:

* 此代碼用於識別資料集中的唯一類別。
* 對於每個類別,它選擇第一個實例( `c_x_train[0]` )並繪製它。
圖例表示類別標籤。

6.挽救劇情:

* 此圖表儲存為名為"data.png"的圖像檔案。

7.將影像轉換為 PDF:

* IronPDF 中的`ImageToPdfConverter`將已儲存的影像("data.png")轉換為 PDF 檔案("plot.pdf")。

輸出的PDF

Keras Python(開發者使用指南):圖 3 - 前一個程式碼輸出的 PDF 文件

IronPDF 許可

Keras Python(開發者使用指南):圖 4 - IronPDF for Python 許可頁面

如上面的程式碼所示, IronPDF需要許可證才能運作。 在腳本開頭按如下方式設定許可證密鑰:

# Apply your license key
License.LicenseKey = "your key goes here"
# Apply your license key
License.LicenseKey = "your key goes here"
PYTHON

如果您對 IronPDF 庫的試用許可證感興趣,可以從這裡取得試用許可證金鑰。

結論

Keras 人工智慧 Python 程式庫因其簡潔性和靈活性而在深度學習領域中脫穎而出。 它抽象化了建構神經網路所涉及的許多複雜性,使開發人員能夠專注於模型的設計和試驗。 無論你是剛開始接觸深度學習的初學者,還是經驗豐富的從業者,Keras 都能透過模擬人腦,為你提供將想法變成現實所需的工具。

另一方面,IronPDF 是一個功能強大的 PDF 生成和處理庫,可以輕鬆地將結果匯出為 PDF。 掌握這兩項技能將幫助使用者編寫現代資料科學模型,並將輸出結果匯出為 PDF 檔案以記錄結果。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。