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

基于Python實(shí)現(xiàn)的簡(jiǎn)單數(shù)字識(shí)別程序

 更新時(shí)間:2025年12月25日 08:54:51   作者:ufdf  
文章介紹了如何使用全連接神經(jīng)網(wǎng)絡(luò)(MLP)進(jìn)行MNIST數(shù)字識(shí)別,包括代碼模型定義、訓(xùn)練和測(cè)試的步驟,并解釋了模型權(quán)重保存文件的內(nèi)容,需要的朋友可以參考下

這里我們使用全連接神經(jīng)網(wǎng)絡(luò)(MLP) 實(shí)現(xiàn)的 MNIST 數(shù)字識(shí)別代碼,結(jié)構(gòu)更簡(jiǎn)單,僅包含幾個(gè)線性層和激活函數(shù)。

簡(jiǎn)易代碼

模型定義代碼,model.py

import torch.nn as nn

# 定義一個(gè)簡(jiǎn)單的 CNN 模型
class SimpleModel(nn.Module):
    def __init__(self):
        super(SimpleModel, self).__init__()
        self.flatten = nn.Flatten()
        self.fc1 = nn.Linear(28 * 28, 128)
        self.fc2 = nn.Linear(128, 64)
        self.fc3 = nn.Linear(64, 10)
        self.relu = nn.ReLU()
        self.dropout = nn.Dropout(0.2)

    def forward(self, x):
        x = self.flatten(x)  # [B, 1, 28, 28] -> [B, 784]
        x = self.relu(self.fc1(x))
        x = self.dropout(x)
        x = self.relu(self.fc2(x))
        x = self.dropout(x)
        x = self.fc3(x)  # 輸出層不加激活(CrossEntropyLoss 內(nèi)部含 softmax)
        return x

然后訓(xùn)練代碼,train.py

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from model import SimpleModel  # ?? 從 model.py 導(dǎo)入

# 配置
batch_size = 64
learning_rate = 0.001
num_epochs = 10
model_save_path = 'mnist_mlp.pth'

# 數(shù)據(jù)
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=transform, download=True)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)

# 模型、損失、優(yōu)化器
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = SimpleModel().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# 訓(xùn)練
print(f"Training on {device}...")
model.train()
for epoch in range(num_epochs):
    total_loss = 0.0
    for images, labels in train_loader:
        images, labels = images.to(device), labels.to(device)
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        total_loss += loss.item()
    print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {total_loss/len(train_loader):.4f}')

# 保存
torch.save(model.state_dict(), model_save_path)
print(f"? Model saved to {model_save_path}")

訓(xùn)練

在訓(xùn)練之前我們需要安裝下python依賴

pip install torch torchvision

然后我們就可以開(kāi)始訓(xùn)練模型啦!執(zhí)行命令python ./train.py,你會(huì)看到類似輸出

Training on cpu...
Epoch [1/10], Loss: 0.3501
Epoch [2/10], Loss: 0.1702
Epoch [3/10], Loss: 0.1335
Epoch [4/10], Loss: 0.1141
Epoch [5/10], Loss: 0.1027
Epoch [6/10], Loss: 0.0915
Epoch [7/10], Loss: 0.0884
Epoch [8/10], Loss: 0.0801
Epoch [9/10], Loss: 0.0769
Epoch [10/10], Loss: 0.0715
? Model saved to mnist_mlp.pth

目錄下會(huì)生成一個(gè)mnist_mlp.pthmnist_mlp.pth 是一個(gè) PyTorch 模型權(quán)重保存文件,本質(zhì)上是一個(gè) 序列化后的字典(state_dict),存儲(chǔ)了神經(jīng)網(wǎng)絡(luò)中所有可學(xué)習(xí)參數(shù)(如權(quán)重和偏置)的數(shù)值。

測(cè)試模型

現(xiàn)在我們拿我們的模型去試試我們的數(shù)字圖片了~
predict.py

# predict.py
import torch
import torchvision.transforms as transforms
from PIL import Image
from model import SimpleModel
import argparse
import os

def predict_image(image_path, model_path='mnist_mlp.pth', device='cpu'):
    # 1. 加載模型
    model = SimpleModel()
    model.load_state_dict(torch.load(model_path, map_location=device))
    model.eval()  # 推理模式

    # 2. 圖像預(yù)處理(必須和訓(xùn)練時(shí)一致!)
    transform = transforms.Compose([
        transforms.Grayscale(num_output_channels=1),  # 轉(zhuǎn)灰度
        transforms.Resize((28, 28)),                   # 調(diào)整為 28x28
        transforms.ToTensor(),                         # 轉(zhuǎn)為 Tensor [0,1]
        transforms.Normalize((0.1307,), (0.3081,))    # 用 MNIST 的均值/標(biāo)準(zhǔn)差
    ])

    # 3. 加載并預(yù)處理圖像
    image = Image.open(image_path).convert('L')  # 強(qiáng)制灰度(兼容 RGB 輸入)
    input_tensor = transform(image)              # shape: [1, 28, 28]
    input_batch = input_tensor.unsqueeze(0)      # 增加 batch 維度 → [1, 1, 28, 28]

    # 4. 推理
    with torch.no_grad():
        output = model(input_batch)
        probabilities = torch.softmax(output, dim=1)
        predicted_class = torch.argmax(probabilities, dim=1).item()
        confidence = probabilities[0][predicted_class].item()

    return predicted_class, confidence

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Predict digit in an image using trained MLP')
    parser.add_argument('image_path', type=str, help='Path to the input image (e.g., digit.png)')
    args = parser.parse_args()

    if not os.path.exists(args.image_path):
        print(f"? Error: Image file '{args.image_path}' not found!")
        exit(1)

    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    digit, conf = predict_image(args.image_path, device=device)

    print(f"? Predicted digit: {digit}")
    print(f"?? Confidence: {conf:.4f} ({conf*100:.2f}%)")

