文章目录
class_indices.jsonmodel.pypredict.pytrain.py创建自己的数据集
#详解
class_indices.json
{
"0": "daisy",
"1": "dandelion",
"2": "roses",
"3": "sunflowers",
"4": "tulips"
}
model.py
import torch
.nn
as nn
import torch
class AlexNet(nn
.Module
):
def __init__(self
, num_classes
=1000, init_weights
=False):
super(AlexNet
, self
).__init__
()
self
.features
= nn
.Sequential
(
nn
.Conv2d
(3, 48, kernel_size
=11, stride
=4, padding
=2),
nn
.ReLU
(inplace
=True),
nn
.MaxPool2d
(kernel_size
=3, stride
=2),
nn
.Conv2d
(48, 128, kernel_size
=5, padding
=2),
nn
.ReLU
(inplace
=True),
nn
.MaxPool2d
(kernel_size
=3, stride
=2),
nn
.Conv2d
(128, 192, kernel_size
=3, padding
=1),
nn
.ReLU
(inplace
=True),
nn
.Conv2d
(192, 192, kernel_size
=3, padding
=1),
nn
.ReLU
(inplace
=True),
nn
.Conv2d
(192, 128, kernel_size
=3, padding
=1),
nn
.ReLU
(inplace
=True),
nn
.MaxPool2d
(kernel_size
=3, stride
=2),
)
self
.classifier
= nn
.Sequential
(
nn
.Dropout
(p
=0.5),
nn
.Linear
(128 * 6 * 6, 2048),
nn
.ReLU
(inplace
=True),
nn
.Dropout
(p
=0.5),
nn
.Linear
(2048, 2048),
nn
.ReLU
(inplace
=True),
nn
.Linear
(2048, num_classes
),
)
if init_weights
:
self
._initialize_weights
()
def forward(self
, x
):
x
= self
.features
(x
)
x
= torch
.flatten
(x
, start_dim
=1)
x
= self
.classifier
(x
)
return x
def _initialize_weights(self
):
for m
in self
.modules
():
if isinstance(m
, nn
.Conv2d
):
nn
.init
.kaiming_normal_
(m
.weight
, mode
='fan_out', nonlinearity
='relu')
if m
.bias
is not None:
nn
.init
.constant_
(m
.bias
, 0)
elif isinstance(m
, nn
.Linear
):
nn
.init
.normal_
(m
.weight
, 0, 0.01)
nn
.init
.constant_
(m
.bias
, 0)
predict.py
import torch
from model
import AlexNet
from PIL
import Image
from torchvision
import transforms
import matplotlib
.pyplot
as plt
import json
data_transform
= transforms
.Compose
(
[transforms
.Resize
((224, 224)),
transforms
.ToTensor
(),
transforms
.Normalize
((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
img
= Image
.open("../tulip.jpg")
plt
.imshow
(img
)
img
= data_transform
(img
)
img
= torch
.unsqueeze
(img
, dim
=0)
try:
json_file
= open('./class_indices.json', 'r')
class_indict
= json
.load
(json_file
)
except Exception
as e
:
print(e
)
exit
(-1)
model
= AlexNet
(num_classes
=5)
model_weight_path
= "./AlexNet.pth"
model
.load_state_dict
(torch
.load
(model_weight_path
))
model
.eval()
with torch
.no_grad
():
output
= torch
.squeeze
(model
(img
))
predict
= torch
.softmax
(output
, dim
=0)
predict_cla
= torch
.argmax
(predict
).numpy
()
print(class_indict
[str(predict_cla
)], predict
[predict_cla
].item
())
plt
.show
()
train.py
import torch
import torch
.nn
as nn
from torchvision
import transforms
, datasets
, utils
import matplotlib
.pyplot
as plt
import numpy
as np
import torch
.optim
as optim
from model
import AlexNet
import os
import json
import time
device
= torch
.device
("cuda:0" if torch
.cuda
.is_available
() else "cpu")
print(device
)
data_transform
= {
"train": transforms
.Compose
([transforms
.RandomResizedCrop
(224),
transforms
.RandomHorizontalFlip
(),
transforms
.ToTensor
(),
transforms
.Normalize
((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]),
"val": transforms
.Compose
([transforms
.Resize
((224, 224)),
transforms
.ToTensor
(),
transforms
.Normalize
((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])}
data_root
= os
.path
.abspath
(os
.path
.join
(os
.getcwd
(), "../.."))
image_path
= data_root
+ "/data_set/flower_data/"
train_dataset
= datasets
.ImageFolder
(root
=image_path
+ "/train",
transform
=data_transform
["train"])
train_num
= len(train_dataset
)
flower_list
= train_dataset
.class_to_idx
cla_dict
= dict((val
, key
) for key
, val
in flower_list
.items
())
json_str
= json
.dumps
(cla_dict
, indent
=4)
with open('class_indices.json', 'w') as json_file
:
json_file
.write
(json_str
)
batch_size
= 32
train_loader
= torch
.utils
.data
.DataLoader
(train_dataset
,
batch_size
=batch_size
, shuffle
=True,
num_workers
=0)
validate_dataset
= datasets
.ImageFolder
(root
=image_path
+ "/val",
transform
=data_transform
["val"])
val_num
= len(validate_dataset
)
validate_loader
= torch
.utils
.data
.DataLoader
(validate_dataset
,
batch_size
=4, shuffle
=True,
num_workers
=0)
net
= AlexNet
(num_classes
=5, init_weights
=True)
net
.to
(device
)
loss_function
= nn
.CrossEntropyLoss
()
optimizer
= optim
.Adam
(net
.parameters
(), lr
=0.0002)
save_path
= './AlexNet.pth'
best_acc
= 0.0
for epoch
in range(10):
net
.train
()
running_loss
= 0.0
t1
= time
.perf_counter
()
for step
, data
in enumerate(train_loader
, start
=0):
images
, labels
= data
optimizer
.zero_grad
()
outputs
= net
(images
.to
(device
))
loss
= loss_function
(outputs
, labels
.to
(device
))
loss
.backward
()
optimizer
.step
()
running_loss
+= loss
.item
()
rate
= (step
+ 1) / len(train_loader
)
a
= "*" * int(rate
* 50)
b
= "." * int((1 - rate
) * 50)
print("\rtrain loss: {:^3.0f}%[{}->{}]{:.3f}".format(int(rate
* 100), a
, b
, loss
), end
="")
print()
print(time
.perf_counter
()-t1
)
net
.eval()
acc
= 0.0
with torch
.no_grad
():
for val_data
in validate_loader
:
val_images
, val_labels
= val_data
outputs
= net
(val_images
.to
(device
))
predict_y
= torch
.max(outputs
, dim
=1)[1]
acc
+= (predict_y
== val_labels
.to
(device
)).sum().item
()
val_accurate
= acc
/ val_num
if val_accurate
> best_acc
:
best_acc
= val_accurate
torch
.save
(net
.state_dict
(), save_path
)
print('[epoch %d] train_loss: %.3f test_accuracy: %.3f' %
(epoch
+ 1, running_loss
/ step
, val_accurate
))
print('Finished Training')
创建自己的数据集
偷懒的办法 在flowerdata下直接全删了改自己的
转载请注明原文地址:https://blackberry.8miu.com/read-4001.html