2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Weeds are one of the main problems in agriculture, posing a serious threat to crop growth and yield. Traditional manual identification and management methods are inefficient and imprecise, so advanced computer vision technology is needed to improve the efficiency and quality of agricultural production. As a deep learning model, ResNet performs well in processing complex image classification tasks. It can not only effectively solve the problems of diverse and complex weeds in farmland, but also promote the development of intelligent agriculture, reduce dependence on chemical pesticides, and achieve the goal of sustainable agricultural development. By using ResNet for weed classification, farmers can be provided with smarter and more accurate agricultural management solutions, which can promote the improvement of agricultural production efficiency and the modernization of the agricultural industry. Therefore, this project uses the domestic framework PaddleClas+Swanlab+Gradio+Swanhub for weed classification experiments.
PaddlePaddle is an enterprise-level deep learning platform developed by Baidu, which is designed to support the full process of deep learning applications from model development to deployment. It provides a wealth of tools and libraries to support a variety of deep learning tasks, including image processing, natural language processing, speech recognition, etc.PaddlePaddle
PaddleClas is a tool library in the Paddle framework specifically for image classification tasks. It provides a complete set of end-to-end solutions, including data processing, model definition, training, evaluation, and deployment, aiming to help developers quickly build and deploy efficient image classification models.PaddleClas
SwanLab is an open source, lightweight AI experiment tracking tool that improves the ML experiment tracking and collaboration experience by providing a friendly API combined with hyperparameter tracking, indicator recording, online collaboration and other functions.Welcome to SwanLab | SwanLab Official Documentation
Swanhub is an open source model collaboration and sharing community developed by Geek Studio. It provides AI developers with functions such as AI model hosting, training records, model result display, and API rapid deployment.Welcome to Swanhub
Gradio is an open source Python library designed to help data scientists, researchers, and developers working in the field of machine learning quickly create and share user interfaces for machine learning models.Gradio
Install the following 3 libraries:
- paddle
- swanlab
- gradio
Installation command:
pip install paddle swanlab gradio
Weed Classification Dataset: DeepWeeds
- DeepWeeds
- --images
- ----1.jpg
- ----2.jpg
- --train.txt
- --val.txt
- --test.txt
- --classnames.txt
Their respective functions and significance:
1. DeepWeeds folder: This folder is used to store the image folder images, training set test set validation set files and label files
2. images folder: This folder is used to save training, testing, and validation image folders.
3. train.txt, val.txt, test.txt files: These files are used to save the training, test, and validation set image paths and categories.
4. classnames file: used to save category labels
Model link:PaddleClas Model
After decompression, you will get the PaddleClas folder.
Create app.py in the PaddleClas folder.
Its function is to run the Gradio Demo script
First, find ppcls-->configs-->ImageNet-->Res2Net-->Res2Net50_14w_8s.yaml in the PaddleClas folder.
Modify epochs to 100, class class_num to 9, training image path, verification image path and label file. A total of 7 changes were made.
- # global configs
- Global:
- checkpoints: null
- pretrained_model: null
- output_dir: ./output/
- device: gpu
- save_interval: 1
- eval_during_train: True
- eval_interval: 1
- epochs: 100###########################1##############################
- print_batch_step: 10
- use_visualdl: False
- # used for static mode and model export
- image_shape: [3, 224, 224]
- save_inference_dir: ./inference
-
- # model architecture
- Arch:
- name: Res2Net50_14w_8s
- class_num: 9############################2##############################
-
- # loss function config for traing/eval process
- Loss:
- Train:
- - CELoss:
- weight: 1.0
- epsilon: 0.1
- Eval:
- - CELoss:
- weight: 1.0
-
-
- Optimizer:
- name: Momentum
- momentum: 0.9
- lr:
- name: Cosine
- learning_rate: 0.1
- regularizer:
- name: 'L2'
- coeff: 0.0001
-
-
- # data loader for train and eval
- DataLoader:
- Train:
- dataset:
- name: ImageNetDataset
- image_root: ./weeds/images/#################3#######################
- cls_label_path: ./weeds/train.txt###########4########################
- transform_ops:
- - DecodeImage:
- to_rgb: True
- channel_first: False
- - RandCropImage:
- size: 224
- - RandFlipImage:
- flip_code: 1
- - NormalizeImage:
- scale: 1.0/255.0
- mean: [0.485, 0.456, 0.406]
- std: [0.229, 0.224, 0.225]
- order: ''
- batch_transform_ops:
- - MixupOperator:
- alpha: 0.2
-
- sampler:
- name: DistributedBatchSampler
- batch_size: 64
- drop_last: False
- shuffle: True
- loader:
- num_workers: 4
- use_shared_memory: True
-
- Eval:
- dataset:
- name: ImageNetDataset
- image_root: ./DeepWeeds/images/###############5#######################
- cls_label_path: ./DeepWeeds/val.txt###########6########################
- transform_ops:
- - DecodeImage:
- to_rgb: True
- channel_first: False
- - ResizeImage:
- resize_short: 256
- - CropImage:
- size: 224
- - NormalizeImage:
- scale: 1.0/255.0
- mean: [0.485, 0.456, 0.406]
- std: [0.229, 0.224, 0.225]
- order: ''
- sampler:
- name: DistributedBatchSampler
- batch_size: 64
- drop_last: False
- shuffle: False
- loader:
- num_workers: 4
- use_shared_memory: True
-
- Infer:
- infer_imgs: docs/images/inference_deployment/whl_demo.jpg
- batch_size: 10
- transforms:
- - DecodeImage:
- to_rgb: True
- channel_first: False
- - ResizeImage:
- resize_short: 256
- - CropImage:
- size: 224
- - NormalizeImage:
- scale: 1.0/255.0
- mean: [0.485, 0.456, 0.406]
- std: [0.229, 0.224, 0.225]
- order: ''
- - ToCHWImage:
- PostProcess:
- name: Topk
- topk: 5
- class_id_map_file: ./DeepWeeds/classnaems.txt###########7##################
-
- Metric:
- Train:
- Eval:
- - TopkAcc:
- topk: [1, 5]
Find tools-->train.py in the PaddleClas folder. Initialize swanlab
- # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
-
- from __future__ import absolute_import
- from __future__ import division
- from __future__ import print_function
- import os
- import sys
-
- __dir__ = os.path.dirname(os.path.abspath(__file__))
- sys.path.append(os.path.abspath(os.path.join(__dir__, '../')))
-
- from ppcls.utils import config
- from ppcls.engine.engine import Engine
- import swanlab
- # -*- coding: utf-8 -*-
-
- if __name__ == "__main__":
- args = config.parse_args()
- config = config.get_config(
- args.config, overrides=args.override, show=False)
- config.profiler_options = args.profiler_options
- engine = Engine(config, mode="train")
-
- ## 初始化swanlab
- swanlab.init(
- experiment_name="Swanlab_ResNet50_PaddleClas",
- description="Train ResNet50 for weeds classification.",
- project="Swanhub_Weeds_Classification",
- config={
- "model": "ResNet50",
- "optim": "Adam",
- "lr": 0.001,
- "batch_size": 64,
- "num_epochs": 100,
- "num_class": 9,
- }
- )
- engine.train()
In PaddleClas, find ppcls-->engine-->train-->utils.py and add the following code:
- swanlab.log({"train_lr_msg": lr_msg.split(": ")[1]}) #
- swanlab.log({"train_CELoss": metric_msg.split(",")[0].split(': ')[1]}) ##
- swanlab.log({'train_loss': metric_msg.split(",")[1].split(': ')[1]})
In the PaddleClas folder, find ppcls-->engine-->engine.py and add the following code:
swanlab.log({'best_metric': best_metric.get('metric')})
Enter the following command in the console:
python -m paddle.distributed.launch tools/train.py -c ./ppcls/configs/ImageNet/Res2Net/Res2Net50_14w_8s.yaml
View experiment details at swanlab
The experimental results are as follows:
swanlab View experimental results
Enter the following code into the console:
python tools/infer.py -c ./ppcls/configs/ImageNet/Res2Net/Res2Net50_14w_8s.yaml -o Infer.infer_imgs=./DeepWeeds/infer/01.jpg -o Global.pretrained_model=./output/Res2Net50_14w_8s/best_model
First, find ppcls-->configs-->ImageNet-->DarkNet-->DarkNet53.yaml in the PaddleClas folder.
Modify epochs to 100, class class_num to 9, training image path, verification image path and label file. A total of 7 changes were made.
- # global configs
- Global:
- checkpoints: null
- pretrained_model: null
- output_dir: ./output/
- device: gpu
- save_interval: 1
- eval_during_train: True
- eval_interval: 1
- epochs: 100
- print_batch_step: 10
- use_visualdl: False
- # used for static mode and model export
- image_shape: [3, 256, 256]
- save_inference_dir: ./inference
-
- # model architecture
- Arch:
- name: DarkNet53
- class_num: 9
-
- # loss function config for traing/eval process
- Loss:
- Train:
- - CELoss:
- weight: 1.0
- epsilon: 0.1
- Eval:
- - CELoss:
- weight: 1.0
-
-
- Optimizer:
- name: Momentum
- momentum: 0.9
- lr:
- name: Cosine
- learning_rate: 0.1
- regularizer:
- name: 'L2'
- coeff: 0.0001
-
-
- # data loader for train and eval
- DataLoader:
- Train:
- dataset:
- name: ImageNetDataset
- image_root: F:/datasets/DeepWeeds/images
- cls_label_path: F:/datasets/DeepWeeds/train.txt
- transform_ops:
- - DecodeImage:
- to_rgb: True
- channel_first: False
- - RandCropImage:
- size: 256
- - RandFlipImage:
- flip_code: 1
- - NormalizeImage:
- scale: 1.0/255.0
- mean: [0.485, 0.456, 0.406]
- std: [0.229, 0.224, 0.225]
- order: ''
- batch_transform_ops:
- - MixupOperator:
- alpha: 0.2
-
- sampler:
- name: DistributedBatchSampler
- batch_size: 64
- drop_last: False
- shuffle: True
- loader:
- num_workers: 4
- use_shared_memory: True
-
- Eval:
- dataset:
- name: ImageNetDataset
- image_root: F:/datasets/DeepWeeds/images
- cls_label_path: F:/datasets/DeepWeeds/val.txt
- transform_ops:
- - DecodeImage:
- to_rgb: True
- channel_first: False
- - ResizeImage:
- resize_short: 292
- - CropImage:
- size: 256
- - NormalizeImage:
- scale: 1.0/255.0
- mean: [0.485, 0.456, 0.406]
- std: [0.229, 0.224, 0.225]
- order: ''
- sampler:
- name: DistributedBatchSampler
- batch_size: 64
- drop_last: False
- shuffle: False
- loader:
- num_workers: 4
- use_shared_memory: True
-
- Infer:
- infer_imgs: docs/images/inference_deployment/whl_demo.jpg
- batch_size: 10
- transforms:
- - DecodeImage:
- to_rgb: True
- channel_first: False
- - ResizeImage:
- resize_short: 292
- - CropImage:
- size: 256
- - NormalizeImage:
- scale: 1.0/255.0
- mean: [0.485, 0.456, 0.406]
- std: [0.229, 0.224, 0.225]
- order: ''
- - ToCHWImage:
- PostProcess:
- name: Topk
- topk: 5
- class_id_map_file: F:/datasets/DeepWeeds/classnames
-
- Metric:
- Train:
- Eval:
- - TopkAcc:
- topk: [1, 5]
Find tools->train.py in the PaddleClas folder. Modify the initialization of swanlab
- # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
-
- from __future__ import absolute_import
- from __future__ import division
- from __future__ import print_function
- import os
- import sys
-
- __dir__ = os.path.dirname(os.path.abspath(__file__))
- sys.path.append(os.path.abspath(os.path.join(__dir__, '../')))
-
- from ppcls.utils import config
- from ppcls.engine.engine import Engine
- import swanlab
- # -*- coding: utf-8 -*-
-
- if __name__ == "__main__":
- args = config.parse_args()
- config = config.get_config(
- args.config, overrides=args.override, show=False)
- config.profiler_options = args.profiler_options
- engine = Engine(config, mode="train")
-
- ## 初始化swanlab
- swanlab.init(
- experiment_name="Swanlab_DrakNet53_PaddleClas",
- description="Train DarkNet53 for weeds classification.",
- project="Swanhub_Weeds_Classification",
- config={
- "model": "DarkNet53",
- "optim": "Adam",
- "lr": 0.001,
- "batch_size": 64,
- "num_epochs": 100,
- "num_class": 9,
- }
- )
- engine.train()
Enter the following command in the console:
python -m paddle.distributed.launch tools/train.py -c ./ppcls/configs/ImageNet/DarkNet/DarknetNet53.yaml
View experiment details at swanlab
The experimental results are as follows:
Enter the following code into the console:
python tools/infer.py -c ./ppcls/configs/ImageNet/DarkNet/DarkNet53.yaml -o Infer.infer_imgs=./DeepWeeds/infer/01.jpg -o Global.pretrained_model=./output/DarkNet53/best_model
4.5 Swanlab Results Display
As can be seen from the figure, the effect of the ResNet50 model is better than that of the DarkNet53 model. Swanlab provides a convenient comparison chart function.
To be continued...
To be continued...