ultralytics / yolov5

YOLOv5 🚀 in PyTorch > ONNX > CoreML > TFLite
https://docs.ultralytics.com
GNU Affero General Public License v3.0
48.85k stars 15.96k forks source link

Yolo segmentation hyperparameter Evolution #11906

Closed iamprakhargupta closed 10 months ago

iamprakhargupta commented 1 year ago

Search before asking

Question

I have multiple questions which I have since I am trying to run hyperparameter evolution for my segmentation model.

I do see that the segmentation code train.py has code for hyperparameter evolution

Q1: I see the fitness function comments below state that weights will be applied to P R metrics/mAP_0.5(B) and metrics/mAP_0.5:0.95 by slicing all rows and first 4 columns of x

def fitness(x):
    # Model fitness as a weighted combination of metrics
    w = [0.0, 0.0, 0.1, 0.9]  # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
    return (x[:, :4] * w).sum(1)

But in the train.py when we read the CSV we pass all the values of the csv to the fitness()

for _ in range(opt.evolve):  # generations to evolve
            if evolve_csv.exists():  # if evolve.csv exists: select best hyps and mutate
                # Select parent(s)
                parent = 'single'  # parent selection method: 'single' or 'weighted'
                x = np.loadtxt(evolve_csv, ndmin=2, delimiter=',', skiprows=1)
                n = min(5, len(x))  # number of previous results to consider
                x = x[np.argsort(-fitness(x))][:n]  # top n mutations
                w = fitness(x) - fitness(x).min() + 1E-6  # weights (sum > 0)
                if parent == 'single' or len(x) == 1:
                    # x = x[random.randint(0, n - 1)]  # random selection
                    x = x[random.choices(range(n), weights=w)[0]]  # weighted selection
                elif parent == 'weighted':
                    x = (x * w.reshape(n, 1)).sum(0) / w.sum() 

Now my question is how are weights being applied to my metrics because when I look at my evolve.csv

      train/box_loss,      train/seg_loss,      train/obj_loss,      train/cls_loss,metrics/precision(B),   metrics/recall(B),  metrics/mAP_0.5(B),metrics/mAP_0.5:0.95(B),metrics/precision(M),   metrics/recall(M),  metrics/mAP_0.5(M),metrics/mAP_0.5:0.95(M),        val/box_loss,        val/seg_loss,        val/obj_loss,        val/cls_loss,               x/lr0,               x/lr1,               x/lr2,                 lr0,                 lrf,            momentum,        weight_decay,       warmup_epochs,     warmup_momentum,      warmup_bias_lr,                 box,                 cls,              cls_pw,                 obj,              obj_pw,               iou_t,            anchor_t,            fl_gamma,               hsv_h,               hsv_s,               hsv_v,             degrees,           translate,               scale,               shear,         perspective,              flipud,              fliplr,              mosaic,               mixup,          copy_paste,             anchors
             0.82198,             0.64013,             0.71905,             0.44133,             0.77251,             0.55216,             0.59938,             0.27542,            0.044692,            0.048322,            0.030093,           0.0058852,               0.001,                0.01,               0.937,              0.0005,                   3,                 0.8,                 0.1,                0.05,                 0.5,                   1,                   1,                   1,                 0.2,                   4,                   0,               0.015,                 0.7,                 0.4,                   0,                 0.1,                 0.5,                   0,                   0,                   0,                 0.5,                   0,                   0,                   0,                   3
             0.82198,             0.64013,             0.71905,             0.44133,             0.77251,             0.55216,             0.59938,             0.27542,            0.044692,            0.048322,            0.030093,           0.0058852,               0.001,                0.01,               0.937,              0.0005,                   3,                 0.8,                 0.1,                0.05,                 0.5,                   1,                   1,                   1,                 0.2,                   4,                   0,               0.015,                 0.7,                 0.4,                   0,                 0.1,                 0.5,                   0,                   0,                   0,                 0.5,                   0,                   0,                   0,                   3
                   0,                   0,                   0,                   0,                   0,                   0,                   0,                   0,                 nan,                 nan,                 nan,                 nan,                 0.1,             0.04195,                 0.6,               0.001,             0.00589,             0.00104,             0.00957,                 0.2,                 0.2,                   2,                 0.8,                 0.5,                 0.1,                   2,                   1,                 0.1,                 0.9,                 0.2,                   4,                   0,             0.01544,             0.61419,               0.001,                   0,                 0.1,                 0.5,                   0,                   0,                   2
                   0,                   0,                   0,                   0,                   0,                   0,                   0,                   0,                 nan,                 nan,                 nan,                 nan,                 0.1,             0.04195,                 0.6,               0.001,             0.00589,             0.00104,             0.00957,                 0.2,                 0.2,                   2,                 0.8,                 0.5,                 0.1,                   2,                   1,                 0.1,                 0.9,                 0.2,                   4,                   0,             0.01544,             0.61419,               0.001,                   0,                 0.1,                 0.5,                   0,                   0,                   2
          0.00019934,            0.010324,          0.00010308,          2.0187e-05,          0.00031629,           0.0038312,          0.00017246,          2.0777e-05,             0.47588,             0.41791,           0.0052818,            0.011287,                 0.1,             0.04529,                 0.6,               0.001,             0.00658,             0.00101,                0.01,                 0.2,                 0.2,                   2,             0.77271,                 0.5,                 0.1,                   2,                   1,                 0.1,                 0.9,             0.20879,                   4,                   0,              0.0153,             0.69439,               0.001,                   0,                 0.1,             0.52331,                   0,                   0,                   2
          0.00019934,            0.010324,          0.00010308,          2.0187e-05,          0.00031629,           0.0038312,          0.00017246,          2.0777e-05,             0.47588,             0.41791,           0.0052818,            0.011287,                 0.1,             0.04529,                 0.6,               0.001,             0.00658,             0.00101,                0.01,                 0.2,                 0.2,                   2,             0.77271,                 0.5,                 0.1,                   2,                   1,                 0.1,                 0.9,             0.20879,                   4,                   0,              0.0153,             0.69439,               0.001,                   0,                 0.1,             0.52331,                   0,                   0,                   2

