在樹莓派上實現numpy的conv2d折積神經網路做影象分類,載入pytorch的模型引數,推理mnist手寫數位識別,並使用多程序加速

2023-05-30 21:00:38

這幾天又在玩樹莓派,先是搞了個物聯網,又在嘗試在樹莓派上搞一些簡單的神經網路,這次搞得是折積識別mnist手寫數位識別

訓練程式碼在電腦上,cpu就能訓練,很快的:

import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
import numpy as np

# 設定隨機種子
torch.manual_seed(42)

# 定義資料預處理
transform = transforms.Compose([
    transforms.ToTensor(),
    # transforms.Normalize((0.1307,), (0.3081,))
])

# 載入訓練資料集
train_dataset = datasets.MNIST('data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)

# 構建折積神經網路模型
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
        self.pool = nn.MaxPool2d(2)
        self.fc = nn.Linear(10 * 12 * 12, 10)

    def forward(self, x):
        x = self.pool(torch.relu(self.conv1(x)))
        x = x.view(-1, 10 * 12 * 12)
        x = self.fc(x)
        return x

model = Net()

# 定義損失函數和優化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

# 訓練模型
def train(model, device, train_loader, optimizer, criterion, epochs):
    model.train()
    for epoch in range(epochs):
        for batch_idx, (data, target) in enumerate(train_loader):
            data, target = data.to(device), target.to(device)
            optimizer.zero_grad()
            output = model(data)
            loss = criterion(output, target)
            loss.backward()
            optimizer.step()
            if batch_idx % 100 == 0:
                print(f'Train Epoch: {epoch+1} [{batch_idx * len(data)}/{len(train_loader.dataset)} '
                      f'({100. * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}')

# 在GPU上訓練(如果可用),否則使用CPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

# 訓練模型
train(model, device, train_loader, optimizer, criterion, epochs=5)

# 儲存模型為NumPy資料
model_state = model.state_dict()
numpy_model_state = {key: value.cpu().numpy() for key, value in model_state.items()}
np.savez('model.npz', **numpy_model_state)
print("Model saved as model.npz")

然後需要自己在dataset裡匯出一些圖片:我儲存在了mnist_pi資料夾下,「_」後面的是標籤,主要是在pc端匯出儲存到樹莓派下

 樹莓派推理端的程式碼,需要numpy手動重新搭建網路,並且需要手動實現conv2d折積神經網路和maxpool2d最大池化,然後載入那些儲存的矩陣引數,做矩陣乘法和加法

import numpy as np
import os
from PIL import Image

def conv2d(input, weight, bias, stride=1, padding=0):
    batch_size, in_channels, in_height, in_width = input.shape
    out_channels, in_channels, kernel_size, _ = weight.shape

    # 計算輸出特徵圖的大小
    out_height = (in_height + 2 * padding - kernel_size) // stride + 1
    out_width = (in_width + 2 * padding - kernel_size) // stride + 1

    # 新增padding
    padded_input = np.pad(input, ((0, 0), (0, 0), (padding, padding), (padding, padding)), mode='constant')

    # 初始化輸出特徵圖
    output = np.zeros((batch_size, out_channels, out_height, out_width))

    # 執行折積操作
    for b in range(batch_size):
        for c_out in range(out_channels):
            for h_out in range(out_height):
                for w_out in range(out_width):
                    h_start = h_out * stride
                    h_end = h_start + kernel_size
                    w_start = w_out * stride
                    w_end = w_start + kernel_size

                    # 提取對應位置的輸入影象區域
                    input_region = padded_input[b, :, h_start:h_end, w_start:w_end]

                    # 計算折積結果
                    x = input_region * weight[c_out]
                    bia = bias[c_out]
                    conv_result = np.sum(x, axis=(0,1, 2)) + bia

                    # 將折積結果儲存到輸出特徵圖中
                    output[b, c_out, h_out, w_out] = conv_result

    return output

def max_pool2d(input, kernel_size, stride=None, padding=0):
    batch_size, channels, in_height, in_width = input.shape

    if stride is None:
        stride = kernel_size

    out_height = (in_height - kernel_size + 2 * padding) // stride + 1
    out_width = (in_width - kernel_size + 2 * padding) // stride + 1

    padded_input = np.pad(input, ((0, 0), (0, 0), (padding, padding), (padding, padding)), mode='constant')

    output = np.zeros((batch_size, channels, out_height, out_width))

    for b in range(batch_size):
        for c in range(channels):
            for h_out in range(out_height):
                for w_out in range(out_width):
                    h_start = h_out * stride
                    h_end = h_start + kernel_size
                    w_start = w_out * stride
                    w_end = w_start + kernel_size

                    input_region = padded_input[b, c, h_start:h_end, w_start:w_end]

                    output[b, c, h_out, w_out] = np.max(input_region)

    return output


# 載入儲存的模型資料
model_data = np.load('model.npz')

# 提取模型引數
conv_weight = model_data['conv1.weight']
conv_bias = model_data['conv1.bias']
fc_weight = model_data['fc.weight']
fc_bias = model_data['fc.bias']

# 進行推理
def inference(images):
    # 執行折積操作
    conv_output = conv2d(images, conv_weight, conv_bias, stride=1, padding=0)
    conv_output = np.maximum(conv_output, 0)  # ReLU啟用函數
    #maxpool2d
    pool = max_pool2d(conv_output,2)
    # 執行全連線操作
    flattened = pool.reshape(pool.shape[0], -1)
    fc_output = np.dot(flattened, fc_weight.T) + fc_bias
    fc_output = np.maximum(fc_output, 0)  # ReLU啟用函數

    # 獲取預測結果
    predictions = np.argmax(fc_output, axis=1)

    return predictions


folder_path = './mnist_pi'  # 替換為圖片所在的資料夾路徑
def infer_images_in_folder(folder_path):
    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        if os.path.isfile(file_path) and file_name.endswith(('.jpg', '.jpeg', '.png')):
            image = Image.open(file_path)
            label = file_name.split(".")[0].split("_")[1]
            image = np.array(image)/255.0
            image = np.expand_dims(image,axis=0)
            image = np.expand_dims(image,axis=0)
            print("file_path:",file_path,"img size:",image.shape,"label:",label)
            predicted_class = inference(image)
            print('Predicted class:', predicted_class)

infer_images_in_folder(folder_path)

 

這程式碼完全就是numpy推理,不需要安裝pytorch,樹莓派也裝不動pytorch,太重了,下面是推理結果,比之前的MLP網路慢很多,主要是手動實現的折積網路全靠迴圈實現。

 那我們給它加加速吧,下面是一個多執行緒加速程式:

import numpy as np
import os
from PIL import Image
from multiprocessing import Pool

def conv2d(input, weight, bias, stride=1, padding=0):
    batch_size, in_channels, in_height, in_width = input.shape
    out_channels, in_channels, kernel_size, _ = weight.shape

    # 計算輸出特徵圖的大小
    out_height = (in_height + 2 * padding - kernel_size) // stride + 1
    out_width = (in_width + 2 * padding - kernel_size) // stride + 1

    # 新增padding
    padded_input = np.pad(input, ((0, 0), (0, 0), (padding, padding), (padding, padding)), mode='constant')

    # 初始化輸出特徵圖
    output = np.zeros((batch_size, out_channels, out_height, out_width))

    # 執行折積操作
    for b in range(batch_size):
        for c_out in range(out_channels):
            for h_out in range(out_height):
                for w_out in range(out_width):
                    h_start = h_out * stride
                    h_end = h_start + kernel_size
                    w_start = w_out * stride
                    w_end = w_start + kernel_size

                    # 提取對應位置的輸入影象區域
                    input_region = padded_input[b, :, h_start:h_end, w_start:w_end]

                    # 計算折積結果
                    x = input_region * weight[c_out]
                    bia = bias[c_out]
                    conv_result = np.sum(x, axis=(0,1, 2)) + bia

                    # 將折積結果儲存到輸出特徵圖中
                    output[b, c_out, h_out, w_out] = conv_result

    return output

def max_pool2d(input, kernel_size, stride=None, padding=0):
    batch_size, channels, in_height, in_width = input.shape

    if stride is None:
        stride = kernel_size

    out_height = (in_height - kernel_size + 2 * padding) // stride + 1
    out_width = (in_width - kernel_size + 2 * padding) // stride + 1

    padded_input = np.pad(input, ((0, 0), (0, 0), (padding, padding), (padding, padding)), mode='constant')

    output = np.zeros((batch_size, channels, out_height, out_width))

    for b in range(batch_size):
        for c in range(channels):
            for h_out in range(out_height):
                for w_out in range(out_width):
                    h_start = h_out * stride
                    h_end = h_start + kernel_size
                    w_start = w_out * stride
                    w_end = w_start + kernel_size

                    input_region = padded_input[b, c, h_start:h_end, w_start:w_end]

                    output[b, c, h_out, w_out] = np.max(input_region)

    return output

# 載入儲存的模型資料
model_data = np.load('model.npz')

# 提取模型引數
conv_weight = model_data['conv1.weight']
conv_bias = model_data['conv1.bias']
fc_weight = model_data['fc.weight']
fc_bias = model_data['fc.bias']

# 進行推理
def inference(images):
    # 執行折積操作
    conv_output = conv2d(images, conv_weight, conv_bias, stride=1, padding=0)
    conv_output = np.maximum(conv_output, 0)  # ReLU啟用函數
    # maxpool2d
    pool = max_pool2d(conv_output, 2)
    # 執行全連線操作
    flattened = pool.reshape(pool.shape[0], -1)
    fc_output = np.dot(flattened, fc_weight.T) + fc_bias
    fc_output = np.maximum(fc_output, 0)  # ReLU啟用函數

    # 獲取預測結果
    predictions = np.argmax(fc_output, axis=1)

    return predictions

labels = []
preds = []
def infer_image(file_path):
    image = Image.open(file_path)
    label = file_path.split("/")[-1].split(".")[0].split("_")[1]
    image = np.array(image) / 255.0
    image = np.expand_dims(image, axis=0)
    image = np.expand_dims(image, axis=0)
    print("file_path:", file_path, "img size:", image.shape, "label:", label)
    predicted_class = inference(image)
    print('Predicted class:', predicted_class)


folder_path = './mnist_pi'  # 替換為圖片所在的資料夾路徑
pool = Pool(processes=4)  # 設定程序數為2,可以根據需要進行調整

def infer_images_in_folder(folder_path):
    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        if os.path.isfile(file_path) and file_name.endswith(('.jpg', '.jpeg', '.png')):
            pool.apply_async(infer_image, args=(file_path,))

    pool.close()
    pool.join()


infer_images_in_folder(folder_path)

 

下圖可以看出來,我的樹莓派3b+,cpu直接拉滿,速度提升4倍: