#报错内容
C:\Users\ASUS\.conda\envs\mindspore\python.exe C:\PycharmProjects\pythonProject1\venv\CIFAR_10_jiangjie\main.py
Traceback (most recent call last):
File "C:\PycharmProjects\pythonProject1\venv\CIFAR_10_jiangjie\main.py", line 1, in <module>
import torchvision
File "C:\Users\ASUS\.conda\envs\mindspore\lib\site-packages\torchvision\__init__.py", line 5, in <module>
from torchvision import datasets
File "C:\Users\ASUS\.conda\envs\mindspore\lib\site-packages\torchvision\datasets\__init__.py", line 1, in <module>
from ._optical_flow import KittiFlow, Sintel, FlyingChairs, FlyingThings3D, HD1K
File "C:\Users\ASUS\.conda\envs\mindspore\lib\site-packages\torchvision\datasets\_optical_flow.py", line 12, in <module>
from ..io.image import _read_png_16
File "C:\Users\ASUS\.conda\envs\mindspore\lib\site-packages\torchvision\io\__init__.py", line 22, in <module>
from .image import (
File "C:\Users\ASUS\.conda\envs\mindspore\lib\site-packages\torchvision\io\image.py", line 59, in <module>
module.load_state_dict(torch.load(r'./param/cifar10_cnn.pkl'))
File "C:\Users\ASUS\.conda\envs\mindspore\lib\site-packages\torch\serialization.py", line 594, in load
with _open_file_like(f, 'rb') as opened_file:
File "C:\Users\ASUS\.conda\envs\mindspore\lib\site-packages\torch\serialization.py", line 230, in _open_file_like
return _open_file(name_or_buffer, mode)
File "C:\Users\ASUS\.conda\envs\mindspore\lib\site-packages\torch\serialization.py", line 211, in __init__
super(_open_file, self).__init__(open(name, mode))
FileNotFoundError: [Errno 2] No such file or directory: './param/cifar10_cnn.pkl'
这个是我操作台的设置,目前出现的问题就是不管运行的是什么样的代码出现的都是FileNotFoundError: [Errno 2] No such file or directory: './param/cifar10_cnn.pkl'的错误,这个能有什么解决方法嘛?
#main.py的代码如下
import torchvision
from torch import nn
import torch
from torch.utils.data import DataLoader
from matplotlib import pyplot as plt
from matplotlib import font_manager
font = font_manager.FontProperties(fname=r'C:\Windows\Fonts\STSONG.TTF')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_loss = list()
test_loss = list()
def plot(train_loss,test_loss):
plt.figure(figsize=(5,5))
plt.plot(train_loss,label='train_loss',alpha = 0.5)
plt.plot(test_loss,label='test_loss',alpha=0.5)
plt.title('使用非线性函数和图像数据增强手段处理CIFAR-10数据集',fontproperties=font)
plt.xlabel('训练/测试次数',fontproperties=font)
plt.ylabel('损失',fontproperties=font)
plt.legend()
plt.show()
#图像数据增强手段
train_data_set = torchvision.datasets.CIFAR10(root='dataset',train=True,transform=torchvision.transforms.Compose([
torchvision.transforms.RandomCrop(size=(32,32),padding=4),
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean=[0.5,0.5,0.5],std=[0.5,0.5,0.5])
]),download=True)
test_data_set = torchvision.datasets.CIFAR10(root='dataset',train=False,transform=torchvision.transforms.Compose([
torchvision.transforms.RandomCrop(size=(32,32),padding=4),
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean=[0.5,0.5,0.5],std=[0.5,0.5,0.5])
]),download=True)
train_data_load = DataLoader(dataset=train_data_set,batch_size=64,shuffle=True,drop_last=True)
test_data_load = DataLoader(dataset=test_data_set,batch_size=64,shuffle=True,drop_last=True)
train_data_size = len(train_data_set)
test_data_size = len(test_data_set)
print(f'训练集的大小为{train_data_size}')
print(f'测试集的大小为{test_data_size}')
class MyNet(nn.Module):
def __init__(self):
super().__init__()
self.main = nn.Sequential(
nn.Conv2d(in_channels=3,out_channels=32,kernel_size=3,padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2,stride=2),
nn.BatchNorm2d(num_features=32),
nn.Conv2d(in_channels=32,out_channels=64,kernel_size=3,padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2,stride=2),
nn.BatchNorm2d(num_features=64),
nn.Conv2d(in_channels=64,out_channels=128,kernel_size=3,padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2,stride=2),
nn.BatchNorm2d(128),
)
self.fc = nn.Sequential(
nn.Flatten(),
nn.Linear(128*4*4,1024),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(1024,256),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(256,10)
)
def forward(self,x):
return self.fc(self.main(x))
mynet = MyNet()
mynet = mynet.to(device)
print(mynet)
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device)
learning_rate = 1e-3
optim = torch.optim.Adam(mynet.parameters(),lr=learning_rate)
train_step = 0
test_step = 0
epoch = 5
if __name__ == '__main__':
for i in range(epoch) :
print(f'----------第{i+1}轮训练开始----------')
mynet.train()
for j , (imgs,targets) in enumerate(train_data_load):
imgs = imgs.to(device)
targets = targets.to(device)
outputs = mynet(imgs)
loss = loss_fn(outputs,targets)
optim.zero_grad()
loss.backward()
optim.step()
train_step += 1
if train_step % 100 == 0:
print(f'训练第{train_step}次,loss={loss}')
train_loss.append(loss)
mynet.eval()
accuracy = 0
accuracy_total = 0
with torch.no_grad():
for j,(imgs,targets) in enumerate(test_data_load):
imgs = imgs.to(device)
targets = targets.to(device)
outputs = mynet(imgs)
loss = loss_fn(outputs,targets)
accuracy = (outputs.argmax(axis=1) == targets).sum()
accuracy_total += accuracy
test_step += 1
if test_step % 100 == 0:
test_loss.append(loss)
print(f'第{i+1}轮训练结束,准确率{accuracy_total/test_data_size}')
torch.save(mynet,f'CIAFR_10_{i+1}_acc_{accuracy_total/test_data_size}.pth')
plot(train_loss,test_loss)
#test.py的代码如下
import os
import torch
from PIL import Image
import torchvision
from torch import nn
class MyNet(nn.Module):
def __init__(self):
super().__init__()
self.main = nn.Sequential(
nn.Conv2d(in_channels=3,out_channels=32,kernel_size=3,padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2,stride=2),
nn.BatchNorm2d(num_features=32),
nn.Conv2d(in_channels=32,out_channels=64,kernel_size=3,padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2,stride=2),
nn.BatchNorm2d(num_features=64),
nn.Conv2d(in_channels=64,out_channels=128,kernel_size=3,padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2,stride=2),
nn.BatchNorm2d(128),
)
self.fc = nn.Sequential(
nn.Flatten(),
nn.Linear(128*4*4,1024),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(1024,256),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(256,10)
)
def forward(self,x):
return self.fc(self.main(x))
targets_idx = {
0:'飞机',
1:'汽车',
2:'鸟',
3:'猫',
4:'鹿',
5:'狗',
6:'青蛙',
7:'马',
8:'船',
9:'卡车'
}
root_dir = 'test_CIFAR_10'
obj_dir = 'test2.png'
img_dir = os.path.join(root_dir,obj_dir)
img = Image.open(img_dir)
tran_pose = torchvision.transforms.Compose([
torchvision.transforms.Resize(size=(32,32)),
torchvision.transforms.ToTensor()
])
mynet = torch.load('CIAFR_10_20_acc_0.8222000002861023.pth',map_location=torch.device('cpu'))
img = tran_pose(img)
img = torch.reshape(img,(1,3,32,32))
print(img.shape)
te
output = mynet(img)
print(targets_idx[output.argmax(axis = 1).item()])