{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import imageio\nimport shutil\nimport random\nfrom tqdm.auto import tqdm\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_path = '../input/global-wheat-detection/train/'\n\ndef display_img(image_idx):\n    img = imageio.imread(f'{img_path}/{image_idx}.jpg')\n    plt.imshow(img)\n    \n\ndef display_all_locations():\n\n    for location in set(df['combined_src']):\n        loc_mask = df['combined_src'] == location\n\n        plt.figure(figsize=(20, 15))\n        plt.suptitle(location)\n        r, c = 10, 10\n        for i in range(r*c):\n            rand_idx = random.randint(0, df[loc_mask].shape[0]-1)\n            plt.subplot(r, c, i+1)\n            display_img(df[loc_mask].iloc[rand_idx, 0])\n\n        # break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"orig_df = pd.read_csv('../input/global-wheat-detection/train.csv')\norig_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"orig_df['source'].hist()\norig_df['source'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"As we can see the arvalis dataset was collected in multiple sets. Let's try to combine all sources into one.","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"orig_df['combined_src'] = orig_df['source'].apply(lambda x: x.split('_')[0])\norig_df['combined_src'].hist()\norig_df['combined_src'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = orig_df.copy()\n\nbboxs = np.stack(df['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))\nfor i, column in enumerate(['x', 'y', 'w', 'h']):\n    df[column] = bboxs[:,i]\n    \ndf.drop(columns=['bbox'], inplace=True)\ndf['x_center'] = df['x'] + df['w']/2\ndf['y_center'] = df['y'] + df['h']/2\ndf['classes'] = 0\n\nindex = list(set(df.image_id))\n\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We use GroupKFold on the combined_src as groups to ensure that no two splits contain elements from the same group.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split, GroupKFold\nfolds_info = []\n\nfor fold_idx, (train_idx, valid_idx) in enumerate(GroupKFold(4).split(df, groups=df.combined_src)):\n    train_df = df.iloc[train_idx].reset_index(drop=True)\n    valid_df = df.iloc[valid_idx].reset_index(drop=True)\n\n    plt.figure()\n    train_df['combined_src'].hist()\n    valid_df['combined_src'].hist()\n    name = \"valid_on_\" + \"_\".join(list(set(valid_df['combined_src'])))\n    plt.title(name)\n\n    print(name, train_idx.shape, valid_idx.shape, f\"ratio: {valid_idx.shape[0] / train_idx.shape[0] * 100:.2f}\")\n    folds_info.append(\n        [train_df, valid_df, name]\n    )\n    # break","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"RRES seems to have a good 85%-15% split. So we can use RRES as the validation set and the othes as the training set.\nLet's see how do the samples from each location look.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"display_all_locations()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def dump(mdf, labels_path, images_path):\n\n    for img_idx, mini in tqdm(mdf.groupby('image_id')):\n        img_loc = f'{img_path}/{img_idx}.jpg'\n\n        shutil.copy(\n            img_loc,\n            f'{images_path}/{img_idx}.jpg'\n        )\n        \n        with open(f'{labels_path}/{img_idx}.txt', 'w+') as f:\n            row = mini[['classes','x_center','y_center','w','h']].astype(float).values\n            row = row/1024\n            row = row.astype(str)\n            for j in range(len(row)):\n                text = ' '.join(row[j])\n                f.write(text)\n                f.write(\"\\n\")\n        # break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def save(train_df, valid_df, savename):\n    outpath = \"/kaggle/working/files/\"\n    train_path_labels = f'{outpath}/train/labels/'\n    train_path_images = f'{outpath}/train/images/'\n    valid_path_labels = f'{outpath}/valid/labels/'\n    valid_path_images = f'{outpath}/valid/images/'\n\n    for p in [train_path_labels, train_path_images, valid_path_labels, valid_path_images]:\n        os.makedirs(p, exist_ok=True)\n        \n    dump(train_df, train_path_labels, train_path_images)\n    dump(valid_df, valid_path_labels, valid_path_images)\n    \n    os.system(f'zip -rmq {savename}.zip files')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\nfor (train_df, valid_df, savename) in folds_info:\n    save(train_df, valid_df, savename)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls -hl","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}