I see first four columns to be train/box_loss, train/seg_loss, train/obj_loss, train/cls_loss.

Q2: In the plot_evolve function inside utils We see we are trying to plot from index 7 onwards but based on the csv above the l0 (intial learning rate) index is 19 onwards so is it something designed for object detection and not for segmenation+detection

def plot_evolve(evolve_csv='path/to/evolve.csv'):  # from utils.plots import *; plot_evolve()
    # Plot evolve.csv hyp evolution results
    evolve_csv = Path(evolve_csv)
    data = pd.read_csv(evolve_csv)
    keys = [x.strip() for x in data.columns]
    x = data.values
    f = fitness(x)
    j = np.argmax(f)  # max fitness index
    plt.figure(figsize=(10, 12), tight_layout=True)
    matplotlib.rc('font', **{'size': 8})
    print(f'Best results from row {j} of {evolve_csv}:')
    for i, k in enumerate(keys[7:]):
        v = x[:, 7 + i]
        mu = v[j]  # best single result
        plt.subplot(6, 5, i + 1)
        plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
        plt.plot(mu, f.max(), 'k+', markersize=15)
        plt.title(f'{k} = {mu:.3g}', fontdict={'size': 9})  # limit to 40 characters
        if i % 5 != 0:
            plt.yticks([])
        print(f'{k:>15}: {mu:.3g}')
    f = evolve_csv.with_suffix('.png')  # filename
    plt.savefig(f, dpi=200)
    plt.close()
    print(f'Saved {f}')

Also when I try running this code without index change (keeping 7 instead of 19) with the evolve.csv file it error out because in subplots we specify to include 30 subplots 5*6 but we get more than 30 and and will include more than 30 hyperparams.

Q3: I didn't understand why there are duplicate records for every evolution entry and also why we have NaN and nan entries(refer to csv attached)?

Additional

No response

github-actions[bot] commented 1 year ago

👋 Hello @iamprakhargupta, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug it.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our Tips for Best Training Results.

Requirements

Python>=3.7.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

YOLOv5 CI

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training, validation, inference, export and benchmarks on macOS, Windows, and Ubuntu every 24 hours and on every commit.

Introducing YOLOv8 🚀

We're excited to announce the launch of our latest state-of-the-art (SOTA) object detection model for 2023 - YOLOv8 🚀!

Designed to be fast, accurate, and easy to use, YOLOv8 is an ideal choice for a wide range of object detection, image segmentation and image classification tasks. With YOLOv8, you'll be able to quickly and accurately detect objects in real-time, streamline your workflows, and achieve new levels of accuracy in your projects.

Check out our YOLOv8 Docs for details and get started with:

pip install ultralytics
iamprakhargupta commented 12 months ago

@glenn-jocher sorry for tagging you but are we sure that hyper parameter evolution is supported for segmentation as well

glenn-jocher commented 12 months ago

@iamprakhargupta hyperparameter Evolution in YOLOv5 is primarily designed for object detection tasks. While YOLOv5 itself does not include built-in support for segmentation tasks, you can still adapt the hyperparameter evolution technique for segmentation by modifying the training pipeline and loss functions.

For segmentation tasks, you might consider exploring other architectures specifically designed for this purpose, such as UNet or Deeplab, which have been widely used for image segmentation and provide better compatibility with hyperparameter evolution techniques.

Note that adapting hyperparameter evolution for segmentation can be a complex process and may require significant modifications to the codebase. It's always recommended to consult the documentation and resources available for the specific segmentation architecture you are using.

Feel free to reach out if you have any further questions or need assistance with implementing segmentation tasks in YOLOv5!

github-actions[bot] commented 11 months ago

👋 Hello there! We wanted to give you a friendly reminder that this issue has not had any recent activity and may be closed soon, but don't worry - you can always reopen it if needed. If you still have any questions or concerns, please feel free to let us know how we can help.

For additional resources and information, please see the links below:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLO 🚀 and Vision AI ⭐