把网络模型单独拎出来了,方便解耦。下一步准备把重要的配置全部拎出来。
This commit is contained in:
@@ -9,8 +9,14 @@ import matplotlib
|
||||
import numpy as np
|
||||
from tqdm import tqdm
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
# 添加net目录到路径
|
||||
# sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'net'))
|
||||
# from food_net import create_food_cnn
|
||||
from net import create_food_cnn
|
||||
|
||||
# 设置matplotlib支持中文显示
|
||||
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans'] # 指定默认字体
|
||||
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
|
||||
@@ -19,61 +25,7 @@ plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
print(f"使用设备: {device}")
|
||||
|
||||
# 定义CNN模型(基于CIFAR10结构,输出层改为3分类)
|
||||
class FoodCNN(nn.Module):
|
||||
def __init__(self):
|
||||
super(FoodCNN, self).__init__()
|
||||
# 第一个卷积块
|
||||
self.conv1 = nn.Conv2d(3, 32, 3, padding=1)
|
||||
self.conv2 = nn.Conv2d(32, 32, 3, padding=1)
|
||||
self.pool1 = nn.MaxPool2d(2, 2)
|
||||
self.dropout1 = nn.Dropout2d(0.25)
|
||||
|
||||
# 第二个卷积块
|
||||
self.conv3 = nn.Conv2d(32, 64, 3, padding=1)
|
||||
self.conv4 = nn.Conv2d(64, 64, 3, padding=1)
|
||||
self.pool2 = nn.MaxPool2d(2, 2)
|
||||
self.dropout2 = nn.Dropout2d(0.25)
|
||||
|
||||
# 第三个卷积块
|
||||
self.conv5 = nn.Conv2d(64, 128, 3, padding=1)
|
||||
self.conv6 = nn.Conv2d(128, 128, 3, padding=1)
|
||||
self.pool3 = nn.MaxPool2d(2, 2)
|
||||
self.dropout3 = nn.Dropout2d(0.25)
|
||||
|
||||
# 全连接层
|
||||
self.fc1 = nn.Linear(128 * 4 * 4, 512)
|
||||
self.dropout4 = nn.Dropout(0.5)
|
||||
self.fc2 = nn.Linear(512, 3) # 改为2分类
|
||||
|
||||
def forward(self, x):
|
||||
# 第一个卷积块
|
||||
x = F.relu(self.conv1(x))
|
||||
x = F.relu(self.conv2(x))
|
||||
x = self.pool1(x)
|
||||
x = self.dropout1(x)
|
||||
|
||||
# 第二个卷积块
|
||||
x = F.relu(self.conv3(x))
|
||||
x = F.relu(self.conv4(x))
|
||||
x = self.pool2(x)
|
||||
x = self.dropout2(x)
|
||||
|
||||
# 第三个卷积块
|
||||
x = F.relu(self.conv5(x))
|
||||
x = F.relu(self.conv6(x))
|
||||
x = self.pool3(x)
|
||||
x = self.dropout3(x)
|
||||
|
||||
# 展平
|
||||
x = x.view(-1, 128 * 4 * 4)
|
||||
|
||||
# 全连接层
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.dropout4(x)
|
||||
x = self.fc2(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
# 数据预处理
|
||||
transform_train = transforms.Compose([
|
||||
@@ -201,7 +153,7 @@ if __name__ == '__main__':
|
||||
print(f"测试集大小: {len(test_dataset)}")
|
||||
|
||||
# 创建模型
|
||||
model = FoodCNN().to(device)
|
||||
model = create_food_cnn().to(device)
|
||||
print(f"模型参数数量: {sum(p.numel() for p in model.parameters() if p.requires_grad)}")
|
||||
|
||||
# 定义损失函数和优化器(使用与CIFAR10相同的超参数)
|
||||
|
||||
Reference in New Issue
Block a user