我們可以python .\predict.py .\data\digit.png來(lái)看看預(yù)測(cè)的結(jié)果如何。

到此這篇關(guān)于基于Python實(shí)現(xiàn)的簡(jiǎn)單數(shù)字識(shí)別程序的文章就介紹到這了,更多相關(guān)Python數(shù)字識(shí)別程序內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python拋出引發(fā)異常(raise)知識(shí)點(diǎn)總結(jié)

    Python拋出引發(fā)異常(raise)知識(shí)點(diǎn)總結(jié)

    在本篇文章里小編給大家整理了關(guān)于Python拋出引發(fā)異常(raise)知識(shí)點(diǎn)總結(jié)內(nèi)容,有需要的朋友們可以學(xué)習(xí)參考下。
    2021-06-06
  • Python streamlit庫(kù)快速構(gòu)建交互式Web應(yīng)用

    Python streamlit庫(kù)快速構(gòu)建交互式Web應(yīng)用

    Streamlit 是一個(gè)專為數(shù)據(jù)科學(xué)家和機(jī)器學(xué)習(xí)工程師設(shè)計(jì)的Python庫(kù),它可以快速構(gòu)建交互式Web應(yīng)用,下面就來(lái)詳細(xì)的介紹一下streamlit庫(kù)的使用,感興趣的可以了解一下
    2025-12-12
  • 手把手教你Python yLab的繪制折線圖的畫法

    手把手教你Python yLab的繪制折線圖的畫法

    這篇文章主要介紹了手把手教你Python yLab的繪制折線圖的畫法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • pandas DataFrame 根據(jù)多列的值做判斷,生成新的列值實(shí)例

    pandas DataFrame 根據(jù)多列的值做判斷,生成新的列值實(shí)例

    今天小編就為大家分享一篇pandas DataFrame 根據(jù)多列的值做判斷,生成新的列值實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05
  • Python入門教程(二十三)Python的繼承

    Python入門教程(二十三)Python的繼承

    這篇文章主要介紹了Python入門教程(二十三)Python的繼承,Python是一門非常強(qiáng)大好用的語(yǔ)言,也有著易上手的特性,本文為入門教程,需要的朋友可以參考下
    2023-04-04
  • 淺談Python3中打開(kāi)文件的方式(With open)

    淺談Python3中打開(kāi)文件的方式(With open)

    本文主要介紹了淺談Python3中打開(kāi)文件的方式(With open),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • 詳解Python中的四種隊(duì)列

    詳解Python中的四種隊(duì)列

    隊(duì)列是一種只允許在一端進(jìn)行插入操作,而在另一端進(jìn)行刪除操作的線性表。這篇文章主要介紹了Python中的四種隊(duì)列,需要的朋友可以參考下
    2018-05-05
  • PyQt轉(zhuǎn)換路徑中的斜杠(斜杠(/)與反斜杠(\)轉(zhuǎn)換)

    PyQt轉(zhuǎn)換路徑中的斜杠(斜杠(/)與反斜杠(\)轉(zhuǎn)換)

    本文主要介紹了PyQt轉(zhuǎn)換路徑中的斜杠(斜杠(/)與反斜杠(\)轉(zhuǎn)換),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • 超全面python常見(jiàn)報(bào)錯(cuò)以及解決方案梳理必收藏

    超全面python常見(jiàn)報(bào)錯(cuò)以及解決方案梳理必收藏

    使用python難免會(huì)出現(xiàn)各種各樣的報(bào)錯(cuò),以下是Python常見(jiàn)的報(bào)錯(cuò)以及解決方法(持續(xù)更新),快進(jìn)入收藏吃灰吧
    2022-03-03
  • 基于Python實(shí)現(xiàn)溫度單位轉(zhuǎn)換器(新手版)

    基于Python實(shí)現(xiàn)溫度單位轉(zhuǎn)換器(新手版)

    這篇文章主要為大家詳細(xì)介紹了如何基于Python實(shí)現(xiàn)溫度單位轉(zhuǎn)換器,主要是將攝氏溫度(C)和華氏溫度(F)相互轉(zhuǎn)換,下面小編就來(lái)和大家簡(jiǎn)單介紹一下吧
    2025-08-08

最新評(píng)論

德清县| 昌都县| 镇赉县| 鹤庆县| 奉新县| 萨迦县| 梧州市| 石屏县| 靖江市| 津南区| 象山县| 新丰县| 贡嘎县| 潼南县| 延吉市| 太康县| 同心县| 象州县| 河北区| 金华市| 隆德县| 东台市| 曲麻莱县| 馆陶县| 青田县| 通山县| 高雄市| 阿克苏市| 安平县| 易门县| 元阳县| 轮台县| 房产| 建瓯市| 柳林县| 营口市| 修武县| 独山县| 藁城市| 石泉县| 望都县|