AlexNet

概念

过拟合:根本原因是特征维度过多,模型假设过于复杂,参数过多,训练数据过少,噪声过多,导致拟合的函数完美的预测训练集 ,但对新数据的测试集预测结果差。 过度的拟合了训练数据,而没有考虑到泛化能力。

代码

model.py

python 复制代码
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),  # input[3, 224, 224]  output[48, 55, 55]
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),                  # output[48, 27, 27]
            nn.Conv2d(48, 128, kernel_size=5, padding=2),           # output[128, 27, 27]
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),                  # output[128, 13, 13]
            nn.Conv2d(128, 192, kernel_size=3, padding=1),          # output[192, 13, 13]
            nn.ReLU(inplace=True),
            nn.Conv2d(192, 192, kernel_size=3, padding=1),          # output[192, 13, 13]
            nn.ReLU(inplace=True),
            nn.Conv2d(192, 128, kernel_size=3, padding=1),          # output[128, 13, 13]
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),                  # output[128, 6, 6]
        )
        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)

padding:

只能传入两种形式的变量,int整形,tuple类型。

比如int整形传入1,就会在图像的左上右下分别添上一层0。

比如tuple(1,2):1代表上下方各补一行零,2代表左右两侧各补两列零。

或者:

nn.ReLU(inplace=True):inplace=True增加计算量,减少内存使用

**Dropout:**失活。Dropout 是为了让全连接层部分失活,所以需要dropout的全连接层前配置Dropout()

激活:每一层都要激活。激活属于非线性操作,如果不激活,每层就是纯线性变换,连续的多层和只有一层是等效的,没有任何区别。

train.py

transform

python 复制代码
data_transform = {

        "train": transforms.Compose([transforms.RandomResizedCrop(224), # 随机裁剪成224×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)),  # cannot 224, must (224, 224)

                                   transforms.ToTensor(),

                                   transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])}

json类别文件

python 复制代码
    # data_root = os.path.abspath(os.path.join(os.getcwd(), "../.."))  # get data root path
    image_path = ("./flower_data")  # flower data set path
    assert os.path.exists(image_path), "{} path does not exist.".format(image_path)
    train_dataset = datasets.ImageFolder(root=os.path.join(image_path, "train"),
                                         transform=data_transform["train"])
    train_num = len(train_dataset)

用flower_list来保存类别索引,在这个数据集下,图片所在的文件夹名称即为他们的索引。

然后通过dict方法联合类别和序号值

再写入json文件。

python 复制代码
    # {'daisy':0, 'dandelion':1, 'roses':2, 'sunflower':3, 'tulips':4}

    flower_list = train_dataset.class_to_idx 

    cla_dict = dict((val, key) for key, val in flower_list.items())

    # write dict into json file

    json_str = json.dumps(cla_dict, indent=4)

    with open('class_indices.json', 'w') as json_file:

        json_file.write(json_str)

损失函数

python 复制代码
   loss_function = nn.CrossEntropyLoss()

nn.CrossEntropyLoss():针对多类别的损失函数

优化器

python 复制代码
    optimizer = optim.Adam(net.parameters(), lr=0.0002)

优化器是Adam优化器,优化对象是网络中所有的可训练的参数,学习率设置的为0.0002

net.train()

使用Dropout的方式再网络正向传播过程中随机失活一部分神经元。这是再训练过程中需要的,所以会调用net.train(),再测试过程中不需要随机失活,所以会调用net.eval()关闭dropout()方法.

相关推荐
tedcloud1233 小时前
UI-TARS-desktop部署教程:构建AI桌面自动化系统
服务器·前端·人工智能·ui·自动化·github
曦月逸霜5 小时前
啥是RAG 它能干什么?
人工智能·python·机器学习
AI医影跨模态组学5 小时前
Lancet Digit Health(IF=24.1)广东省人民医院刘再毅&南方医科大学南方医院梁莉等团队:基于可解释深度学习模型预测胶质瘤分子改变
人工智能·深度学习·论文·医学·医学影像·影像组学
应用市场5 小时前
AI 编程助手三强争霸(2026 版):Claude、Gemini、GPT 各自擅长什么?
人工智能·gpt
CSND7406 小时前
YOLO resume断点续训(不能用官方的权重,是自己训练一半生成的last.pt)
深度学习·yolo·机器学习
AC赳赳老秦6 小时前
供应链专员提效:OpenClaw自动跟踪物流信息、更新库存数据,异常自动提醒
java·大数据·服务器·数据库·人工智能·自动化·openclaw
脑极体6 小时前
从Token消耗到DAA增长,AI价值标尺正在重构
人工智能·重构
csdn小瓯6 小时前
LangGraph自适应工作流路由机制:从关键词匹配到智能决策的完整实现
人工智能·fastapi·langgraph
QYR-分析6 小时前
高功率飞秒激光器行业发展现状、市场机遇及未来趋势分析
大数据·人工智能
AI医影跨模态组学7 小时前
J Clin Oncol(IF=43.4)美国Cedars-Sinai医学中心等团队:基于计算组织学人工智能的晚期胰腺癌化疗选择预测性生物标志物的开发与验证
人工智能·机器学习·论文·医学·医学影像·影像组学