python - 使用 coco 数据格式 json 文件进行交叉验证

标签 python json machine-learning cross-validation semantic-segmentation

我是一名 ML 学习新手,正在尝试使用 COCO 数据格式 json 和 Google Drive 上的大量图像在 Google Colab 上进行语义图像分割。

更新

我借用了这段代码作为起点。所以我在 colab 上的代码几乎是这样的。 https://github.com/akTwelve/tutorials/blob/master/mask_rcnn/MaskRCNN_TrainAndInference.ipynb

/更新

每次收到新的注释数据时,我都会将导出的 json 文件拆分为 2 个 json(以 80/20 的比例进行训练/验证)。但这变得很累,因为我在一个文件中有超过 1000 个注释,并且我使用 VS code 的替换功能手动完成它。

是否有更好的方法在 Google Colab 上以编程方式执行此操作?

所以我喜欢做的是旋转注释数据,而不需要手动吐出 json 文件。

假设,我的 google 驱动器上的一个 json 文件中有 1000 个注释,我想使用 1-800 个注释进行训练,使用 801-1000 个注释来验证第一个训练 session ,然后用于下一个训练 session 我想使用 210-1000 个注释进行训练,使用 1-200 个注释进行验证。就像在colab上的代码中选择json中的一部分数据一样。

或者,如果我可以在一次训练期间轮换数据(K-Fold 交叉验证?),那就更好了,但我不知道如何做到这一点。

这是我在 colab 上的部分代码。

加载json文件

dataset_train = CocoLikeDataset()
dataset_train.load_data('PATH_TO_TRAIN_JSON', 'PATH_TO_IMAGES')
dataset_train.prepare()

dataset_val = CocoLikeDataset()
dataset_val.load_data('PATH_TO_VALIDATE_JSON', 'PATH_TO_IMAGES')
dataset_val.prepare()

初始化模型

model = modellib.MaskRCNN(mode="training", config=config, model_dir=MODEL_DIR)

init_with = "coco"

if init_with == "imagenet":
    model.load_weights(model.get_imagenet_weights(), by_name=True)
elif init_with == "coco":
    model.load_weights(COCO_MODEL_PATH, by_name=True,
                       exclude=["mrcnn_class_logits", "mrcnn_bbox_fc", 
                                "mrcnn_bbox", "mrcnn_mask"])
elif init_with == "last":
    model.load_weights(model.find_last(), by_name=True)

火车

start_train = time.time()
model.train(dataset_train, dataset_val, 
            learning_rate=config.LEARNING_RATE, 
            epochs=30, 
            layers='heads')
end_train = time.time()
minutes = round((end_train - start_train) / 60, 2)
print(f'Training took {minutes} minutes')

验证

start_train = time.time()
model.train(dataset_train, dataset_val, 
            learning_rate=config.LEARNING_RATE / 10,
            epochs=10, 
            layers="all")
end_train = time.time()
minutes = round((end_train - start_train) / 60, 2)
print(f'Training took {minutes} minutes')

json

{
  "info": {
    "year": 2020,
    "version": "1",
    "description": "Exported using VGG Image Annotator (http://www.robots.ox.ac.uk/~vgg/software/via/)",
    "contributor": "",
    "url": "http://www.robots.ox.ac.uk/~vgg/software/via/",
    "date_created": "Tue Jan 21 2020 16:18:14"
  },
  "images": [
    {
      "id": 0,
      "width": 2880,
      "height": 2160,
      "file_name": "sample01.jpg",
      "license": 1,
      "flickr_url": "sample01.jpg",
      "coco_url": "sample01.jpg",
      "date_captured": ""
    }
  ],
   "annotations": [
    {
      "id": 0,
      "image_id": "0",
      "category_id": 1,
      "segmentation": [
        588,
        783,
        595,
        844,
        607,
        687,
        620,
        703,
        595,
        722,
        582,
        761
      ],
      "area": 108199,
      "bbox": [
        582,
        687,
        287,
        377
      ],
      "iscrowd": 0
    }
  ],
  "licenses": [
    {
      "id": 1,
      "name": "Unknown",
      "url": ""
    }
  ],
  "categories": [
    {
      "id": 1,
      "name": "nail",
      "supercategory": "type"
    }
  ]
}

仅供引用,我的工作流程就像

  1. 使用 VIA 注释工具标记图像

  2. 以coco格式json导出注释

  3. 修改 json 并保存到我的 Google 云端硬盘

  4. 在colab上加载json并开始训练

最佳答案

sklearn 库中有一个非常好的实用函数,可以完全满足您的需求。它的名字叫train_test_split .

现在,很难理解您的数据结构是什么,但我假设这段代码:

dataset_train = CocoLikeDataset()
dataset_train.load_data('PATH_TO_TRAIN_JSON', 'PATH_TO_IMAGES')
dataset_train.prepare()

使用某种图像数组或图像路径数组填充dataset_train。 sklearn 的 train_test_split 函数能够接受 pandas DataFrame 以及 numpy 数组。

我通常对 pandas DataFrames 非常满意,因此我建议您使用 pandas 函数 concat 将训练和验证数据合并到一个 DataFrame 中,然后创建一个随机数据在每个训练周期开始时使用 sklearn 函数 train_test_split 进行分割。它看起来像下面这样:

import pandas as pd
from sklearn.model_selection import train_test_split

# Convert the data into a DataFrame
master_df = pd.concat([pd.DataFrame(dataset_train), pd.DataFrame(dataset_val)], ignore_index=True)

# Separate out the data and targets DataFrames' (required by train_test_split)
data_df = master_df[['image_data_col_1','image_data_col_2','image_data_col_3']]
targets_df = master_df[['class_label']]

# Split the data into a random train/test (or train/val) split
data_train, data_val, targets_train, targets_val = train_test_split(data_df, targets_df, test_size=0.2)

# Training loop
# If the training function requires the targets to be present in the same DataFrame, you can do this before beginning training:
dataset_train_df = pd.concat([data_train, targets_train], axis=1)
dataset_val_df = pd.concat([data_val, targets_val], axis=1)
##################################
# Continue with training loop...
##################################

最后一点:理想情况下,您应该拥有三组 - 训练、测试和验证。因此,预先分离出一个测试集,然后在训练循环的每次迭代开始时执行train_test_split,以从剩余数据中获取训练验证分割。

关于python - 使用 coco 数据格式 json 文件进行交叉验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59851458/

相关文章:

python - 使补丁更大,用作 matplotlib 中的图例

javascript - typescript :无法从函数内部访问属性

json - 在 Play 2 中如何检查 JsValue 变量是否为 NULL?

python - Keras 输出层出现意外错误

python - 深度学习: save and load a universal machine model through different libraries

python - 精度比 gridsearchCV 低

python - Sphinx 'latin-1' 编解码器无法编码字符' - 想要使用 utf-8

python - 如何从 readline() 函数中去除字符串中的换行符?

python - 将图像转换为其他图像

c# - JSON 不反序列化