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

pytorch如何使用訓練好的模型預測新數(shù)據(jù)

 更新時間:2023年06月15日 09:03:45   作者:Xiuxiu_Law  
這篇文章主要介紹了pytorch如何使用訓練好的模型預測新數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

pytorch使用訓練好的模型預測新數(shù)據(jù)

神經(jīng)網(wǎng)絡在進行完訓練和測試后,如果達到了較高的正確率的話,我們可以嘗試將模型用于預測新數(shù)據(jù)。

總共需要兩大部分:神經(jīng)網(wǎng)絡、預測函數(shù)(新圖片的加載,傳入模型、得出結果)。

完整代碼

import torch, glob, cv2
from torchvision import transforms
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):  # 神經(jīng)網(wǎng)絡部分用你自己的
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, 2, 1)  # nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
        self.conv2 = nn.Conv2d(32, 64, 3, 2, 1)
        self.conv3 = nn.Conv2d(64, 128, 3, 1)
        self.dropout1 = nn.Dropout2d(0.25)
        self.dropout2 = nn.Dropout2d(0.5)
        self.fc1 = nn.Linear(6272, 128)  # 6272=128*7*7
        self.fc2 = nn.Linear(128, 8)
    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = self.conv3(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        self.output = F.log_softmax(x, dim=1)
        out1 = x
        return self.output,out1
def predict():
    model = Net()
    model.load_state_dict(torch.load('test.pt'))
    torch.no_grad()
    imgfile = glob.glob(r"")  # 輸入要預測的圖片所在路徑
    print(len(imgfile), imgfile)
    for i in imgfile:
        imgfile1 = i.replace("\\", "/")
        img = cv2.imdecode(np.fromfile(imgfile1, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img, (64, 64))  # 是否需要resize取決于新圖片格式與訓練時的是否一致
        tran = transforms.ToTensor()
        img = img.reshape((*img.shape, -1))
        img = tran(img)
        img = img.unsqueeze(0)
        outputs, out1 = model(img)  # outputs,out1修改為你的網(wǎng)絡的輸出
        predicted, index  = torch.max(out1, 1)
        degre = int(index[0])
        list = [0, 45, -45, -90, 90, 135, -135, 180]
        print(predicted, list[degre])
if __name__ == '__main__':
    predict()

神經(jīng)網(wǎng)絡部分復制你在訓練時定義的神經(jīng)網(wǎng)絡即可,如果模型保存為字典,則需要

model.load_state_dict(torch.load('test.pt'))

新圖片的格式需要與訓練測試時的圖片格式保持一致,所以需要resize,如果新圖片為相同格式略過。

最后的list是你樣本類別的list,每一類的索引需要與label保持一致,例如:

list = ['褲子', '套衫', '連衣裙', '外套', '涼鞋', '襯衫', '運動鞋', '短靴']

結果分析

tensor([7.0595], grad_fn=<MaxBackward0>) 45
tensor([11.9538], grad_fn=<MaxBackward0>) -45
tensor([5.8450], grad_fn=<MaxBackward0>) 135

前面的張量tensor代表了各個類別的“概率”中最大的那一個,然后根據(jù)最大“概率”所在的位置(index)來找到list所對應的類別,然后輸出。

pytorch框架--簡單模型預測

模型預測示例

使用訓練好的模型進行預測

import torchvision
from model import Tudui
import torch
from PIL import Image
# 讀取圖像
img = Image.open("./data/train/Dog/9.jpg")
# 數(shù)據(jù)預處理
# 縮放
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)),
                                            torchvision.transforms.ToTensor()])
image = transform(img)
print(image.shape)
# 根據(jù)保存方式加載
model = torch.load("tudui_99.pth", map_location=torch.device('cpu'))
# 注意維度轉換,單張圖片
image1 = torch.reshape(image, (1, 3, 32, 32))
# 測試開關
model.eval()
# 節(jié)約性能
with torch.no_grad():
    output = model(image1)
print(output)
# print(output.argmax(1))
# 定義類別對應字典
dist = {0: "飛機", 1: "汽車", 2: "鳥", 3: "貓", 4: "鹿", 5: "狗", 6: "青蛙", 7: "馬", 8: "船", 9: "卡車"}
# 轉numpy格式,列表內取第一個
a = dist[output.argmax(1).numpy()[0]]
img.show()
print(a)

總結

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論

洪江市| 太原市| 同德县| 乐业县| 团风县| 南丰县| 当涂县| 阿拉尔市| 徐州市| 光泽县| 家居| 班玛县| 四子王旗| 景洪市| 苗栗市| 大英县| 边坝县| 凤庆县| 宁化县| 炉霍县| 兴化市| 浦县| 炉霍县| 南安市| 昌乐县| 泰州市| 太仓市| 古交市| 新疆| 武邑县| 湘潭市| 罗山县| 丰台区| 侯马市| 清涧县| 新津县| 武义县| 甘南县| 镶黄旗| 昌黎县| 皮山县|