{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"%%time\n\nprint(\"this will take around 9 mins\")\n# install dependencies: (use cu101 because colab has CUDA 10.1)\n# !pip install -U torch==1.7.0+cu101 torchvision==0.6.1+cu101 -f https://download.pytorch.org/whl/torch_stable.html\n\n# install mmcv-full thus we could use CUDA operators\n!pip install mmcv-full","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ls","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm -rf mmdetection\n!git clone --branch v2.7.0 https://github.com/open-mmlab/mmdetection.git\n%cd mmdetection\n\n!pip install -e .\n\n# install Pillow 7.0.0 back in order to avoid bug in colab\n!pip install Pillow==7.0.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Check Pytorch installation\nimport torch, torchvision\nprint(torch.__version__, torch.cuda.is_available())\n\n# Check MMDetection installation\nimport mmdet\nprint(mmdet.__version__)\n\n# Check mmcv installation\nfrom mmcv.ops import get_compiling_cuda_version, get_compiler_version\nprint(get_compiling_cuda_version())\nprint(get_compiler_version())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ls","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!mkdir checkpoints\n!wget -c http://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth \\\n      -O checkpoints/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from mmdet.apis import inference_detector, init_detector, show_result_pyplot\n\n# Choose to use a config and initialize the detector\nconfig = 'configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco.py'\n# Setup a checkpoint file to load\ncheckpoint = 'checkpoints/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth'\n# initialize the detector\nmodel = init_detector(config, checkpoint, device='cuda:0')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Use the detector to do inference\nimg = 'demo/demo.jpg'\nresult = inference_detector(model, img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Let's plot the result\nshow_result_pyplot(model, img, result, score_thr=0.3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from mmcv import Config\ncfg = Config.fromfile('./configs/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_1x_coco.py')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from mmdet.apis import set_random_seed\ncfg.model=dict(\n    type='CascadeRCNN',\n    #pretrained='open-mmlab://resnext101_64x4d',\n    pretrained=None,\n    backbone=dict(\n        type='ResNeXt',\n        depth=101,\n        num_stages=4,\n        out_indices=(0, 1, 2, 3),\n        frozen_stages=1,\n        norm_cfg=dict(type='SyncBN', requires_grad=True),\n        # norm_cfg = dict(type='GN', num_groups=32, requires_grad=True),  # not working\n        norm_eval=True,\n        style='pytorch',\n        groups=64,\n        base_width=4,\n        # dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),\n        # stage_with_dcn=(False, True, True, True)\n        ),\n    neck=dict(\n        type='FPN',\n        in_channels=[256, 512, 1024, 2048],\n        out_channels=256,\n        num_outs=5),\n    rpn_head=dict(\n        type='RPNHead',\n        in_channels=256,\n        feat_channels=256,\n        anchor_generator=dict(\n            type='AnchorGenerator',\n            scales=[8],\n            ratios=[0.5, 1.0, 2.0, 3.0, 5.0],\n            strides=[4, 8, 16, 32, 64]),\n        bbox_coder=dict(\n            type='DeltaXYWHBBoxCoder',\n            target_means=[0.0, 0.0, 0.0, 0.0],\n            target_stds=[1.0, 1.0, 1.0, 1.0]),\n        loss_cls=dict(\n            type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),\n        loss_bbox=dict(\n            type='SmoothL1Loss', beta=0.1111111111111111, loss_weight=1.0)),\n        #reg_decoded_bbox=True,\n        #loss_bbox=dict(type='GIoULoss', loss_weight=5.0)),\n    roi_head=dict(\n        type='CascadeRoIHead',\n        num_stages=3,\n        stage_loss_weights=[1, 0.5, 0.25],\n        bbox_roi_extractor=dict(\n            type='SingleRoIExtractor',\n            roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),\n            out_channels=256,\n            featmap_strides=[4, 8, 16, 32]),\n        bbox_head=[\n            dict(\n                type='Shared2FCBBoxHead',\n                in_channels=256,\n                fc_out_channels=1024,\n                roi_feat_size=7,\n                num_classes=14,\n                bbox_coder=dict(\n                    type='DeltaXYWHBBoxCoder',\n                    target_means=[0.0, 0.0, 0.0, 0.0],\n                    target_stds=[0.1, 0.1, 0.2, 0.2]),\n                reg_class_agnostic=True,\n                loss_cls=dict(\n                    type='CrossEntropyLoss',\n                    use_sigmoid=False,\n                    loss_weight=1.0),\n                loss_bbox=dict(type='SmoothL1Loss', beta=1.0,\n                               loss_weight=1.0)),\n                #reg_decoded_bbox=True,\n                #loss_bbox=dict(type='GIoULoss', loss_weight=5.0)),\n            dict(\n                type='Shared2FCBBoxHead',\n                in_channels=256,\n                fc_out_channels=1024,\n                roi_feat_size=7,\n                num_classes=14,\n                bbox_coder=dict(\n                    type='DeltaXYWHBBoxCoder',\n                    target_means=[0.0, 0.0, 0.0, 0.0],\n                    target_stds=[0.05, 0.05, 0.1, 0.1]),\n                reg_class_agnostic=True,\n                loss_cls=dict(\n                    type='CrossEntropyLoss',\n                    use_sigmoid=False,\n                    loss_weight=1.0),\n                loss_bbox=dict(type='SmoothL1Loss', beta=1.0,\n                               loss_weight=1.0)),\n                #reg_decoded_bbox=True,\n                #loss_bbox=dict(type='GIoULoss', loss_weight=5.0)),\n            dict(\n                type='Shared2FCBBoxHead',\n                in_channels=256,\n                fc_out_channels=1024,\n                roi_feat_size=7,\n                num_classes=14,\n                bbox_coder=dict(\n                    type='DeltaXYWHBBoxCoder',\n                    target_means=[0.0, 0.0, 0.0, 0.0],\n                    target_stds=[0.033, 0.033, 0.067, 0.067]),\n                reg_class_agnostic=True,\n                loss_cls=dict(\n                    type='CrossEntropyLoss',\n                    use_sigmoid=False,\n                    loss_weight=1.0),\n                loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))\n                #reg_decoded_bbox=True,\n                #loss_bbox=dict(type='GIoULoss', loss_weight=5.0))\n        ]))\n\ncfg.train_cfg = dict(\n    rpn=dict(\n        assigner=dict(\n            type='MaxIoUAssigner',\n            pos_iou_thr=0.7,\n            neg_iou_thr=0.3,\n            min_pos_iou=0.3,\n            match_low_quality=True,\n            ignore_iof_thr=-1),\n        sampler=dict(\n            type='RandomSampler',\n            num=256,\n            pos_fraction=0.5,\n            neg_pos_ub=-1,\n            add_gt_as_proposals=False),\n        allowed_border=0,\n        pos_weight=-1,\n        debug=False),\n    rpn_proposal=dict(\n        nms_across_levels=False,\n        nms_pre=2000,\n        nms_post=2000,\n        max_num=2000,\n        nms_thr=0.7,\n        min_bbox_size=0),\n    rcnn=[\n        dict(\n            assigner=dict(\n                type='MaxIoUAssigner',\n                pos_iou_thr=0.5,\n                neg_iou_thr=0.5,\n                min_pos_iou=0.5,\n                match_low_quality=False,\n                ignore_iof_thr=-1),\n            sampler=dict(\n                _delete_=True,\n                type='CombinedSampler',\n                num=512,\n                pos_fraction=0.25,\n                add_gt_as_proposals=True,\n                pos_sampler=dict(type='InstanceBalancedPosSampler'),\n                neg_sampler=dict(\n                    type='IoUBalancedNegSampler',\n                    floor_thr=-1,\n                    floor_fraction=0,\n                    num_bins=3)),\n                pos_weight=-1,\n                debug=False),\n        dict(\n            assigner=dict(\n                type='MaxIoUAssigner',\n                pos_iou_thr=0.6,\n                neg_iou_thr=0.6,\n                min_pos_iou=0.6,\n                match_low_quality=False,\n                ignore_iof_thr=-1),\n            sampler=dict(\n                _delete_=True,\n                type='CombinedSampler',\n                num=512,\n                pos_fraction=0.25,\n                add_gt_as_proposals=True,\n                pos_sampler=dict(type='InstanceBalancedPosSampler'),\n                neg_sampler=dict(\n                    type='IoUBalancedNegSampler',\n                    floor_thr=-1,\n                    floor_fraction=0,\n                    num_bins=3)),\n                pos_weight=-1,\n                debug=False),\n        dict(\n            assigner=dict(\n                type='MaxIoUAssigner',\n                pos_iou_thr=0.7,\n                neg_iou_thr=0.7,\n                min_pos_iou=0.7,\n                match_low_quality=False,\n                ignore_iof_thr=-1),\n            sampler=dict(\n                _delete_=True,\n                type='CombinedSampler',\n                num=512,\n                pos_fraction=0.25,\n                add_gt_as_proposals=True,\n                pos_sampler=dict(type='InstanceBalancedPosSampler'),\n                neg_sampler=dict(\n                    type='IoUBalancedNegSampler',\n                    floor_thr=-1,\n                    floor_fraction=0,\n                    num_bins=3)),\n                pos_weight=-1,\n                debug=False)\n    ])\n\ncfg.test_cfg = dict(\n    rpn=dict(\n        nms_across_levels=False,\n        nms_pre=1000,\n        nms_post=1000,\n        max_num=1000,\n        nms_thr=0.7,\n        min_bbox_size=0),\n    rcnn=dict(\n        score_thr=0.01,\n        nms=dict(type='nms', iou_threshold=0.5),\n        max_per_img=300))\ndataset_type = 'CocoDataset'\ndata_root = 'data/coco/'\nimg_norm_cfg = dict(\n    mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)\nalbu_train_transforms = [\n    dict(type='RandomRotate90', p=0.5),\n    #dict(type='CLAHE', p=0.5),\n    #dict(type='InvertImg', p=0.5),\n    ]\ncfg.train_pipeline = [\n    dict(type='LoadImageFromFile'),\n    dict(type='LoadAnnotations', with_bbox=True, with_mask=False),\n    dict(type='Resize',img_scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736),(1333, 768), (1333, 800)],multiscale_mode='value',keep_ratio=True),\n    dict(type='RandomFlip', flip_ratio=0.5),\n    #dict(type='RandomFlip', flip_ratio=0.5, direction='horizontal'),\n    #dict(type='RandomFlip', flip_ratio=0.5, direction='vertical'),\n    #dict(type='BBoxJitter', min=0.9, max=1.1),\n    #dict(type='MixUp', p=0.5, lambd=0.5),\n    dict(\n        type='Normalize',\n        mean=[123.675, 116.28, 103.53],\n        std=[58.395, 57.12, 57.375],\n        to_rgb=True),\n    dict(\n        type='Albu',\n        transforms=albu_train_transforms,\n        bbox_params=dict(\n        type='BboxParams',\n        format='pascal_voc',\n        label_fields=['gt_labels'],\n        min_visibility=0.0,\n        filter_lost_elements=True),\n        keymap=dict(img='image', gt_bboxes='bboxes'),\n        update_pad_shape=False,\n        skip_img_without_anno=True),\n    dict(type='Pad', size_divisor=32),\n    dict(type='DefaultFormatBundle'),\n    dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])\n]\ncfg.test_pipeline = [\n    dict(type='LoadImageFromFile'),\n    dict(\n        type='MultiScaleFlipAug',\n        img_scale=(1333, 800),\n        flip=False,\n        transforms=[\n            dict(type='Resize', keep_ratio=True),\n            dict(type='RandomFlip'),\n            dict(\n                type='Normalize',\n                mean=[123.675, 116.28, 103.53],\n                std=[58.395, 57.12, 57.375],\n                to_rgb=True),\n            dict(type='Pad', size_divisor=32),\n            dict(type='ImageToTensor', keys=['img']),\n            dict(type='Collect', keys=['img'])\n        ])\n]\ncfg.data = dict(\n    samples_per_gpu=2,\t# 2 gpus, real batch_size=6\n    workers_per_gpu=2,\n    train=dict(\n        type='RepeatDataset',\n        times=3,\n        dataset=dict(\n            type='CocoDataset',\n            ann_file='../../input/vinbigdata-coco-dataset-with-wbf-3x-downscaled/vinbigdata-coco-dataset-with-wbf-3x-downscaled/train_annotations.json',\n            img_prefix='../../input/vinbigdata-coco-dataset-with-wbf-3x-downscaled/vinbigdata-coco-dataset-with-wbf-3x-downscaled/',\n            pipeline=cfg.train_pipeline,\n            classes=('Aortic_enlargement', 'Atelectasis', 'Calcification',\n                 'Cardiomegaly', 'Consolidation', 'ILD', 'Infiltration',\n                 'Lung_Opacity', 'Nodule/Mass', 'Other_lesion',\n                 'Pleural_effusion', 'Pleural_thickening', 'Pneumothorax',\n                 'Pulmonary_fibrosis'))),\n    val=dict(\n        type='CocoDataset',\n        ann_file='../../input/vinbigdata-coco-dataset-with-wbf-3x-downscaled/vinbigdata-coco-dataset-with-wbf-3x-downscaled/val_annotations.json',\n        img_prefix='../../input/vinbigdata-coco-dataset-with-wbf-3x-downscaled/vinbigdata-coco-dataset-with-wbf-3x-downscaled/',\n        pipeline=cfg.test_pipeline,\n        classes=('Aortic_enlargement', 'Atelectasis', 'Calcification',\n                 'Cardiomegaly', 'Consolidation', 'ILD', 'Infiltration',\n                 'Lung_Opacity', 'Nodule/Mass', 'Other_lesion',\n                 'Pleural_effusion', 'Pleural_thickening', 'Pneumothorax',\n                 'Pulmonary_fibrosis')),\n    test=dict(\n        type='CocoDataset',\n        ann_file='../../input/vinbigdata-coco-dataset-with-wbf-3x-downscaled/vinbigdata-coco-dataset-with-wbf-3x-downscaled/val_annotations.json',\n        img_prefix='../../input/vinbigdata-coco-dataset-with-wbf-3x-downscaled/vinbigdata-coco-dataset-with-wbf-3x-downscaled/',\n        pipeline=cfg.test_pipeline)\n    )\ncfg.evaluation = dict(interval=1, metric='bbox')\ncfg.optimizer = dict(type='SGD', lr=0.0025, momentum=0.9, weight_decay=0.0001)\ncfg.optimizer_config = dict(grad_clip=None)\ncfg.lr_config = dict(\n    policy='step',\n    warmup='linear',\n    warmup_iters=500,\n    warmup_ratio=0.001,\n    step=[8, 11])\ncfg.total_epochs = 12\ncfg.checkpoint_config = dict(interval=1)\ncfg.log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook'),\n    dict(type='TensorboardLoggerHook')])\n\n# Set seed thus the results are more reproducible\ncfg.seed = 0\nset_random_seed(0, deterministic=False)\ncfg.gpu_ids = range(1)\n\n# we can use here mask_rcnn.\ncfg.load_from = None\ncfg.work_dir = \"../vinbig_output\"\n\n# One Epoch takes around 18 mins\ncfg.total_epochs = 12\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'Config:\\n{cfg.pretty_text}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# the dataset has been taken : https://www.kaggle.com/sreevishnudamodaran/vinbigdata-fusing-bboxes-coco-dataset\nimport os\nos.listdir(\"../../input/vinbigdata-coco-dataset-with-wbf-3x-downscaled/vinbigdata-coco-dataset-with-wbf-3x-downscaled\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# for saving checkpoint and plots\nimport os\nos.makedirs('../vinbig_output')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tqdm.notebook import tqdm\nimport pandas as pd\nimport numpy as np\n#不用科学计数法表示\nnp.set_printoptions(suppress=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"keys_coco = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train',\n             'truck', 'boat', 'traffic_light', 'fire_hydrant', 'stop_sign',\n             'parking_meter', 'bench')\nvalues_vinbigdata = (\"Aortic_enlargement\", \"Atelectasis\", \"Calcification\", \"Cardiomegaly\", \n          \"Consolidation\", \"ILD\", \"Infiltration\", \"Lung_Opacity\", \"Nodule/Mass\", \n          \"Other_lesion\", \"Pleural_effusion\", \"Pleural_thickening\", \"Pneumothorax\", \"Pulmonary_fibrosis\")\nnames_coco_to_vbg = dict(zip(keys_coco, values_vinbigdata))\nprint(names_coco_to_vbg)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def generate_id(result):\n    i = 0\n    id_result = []\n    id_name_result = []\n    for box_class in result:\n#         print(box_class)\n        if not box_class.shape[0] == 0:\n            for index in range(0,box_class.shape[0]):\n#                 print(values_vinbigdata[i])\n#                 print(keys_coco[i])\n                id_result.append(i)\n                id_name_result.append(values_vinbigdata[i])\n        i+=1\n#     print(id_result)\n#     print(id_name_result)\n    id_result = np.array(id_result).reshape((len(id_result),1))\n    \n    return id_result","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def filter_condition_with_list(condition_list, will_filter_list):\n    filtered_list=[]\n    for con_, wf_ in zip(condition_list, will_filter_list):\n        if not con_:\n            filtered_list.append(wf_)\n    return filtered_list    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from mmdet.apis import inference_detector, init_detector, show_result_pyplot\n\n# Choose to use a config and initialize the detector\nconfig = cfg\n# Setup a checkpoint file to load\ncheckpoint = '/kaggle/input/mmdet-ca-fasterrcnn/vinbig_output/epoch_5.pth'\n# initialize the detector\nmodel = init_detector(config, checkpoint, device='cuda:0')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#测试图片的大小\ndim = 512 #1024, 256, 'original'\n#测试图片位置及文件表\ntest_dir = f'/kaggle/input/vinbigdata-{dim}-image-dataset/vinbigdata/test' #其实没用到\ntest_df = pd.read_csv(f'/kaggle/input/vinbigdata-{dim}-image-dataset/vinbigdata/test.csv')\n#测试的图片序号\nimg_id = test_df['image_id'].values\nprint(img_id)\n#阈值\nscore_thr = 0.15","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# print(test_df['image_id'].values.tolist()[0:3])\nsub_single_dic_fff= {}\n# id_int = []\n# {img_id: sub_single_boxes}\n# Use the detector to do inference\nfor img_id in tqdm(test_df['image_id'].values):\n    img = '/kaggle/input/vinbigdata-512-image-dataset/vinbigdata/test/{}.png'.format(img_id)\n    result = inference_detector(model, img)\n    a = np.vstack(result)[:,[4,0,1,2,3]] #构造一张图片的result ：类别, xmin, ymin, xmax, ymax\n    a = np.concatenate((generate_id(result), a) ,axis=1) # 在第一列添加id序号\n#     print(a)\n#     根据阈值删掉小概率检测框\n    thr_result = a[:,1] > score_thr\n    filtered_list = filter_condition_with_list(thr_result, list(range(0,len(thr_result))))\n    a = np.delete(a, filtered_list, axis=0)\n#     print(a)\n#     转换成列表，方便后续转dataframe写进csv结果\n    df = pd.DataFrame(a, index=None, columns = ['id', 'prob','x_min','y_min','x_max','y_max'])\n    df['width'] = dim\n    df['height'] = dim\n    df['image_id'] = img_id\n#     print(df)\n#     做归一化，(把左上右下四个点的坐标，计算成相对坐标)\n    df['x_min'] = df.apply(lambda row: (row.x_min)/row.width, axis =1)\n    df['y_min'] = df.apply(lambda row: (row.y_min)/row.height, axis =1)\n    df['x_max'] = df.apply(lambda row: (row.x_max)/row.width, axis =1)\n    df['y_max'] = df.apply(lambda row: (row.y_max)/row.height, axis =1)\n#     合并test_df和df，得到带有实测图片宽高的表格\n    result_df = pd.merge(df,test_df,on='image_id',how='left')\n#     做归一化，(把左上右下四个点的坐标，计算成相对坐标)\n    result_df['x_min'] = result_df.apply(lambda row: (row.x_min)*row.width_y, axis =1)\n    result_df['y_min'] = result_df.apply(lambda row: (row.y_min)*row.height_y, axis =1)\n    result_df['x_max'] = result_df.apply(lambda row: (row.x_max)*row.width_y, axis =1)\n    result_df['y_max'] = result_df.apply(lambda row: (row.y_max)*row.height_y, axis =1)\n#     result_df['id'] = result_df.apply(lambda row: int(row.id), axis =1)\n#     id_int.extend(result_df['id'].values.astype(dtype=int).flatten().tolist())\n    sub_single_boxes = result_df[['id','prob','x_min','y_min','x_max','y_max']].values.flatten().tolist()\n    for _,x in enumerate(sub_single_boxes):\n        if x >=1 or x==0:\n            sub_single_boxes[_] = int(x)\n        else:\n            sub_single_boxes[_] = round(x,1)\n    sub_single_dic_fff[img_id] = str(sub_single_boxes).strip('[').strip(']').replace(',',' ')\n# print(id_int)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(sub_single_dic_fff)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_result = pd.DataFrame.from_dict(sub_single_dic_fff, orient='index', columns=['PredictionString'])\nsub_result = sub_result.reset_index().rename(columns = {'index':'image_id'})\n# sub_result['id'] = id_int\nprint(sub_result)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_result = sub_result.fillna('14 1 0 0 1 1')\n##小bug 无法运行","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_result.to_csv('/kaggle/working/submission.csv',index = False)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}