更多图像分类、图像识别、目标检测、图像分割,图像检索等项目可从主页查看

 功能演示(要看shi pin下面的简介):

https://www.bilibili.com/video/BV1STUKBQEpb/?spm_id_from=333.1387.upload.video_card.click&vd_source=23ce57e8cf06ed0fb5cf39f62df5d51b

(一)简介

基于卷积神经网络的大豆病虫害识别与防治系统是在pytorch框架下实现的,项目中有3个模型,resnet50,alexnet,mobilenet,3个模型都在项目中,随便用一个模型即可,也可以3个都使用,做模型对比,增加工作量。

该系统涉及的技术:python + pyside6 + opencv ;GUI界面:python + pyside6

该项目是可在pycharm和anaconda搭建的虚拟环境 或者 vscode和anaconda搭建的虚拟环境中运行,

 pycharm和anaconda安装和配置可观看教程:

超详细的pycharm+anaconda搭建python虚拟环境_pycharm anaconda环境搭建-CSDN博客

vscode和anaconda安装和配置可观看教程: 

保姆级的vscode+anaconda搭建python虚拟环境-CSDN博客

(二)项目介绍

1. 项目结构

2. 数据集 

部分数据展示: 

3.GUI界面初始界面 

4.GUI预测界面

 

5. 核心代码 
class MainProcess:
    def __init__(self, train_path, test_path, model_name):
        
        self.train_path = train_path
        self.test_path = test_path
        self.model_name = model_name
        self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
        def main(self, epochs):
        # 记录训练过程
        log_file_name = './results/resnet50训练和验证过程.txt'
        # 记录正常的 print 信息
        sys.stdout = Logger(log_file_name)

        # print("using {} device.".format(self.device))
        # 开始训练,记录开始时间
        begin_time = time()
        # 加载数据
        train_loader, validate_loader, class_names, train_num, val_num = self.data_load()
        print("class_names: ", class_names)
        train_steps = len(train_loader)  # 训练集批次数量
        val_steps = len(validate_loader)  # 验证集批次数量
        # 加载模型
        model = self.model_load()  # 创建模型

        # 网络结构可视化
        x = torch.randn(16, 3, 224, 224)  # 随机生成一个输入
        model_visual_path = 'results/resnet50_visual.onnx'  # 模型结构保存路径
        torch.onnx.export(model, x, model_visual_path)  # 将 pytorch 模型以 onnx 格式导出并保存
        # netron.start(model_visual_path)  # 浏览器会自动打开网络结构

        # load pretrain weights
        model_weight_path = "models/resnet50-pre.pth"  # 预训练模型权重路径
        assert os.path.exists(model_weight_path), "file {} does not exist.".format(model_weight_path)  # 权重文件是否存在
        model.load_state_dict(torch.load(model_weight_path, map_location='cpu'))  # 加载预训练模型权重

        # change fc layer structure
        in_channel = model.fc.in_features  # 获取fc层输入通道数
        model.fc = nn.Linear(in_channel, len(class_names))  # 修改fc层结构

        # 将模型放入GPU中或CPU中
        model.to(self.device)
        # 定义损失函数,这里采用交叉熵损失函数
        loss_function = nn.CrossEntropyLoss()
        # 定义优化器
        params = [p for p in model.parameters() if p.requires_grad]  # 过滤不需要梯度更新的参数
        optimizer = optim.Adam(params=params, lr=0.0001)  # 优化器,这里采用Adam优化器,初始学习率为0.0001

        train_loss_history, train_acc_history = [], []  # 记录训练过程的损失和准确率
        test_loss_history, test_acc_history = [], []  # 记录验证过程的损失和准确率
        best_acc = 0.0  # 记录最佳准确率

        for epoch in range(0, epochs):  # 训练epochs次
            # 下面是模型训练
            model.train()  # 启用 BatchNormalization 和 Dropout
            running_loss = 0.0
            train_acc = 0.0
            train_bar = tqdm(train_loader, file=sys.stdout)  # 进度条
            # 进来一个batch的数据,计算一次梯度,更新一次网络
            for step, data in enumerate(train_bar):  # 遍历训练集数据
                images, labels = data  # 获取图像及对应的真实标签
                optimizer.zero_grad()  # 清空过往梯度
                outputs = model(images.to(self.device))  # 得到预测的标签
                train_loss = loss_function(outputs, labels.to(self.device))  # 计算损失
                train_loss.backward()  # 反向传播,计算当前梯度
                optimizer.step()  # 根据梯度更新网络参数

                # print statistics
                running_loss += train_loss.item()  # 累加损失
                predict_y = torch.max(outputs, dim=1)[1]  # 每行最大值的索引
                # torch.eq()进行逐元素的比较,若相同位置的两个元素相同,则返回True;若不同,返回False
                train_acc += torch.eq(predict_y, labels.to(self.device)).sum().item()  # 计算准确率
                train_bar.desc = "train epoch[{}/{}] loss:{:.3f}".format(epoch + 1,
                                                                         epochs,
                                                                         train_loss)  # 更新进度条
            # 下面是模型验证
            model.eval()  # 不启用 BatchNormalization 和 Dropout,保证BN和dropout不发生变化
            val_acc = 0.0  # accumulate accurate number / epoch
            testing_loss = 0.0
            with torch.no_grad():  # 张量的计算过程中无需计算梯度
                val_bar = tqdm(validate_loader, file=sys.stdout)  # 进度条
                for val_data in val_bar:  # 遍历验证集数据
                    val_images, val_labels = val_data  # 取出图像和标签
                    outputs = model(val_images.to(self.device))  # 模型推理

                    val_loss = loss_function(outputs, val_labels.to(self.device))  # 计算损失
                    testing_loss += val_loss.item()  # 累加损失

                    predict_y = torch.max(outputs, dim=1)[1]  # 每行最大值的索引
                    # torch.eq()进行逐元素的比较,若相同位置的两个元素相同,则返回True;若不同,返回False
                    val_acc += torch.eq(predict_y, val_labels.to(self.device)).sum().item()  # 计算准确率

            train_loss = running_loss / train_steps  # 计算平均损失
            train_accurate = train_acc / train_num  # 计算平均准确率
            test_loss = testing_loss / val_steps  # 计算平均损失
            val_accurate = val_acc / val_num  # 计算平均准确率

            train_loss_history.append(train_loss)
            train_acc_history.append(train_accurate)
            test_loss_history.append(test_loss)
            test_acc_history.append(val_accurate)

            print('[epoch %d] train_loss: %.3f  val_accuracy: %.3f' %
                  (epoch + 1, train_loss, val_accurate))
            if val_accurate > best_acc:
                best_acc = val_accurate
                torch.save(model.state_dict(), self.model_name)  # 保存最佳模型

        # 记录结束时间
        end_time = time()
        run_time = end_time - begin_time
        print('该循环程序运行时间:', run_time, "s")
        # 数据保存
        str_train_loss_history = ','.join([str(i) for i in train_loss_history])
        str_train_acc_history = ','.join([str(i) for i in train_acc_history])
        str_test_loss_history = ','.join([str(i) for i in test_loss_history])
        str_test_acc_history = ','.join([str(i) for i in test_acc_history])
        with open('results/resnet50_loss_acc.txt', 'w') as f:
            f.write("train_loss_history: " + str_train_loss_history + "\n")
            f.write("train_acc_history: " + str_train_acc_history + "\n")
            f.write("test_loss_history: " + str_test_loss_history + "\n")
            f.write("test_acc_history: " + str_test_acc_history + "\n")
        # 绘制模型训练过程图
        self.show_loss_acc(train_loss_history, train_acc_history,
                           test_loss_history, test_acc_history)
        # 画热力图
        test_real_labels, test_pre_labels = self.heatmaps(model, validate_loader, class_names)
        # 计算混淆矩阵
        self.calculate_confusion_matrix(test_real_labels, test_pre_labels, class_names)

该系统可以训练自己的数据集,训练过程也比较简单,只需指定自己数据集中训练集、验证集、测试集的路径,指定所用的模型和指定训练的轮数,然后运行项目中的train.py和test.py即可

训练和测试结束后可输出以下结果:
a. 训练过程的准确率曲线和损失曲线

 b. 模型训练过程记录,模型每一轮训练的损失和精度数值记录

c. 模型结构

模型评估可输出:
a. 分类混淆矩阵

​​

 b. 准确率、精确率、召回率、F1值

其他的输出:
a. 模型特征图

b. 热力图

c. 模型参数量对比

(三)总结

以上即为整个项目的介绍,整个项目主要包括以下内容:完整的程序代码文件、训练好的模型、数据集、GUI界面和各种模型指标图表等。

整个项目包含全部资料,一步到位,拿来就用,省心省力。

项目运行过程如出现问题,请及时沟通!

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