{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# This notebook is based [How To Create TFRecords](https://www.kaggle.com/cdeotte/how-to-create-tfrecords).","metadata":{}},{"cell_type":"markdown","source":"## imports","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport cv2","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:37.194653Z","iopub.execute_input":"2021-07-04T01:53:37.195002Z","iopub.status.idle":"2021-07-04T01:53:37.200173Z","shell.execute_reply.started":"2021-07-04T01:53:37.194973Z","shell.execute_reply":"2021-07-04T01:53:37.199134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Hyper parameters","metadata":{}},{"cell_type":"code","source":"DEBUG = False\nDEBUGT_NUM = 560\nSEED = 42\nFOLDS = 20\nN_FFT = 256\nversion = 5","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:37.222387Z","iopub.execute_input":"2021-07-04T01:53:37.22273Z","iopub.status.idle":"2021-07-04T01:53:37.227813Z","shell.execute_reply.started":"2021-07-04T01:53:37.222702Z","shell.execute_reply":"2021-07-04T01:53:37.226797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"VERS = 0\nVERE = 0\nif version==0:\n    VERS = 0\n    VERE = 1\nelif version==1:\n    VERS = 0\n    VERE = 5\nelif version==2:\n    VERS = 5\n    VERE = 10\nelif version==3:\n    VERS = 10\n    VERE = 15\nelif version==4:\n    VERS = 15\n    VERE = 20\nelif version==5:\n    VERS = 0\n    VERE = 20","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:37.253871Z","iopub.execute_input":"2021-07-04T01:53:37.254208Z","iopub.status.idle":"2021-07-04T01:53:37.260019Z","shell.execute_reply.started":"2021-07-04T01:53:37.254179Z","shell.execute_reply":"2021-07-04T01:53:37.259042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## read DFs","metadata":{}},{"cell_type":"code","source":"train_df = pd.read_csv('../input/g2net-gravitational-wave-detection/training_labels.csv')\ntest_df = pd.read_csv('../input/g2net-gravitational-wave-detection/sample_submission.csv')\n\ndef get_train_file_path(image_id):\n    return \"../input/g2net-gravitational-wave-detection/train/{}/{}/{}/{}.npy\".format(\n        image_id[0], image_id[1], image_id[2], image_id)\n\ndef get_test_file_path(image_id):\n    return \"../input/g2net-gravitational-wave-detection/test/{}/{}/{}/{}.npy\".format(\n        image_id[0], image_id[1], image_id[2], image_id)\n\ntrain_df['file_path'] = train_df['id'].apply(get_train_file_path)\ntest_df['file_path'] = test_df['id'].apply(get_test_file_path)\n\ndisplay(train_df.head())\ndisplay(test_df.head())","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:37.293062Z","iopub.execute_input":"2021-07-04T01:53:37.293406Z","iopub.status.idle":"2021-07-04T01:53:38.424897Z","shell.execute_reply.started":"2021-07-04T01:53:37.293377Z","shell.execute_reply":"2021-07-04T01:53:38.423986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if DEBUG:\n    train_df = train_df[:DEBUGT_NUM]\n    test_df = test_df[:DEBUGT_NUM]","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:38.426325Z","iopub.execute_input":"2021-07-04T01:53:38.426633Z","iopub.status.idle":"2021-07-04T01:53:38.431454Z","shell.execute_reply.started":"2021-07-04T01:53:38.426605Z","shell.execute_reply":"2021-07-04T01:53:38.430432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"LEN_TRAINS = len(train_df)\nLEN_TESTS = len(test_df)\nLEN_TRAINS, LEN_TESTS","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:38.433596Z","iopub.execute_input":"2021-07-04T01:53:38.434066Z","iopub.status.idle":"2021-07-04T01:53:38.446009Z","shell.execute_reply.started":"2021-07-04T01:53:38.434022Z","shell.execute_reply":"2021-07-04T01:53:38.445096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## load stats","metadata":{}},{"cell_type":"code","source":"train_mean = np.load('../input/g2net-stat/train_mean.npy')\ntrain_std = np.load('../input/g2net-stat/train_std.npy')\nnp.min(train_mean), np.max(train_mean), np.min(train_std), np.max(train_std)","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:38.447392Z","iopub.execute_input":"2021-07-04T01:53:38.447661Z","iopub.status.idle":"2021-07-04T01:53:38.463234Z","shell.execute_reply.started":"2021-07-04T01:53:38.447635Z","shell.execute_reply":"2021-07-04T01:53:38.462191Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_mean = np.load('../input/g2net-stat/test_mean.npy')\ntest_std = np.load('../input/g2net-stat/test_std.npy')\nnp.min(test_mean), np.max(test_mean), np.min(test_std), np.max(test_std)","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:38.464877Z","iopub.execute_input":"2021-07-04T01:53:38.465395Z","iopub.status.idle":"2021-07-04T01:53:38.476372Z","shell.execute_reply.started":"2021-07-04T01:53:38.46535Z","shell.execute_reply":"2021-07-04T01:53:38.475551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Quick EDA","metadata":{}},{"cell_type":"code","source":"def visualize_sample(\n    x, \n    target=2, \n    _id='sample',\n    colors=(\"black\", \"red\", \"green\"), \n    signal_names=(\"LIGO Hanford\", \"LIGO Livingston\", \"Virgo\")\n):\n    \n    plt.figure(figsize=(16, 7))\n    for i in range(3):\n        plt.subplot(4, 1, i + 1)\n        plt.plot(x[i], color=colors[i])\n        plt.legend([signal_names[i]], fontsize=12, loc=\"lower right\")\n        \n        plt.subplot(4, 1, 4)\n        plt.plot(x[i], color=colors[i])\n    \n    plt.subplot(4, 1, 4)\n    plt.legend(signal_names, fontsize=12, loc=\"lower right\")\n\n    plt.suptitle(f\"id: {_id} target: {target}\", fontsize=16)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:38.477751Z","iopub.execute_input":"2021-07-04T01:53:38.478218Z","iopub.status.idle":"2021-07-04T01:53:38.487264Z","shell.execute_reply.started":"2021-07-04T01:53:38.478174Z","shell.execute_reply":"2021-07-04T01:53:38.486553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import librosa\nimport librosa.display\ndef spectrogram_show(y, n_fft=N_FFT):\n    D = librosa.stft(y, n_fft=n_fft, hop_length=None, win_length=n_fft, window='hann', center=True, dtype=None, pad_mode='reflect')\n    S, phase = librosa.magphase(D)  \n    Sdb = librosa.amplitude_to_db(S)\n    librosa.display.specshow(Sdb, sr=4096, x_axis='time', y_axis='log')\n    return Sdb","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:38.488217Z","iopub.execute_input":"2021-07-04T01:53:38.488783Z","iopub.status.idle":"2021-07-04T01:53:38.502188Z","shell.execute_reply.started":"2021-07-04T01:53:38.488747Z","shell.execute_reply":"2021-07-04T01:53:38.501303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in np.random.choice(train_df.index.tolist(), 3):\n    _id = train_df.iloc[i][\"file_path\"]\n    target = train_df.iloc[i][\"target\"]\n    x = np.load(_id)\n    x = (x-train_mean)/train_std\n    visualize_sample(x, target, _id)","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:38.504607Z","iopub.execute_input":"2021-07-04T01:53:38.504922Z","iopub.status.idle":"2021-07-04T01:53:39.938443Z","shell.execute_reply.started":"2021-07-04T01:53:38.504892Z","shell.execute_reply":"2021-07-04T01:53:39.937059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.seed(0)\nfor i in np.random.choice(train_df.index.tolist(), 3):\n    _id = train_df.iloc[i][\"file_path\"]\n    target = train_df.iloc[i][\"target\"]\n    x = np.load(_id)\n    x = (x-train_mean)/train_std\n    x /=2\n    sdb = spectrogram_show(x[0])\n    print(sdb.shape, np.max(sdb), np.min(sdb))","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:39.940227Z","iopub.execute_input":"2021-07-04T01:53:39.940671Z","iopub.status.idle":"2021-07-04T01:53:40.178168Z","shell.execute_reply.started":"2021-07-04T01:53:39.940636Z","shell.execute_reply":"2021-07-04T01:53:40.177188Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.random.seed(0)\nfor i in np.random.choice(train_df.index.tolist(), 3):\n    _id = train_df.iloc[i][\"file_path\"]\n    target = train_df.iloc[i][\"target\"]\n    x = np.load(_id)\n    x = (x-train_mean)/train_std\n    sdb = spectrogram_show(x[0])\n    print(sdb.shape, np.max(sdb), np.min(sdb))","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:40.179498Z","iopub.execute_input":"2021-07-04T01:53:40.179804Z","iopub.status.idle":"2021-07-04T01:53:40.387752Z","shell.execute_reply.started":"2021-07-04T01:53:40.179759Z","shell.execute_reply":"2021-07-04T01:53:40.386767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## split folds","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import StratifiedKFold\nskf = StratifiedKFold(n_splits=FOLDS, shuffle=True, random_state=SEED)\ntrain_df['fold'] = -1\nfor fold, (train_idx, val_idx) in enumerate(skf.split(train_df, train_df['target'])):\n    train_df.loc[val_idx,'fold'] = fold","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:40.389038Z","iopub.execute_input":"2021-07-04T01:53:40.389352Z","iopub.status.idle":"2021-07-04T01:53:40.407674Z","shell.execute_reply.started":"2021-07-04T01:53:40.389306Z","shell.execute_reply":"2021-07-04T01:53:40.406469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import KFold\nskf = KFold(n_splits=FOLDS, shuffle=False)\ntest_df['fold'] = -1\nfor fold, (train_idx, val_idx) in enumerate(skf.split(test_df)):\n    test_df.loc[val_idx,'fold'] = fold","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:40.408988Z","iopub.execute_input":"2021-07-04T01:53:40.409314Z","iopub.status.idle":"2021-07-04T01:53:40.427307Z","shell.execute_reply.started":"2021-07-04T01:53:40.409256Z","shell.execute_reply":"2021-07-04T01:53:40.426505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.fold.value_counts()","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:40.428604Z","iopub.execute_input":"2021-07-04T01:53:40.428916Z","iopub.status.idle":"2021-07-04T01:53:40.435997Z","shell.execute_reply.started":"2021-07-04T01:53:40.428887Z","shell.execute_reply":"2021-07-04T01:53:40.43501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create TFRecords (Train)","metadata":{}},{"cell_type":"code","source":"def spectrogram(y, n_fft=N_FFT):\n    D = librosa.stft(y, n_fft=n_fft, hop_length=None, win_length=n_fft, window='hann', center=True, dtype=None, pad_mode='reflect')\n    S, phase = librosa.magphase(D)  \n    Sdb = librosa.amplitude_to_db(S)\n    return Sdb","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:40.437195Z","iopub.execute_input":"2021-07-04T01:53:40.437568Z","iopub.status.idle":"2021-07-04T01:53:40.447689Z","shell.execute_reply.started":"2021-07-04T01:53:40.437535Z","shell.execute_reply":"2021-07-04T01:53:40.4468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"spec_train_mean = np.zeros([129,65,3])\nspec_train_std = np.zeros([129,65,3])\nspec_test_mean = np.zeros([129,65,3])\nspec_test_std = np.zeros([129,65,3])","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:40.44912Z","iopub.execute_input":"2021-07-04T01:53:40.44987Z","iopub.status.idle":"2021-07-04T01:53:40.461972Z","shell.execute_reply.started":"2021-07-04T01:53:40.449821Z","shell.execute_reply":"2021-07-04T01:53:40.461067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\ndef _bytes_feature(value):\n    \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n    if isinstance(value, type(tf.constant(0))):\n        value = value.numpy() # BytesList won't unpack a string from an EagerTensor.\n    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef _float_feature(value):\n    \"\"\"Returns a float_list from a float / double.\"\"\"\n    return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\ndef _int64_feature(value):\n    \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:40.46358Z","iopub.execute_input":"2021-07-04T01:53:40.464386Z","iopub.status.idle":"2021-07-04T01:53:40.479985Z","shell.execute_reply.started":"2021-07-04T01:53:40.464336Z","shell.execute_reply":"2021-07-04T01:53:40.478549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def serialize_example(feature0, feature1, feature2):\n  feature = {\n      'image': _bytes_feature(feature0),\n      'target': _int64_feature(feature1),\n      'image_name': _bytes_feature(feature2),\n  }\n  example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n  return example_proto.SerializeToString()","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:40.481992Z","iopub.execute_input":"2021-07-04T01:53:40.482452Z","iopub.status.idle":"2021-07-04T01:53:40.492391Z","shell.execute_reply.started":"2021-07-04T01:53:40.482403Z","shell.execute_reply":"2021-07-04T01:53:40.491356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SIZE = LEN_TRAINS//FOLDS\n\nfolds = train_df.fold.unique().tolist()[VERS:VERE]\nfor i, fold in enumerate(tqdm(folds)): # create tfrecord for each fold# create tfrecord for each fold\n    fold_df = train_df[train_df.fold==fold]\n\n    print(); print('Writing TFRecord of fold %i :'%(fold))  \n    with tf.io.TFRecordWriter('train%.2i-%i.tfrec'%(fold,fold_df.shape[0])) as writer:\n        it = range(SIZE)\n        for k in it: \n            row = fold_df.iloc[k,:]\n            x = np.load(row['file_path'])\n            image_id   = row['id']\n\n            x = (x - train_mean) / train_std\n            \n            x0 = spectrogram(x[0])\n            x1 = spectrogram(x[1])\n            x2 = spectrogram(x[2])\n            \n            x = np.stack([x0, x1, x2], axis=-1)\n            \n            x = (x - np.min(x))/(np.max(x)-np.min(x))\n            x *= 255\n            cv2.imwrite(\"tmp.jpeg\", x)\n            x = cv2.imread(\"tmp.jpeg\")\n            x = cv2.imencode('.jpg', x, (cv2.IMWRITE_JPEG_QUALITY, 99))[1].tostring()\n            \n            #x = x.astype(np.float32)\n\n            example = serialize_example(\n                x,\n                np.array(row['target'], dtype=np.int64),\n                str.encode(image_id)\n            )\n            writer.write(example)\n            #if k%100==0: print(k,', ',end='')\n        filepath = 'train%.2i-%i.tfrec'%(fold,fold_df.shape[0])\n        filename = filepath.split('/')[-1]\n        filesize = os.path.getsize(filepath)/10**6\n        print(filename,':',np.around(filesize, 2),'MB')","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:40.493813Z","iopub.execute_input":"2021-07-04T01:53:40.494334Z","iopub.status.idle":"2021-07-04T01:53:41.923473Z","shell.execute_reply.started":"2021-07-04T01:53:40.494296Z","shell.execute_reply":"2021-07-04T01:53:41.922472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### stats","metadata":{}},{"cell_type":"code","source":"\"\"\"\nSIZE = LEN_TRAINS//FOLDS\n\nfolds = train_df.fold.unique().tolist()\nfor i, fold in enumerate(tqdm(folds)): # create tfrecord for each fold# create tfrecord for each fold\n    fold_df = train_df[train_df.fold==fold]\n    it = range(SIZE)\n    for k in it: \n        row = fold_df.iloc[k,:]\n        x = np.load(row['file_path'])\n        image_id   = row['id']\n\n        x = (x - train_mean) / train_std\n\n        x0 = spectrogram(x[0])\n        x1 = spectrogram(x[1])\n        x2 = spectrogram(x[2])\n        \n        \n\n        x = np.stack([x0, x1, x2], axis=-1)\n        spec_train_mean += x\n\n        #if k%100==0: print(k,', ',end='')\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:41.924667Z","iopub.execute_input":"2021-07-04T01:53:41.925021Z","iopub.status.idle":"2021-07-04T01:53:41.933774Z","shell.execute_reply.started":"2021-07-04T01:53:41.924991Z","shell.execute_reply":"2021-07-04T01:53:41.932823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#spec_train_mean /= LEN_TRAINS","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:41.935244Z","iopub.execute_input":"2021-07-04T01:53:41.935966Z","iopub.status.idle":"2021-07-04T01:53:41.947121Z","shell.execute_reply.started":"2021-07-04T01:53:41.935917Z","shell.execute_reply":"2021-07-04T01:53:41.946144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\"\"\"\nSIZE = LEN_TRAINS//FOLDS\n\nfolds = train_df.fold.unique().tolist()\nfor i, fold in enumerate(tqdm(folds)): # create tfrecord for each fold# create tfrecord for each fold\n    fold_df = train_df[train_df.fold==fold]\n    it = range(SIZE)\n    for k in it: \n        row = fold_df.iloc[k,:]\n        x = np.load(row['file_path'])\n        image_id   = row['id']\n\n        x = (x - train_mean) / train_std\n\n        x0 = spectrogram(x[0])\n        x1 = spectrogram(x[1])\n        x2 = spectrogram(x[2])\n\n        x = np.stack([x0, x1, x2], axis=-1)\n\n        spec_train_std += (x-spec_train_mean)**2.\n\n        #if k%100==0: print(k,', ',end='')\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:41.948867Z","iopub.execute_input":"2021-07-04T01:53:41.949288Z","iopub.status.idle":"2021-07-04T01:53:41.961505Z","shell.execute_reply.started":"2021-07-04T01:53:41.949236Z","shell.execute_reply":"2021-07-04T01:53:41.960395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#spec_train_std /= LEN_TRAINS\n#spec_train_std = np.sqrt(spec_train_std)\n#spec_train_mean.shape, spec_train_std.shape","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:41.96291Z","iopub.execute_input":"2021-07-04T01:53:41.963422Z","iopub.status.idle":"2021-07-04T01:53:41.971765Z","shell.execute_reply.started":"2021-07-04T01:53:41.963374Z","shell.execute_reply":"2021-07-04T01:53:41.970694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#np.save('spec_train_mean.npy',spec_train_mean)\n#np.save('spec_train_std.npy',spec_train_std)","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:41.975156Z","iopub.execute_input":"2021-07-04T01:53:41.975631Z","iopub.status.idle":"2021-07-04T01:53:41.984729Z","shell.execute_reply.started":"2021-07-04T01:53:41.975597Z","shell.execute_reply":"2021-07-04T01:53:41.983776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create TFRecords(Test)","metadata":{}},{"cell_type":"code","source":"def serialize_example(feature0, feature1):\n  feature = {\n      'image': _bytes_feature(feature0),\n      'image_name': _bytes_feature(feature1),\n  }\n  example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n  return example_proto.SerializeToString()","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:41.986344Z","iopub.execute_input":"2021-07-04T01:53:41.986677Z","iopub.status.idle":"2021-07-04T01:53:41.995918Z","shell.execute_reply.started":"2021-07-04T01:53:41.986647Z","shell.execute_reply":"2021-07-04T01:53:41.994967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SIZE = LEN_TESTS//FOLDS\n\nfolds = test_df.fold.unique().tolist()[VERS:VERE]\nfor i, fold in enumerate(tqdm(folds)): # create tfrecord for each fold# create tfrecord for each fold\n    fold_df = test_df[test_df.fold==fold]\n\n    print(); print('Writing TFRecord of fold %i :'%(fold))  \n    with tf.io.TFRecordWriter('test%.2i-%i.tfrec'%(fold,fold_df.shape[0])) as writer:\n        it = range(SIZE)\n        for k in it: \n            row = fold_df.iloc[k,:]\n            x = np.load(row['file_path'])\n            image_id   = row['id']\n\n            x = (x - test_mean) / test_std\n            \n            x0 = spectrogram(x[0])\n            x1 = spectrogram(x[1])\n            x2 = spectrogram(x[2])\n            \n            x = np.stack([x0, x1, x2], axis=-1)\n            \n            #spec_test_mean += x\n            x = (x - np.min(x))/(np.max(x)-np.min(x))\n            x *= 255\n            cv2.imwrite(\"tmp.jpeg\", x)\n            x = cv2.imread(\"tmp.jpeg\")\n            x = cv2.imencode('.jpg', x, (cv2.IMWRITE_JPEG_QUALITY, 99))[1].tostring()\n            \n            #x = x.astype(np.float32)\n            \n\n            example = serialize_example(\n                x,\n                str.encode(image_id)\n            )\n            writer.write(example)\n            #if k%100==0: print(k,', ',end='')","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:41.99719Z","iopub.execute_input":"2021-07-04T01:53:41.997734Z","iopub.status.idle":"2021-07-04T01:53:43.913657Z","shell.execute_reply.started":"2021-07-04T01:53:41.997703Z","shell.execute_reply":"2021-07-04T01:53:43.912674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### stats","metadata":{}},{"cell_type":"code","source":"\"\"\"\nSIZE = LEN_TESTS//FOLDS\n\nfolds = train_df.fold.unique().tolist()\nfor i, fold in enumerate(tqdm(folds)): # create tfrecord for each fold# create tfrecord for each fold\n    fold_df = train_df[train_df.fold==fold]\n    it = range(SIZE)\n    for k in it: \n        row = fold_df.iloc[k,:]\n        x = np.load(row['file_path'])\n        image_id   = row['id']\n\n        x = (x - train_mean) / train_std\n\n        x0 = spectrogram(x[0])\n        x1 = spectrogram(x[1])\n        x2 = spectrogram(x[2])\n        \n        x = np.stack([x0, x1, x2], axis=-1)\n        \n        spec_test_mean += x\n\n        #if k%100==0: print(k,', ',end='')\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:43.915558Z","iopub.execute_input":"2021-07-04T01:53:43.9161Z","iopub.status.idle":"2021-07-04T01:53:43.921704Z","shell.execute_reply.started":"2021-07-04T01:53:43.916066Z","shell.execute_reply":"2021-07-04T01:53:43.920724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\"\"\"\nSIZE = LEN_TESTS//FOLDS\n\nfolds = train_df.fold.unique().tolist()\nfor i, fold in enumerate(tqdm(folds)): # create tfrecord for each fold# create tfrecord for each fold\n    fold_df = train_df[train_df.fold==fold]\n    it = range(SIZE)\n    for k in it: \n        row = fold_df.iloc[k,:]\n        x = np.load(row['file_path'])\n        image_id   = row['id']\n\n        x = (x - train_mean) / train_std\n\n        x0 = spectrogram(x[0])\n        x1 = spectrogram(x[1])\n        x2 = spectrogram(x[2])\n        \n        x = np.stack([x0, x1, x2], axis=-1)\n        \n        spec_test_std = (x-spec_test_mean)**2.0 \n\n        #if k%100==0: print(k,', ',end='')\n\"\"\"","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:43.922893Z","iopub.execute_input":"2021-07-04T01:53:43.923169Z","iopub.status.idle":"2021-07-04T01:53:43.936306Z","shell.execute_reply.started":"2021-07-04T01:53:43.923142Z","shell.execute_reply":"2021-07-04T01:53:43.935201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#spec_test_mean /= LEN_TESTS\n#spec_test_std /= LEN_TESTS\n#spec_test_std = np.sqrt(spec_test_std)\n#spec_test_mean.shape, spec_test_std.shape","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:43.937714Z","iopub.execute_input":"2021-07-04T01:53:43.938035Z","iopub.status.idle":"2021-07-04T01:53:43.950404Z","shell.execute_reply.started":"2021-07-04T01:53:43.938007Z","shell.execute_reply":"2021-07-04T01:53:43.949237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#np.save('spec_test_mean.npy',spec_test_mean)\n#np.save('spec_test_std.npy',spec_test_std)","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:43.952286Z","iopub.execute_input":"2021-07-04T01:53:43.952648Z","iopub.status.idle":"2021-07-04T01:53:43.963103Z","shell.execute_reply.started":"2021-07-04T01:53:43.952597Z","shell.execute_reply":"2021-07-04T01:53:43.961822Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Verify TFRecords","metadata":{}},{"cell_type":"code","source":"import re,math","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:43.964666Z","iopub.execute_input":"2021-07-04T01:53:43.965066Z","iopub.status.idle":"2021-07-04T01:53:43.975391Z","shell.execute_reply.started":"2021-07-04T01:53:43.965035Z","shell.execute_reply":"2021-07-04T01:53:43.974218Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# numpy and matplotlib defaults\nnp.set_printoptions(threshold=15, linewidth=80)\nCLASSES = [0,1]\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    #if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n    #    numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \ndef display_batch_of_images(databatch, predictions=None):\n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    display_batch_of_images(images, predictions)\n    display_batch_of_images((images, labels))\n    display_batch_of_images((images, labels), predictions)\n    \"\"\"\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    images = (images-np.min(images))/(np.max(images)-np.min(images))\n    print(np.max(images),np.min(images))\n    \n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)//rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        title = label\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:53:43.976823Z","iopub.execute_input":"2021-07-04T01:53:43.977106Z","iopub.status.idle":"2021-07-04T01:53:43.996857Z","shell.execute_reply.started":"2021-07-04T01:53:43.977078Z","shell.execute_reply":"2021-07-04T01:53:43.995815Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    #image = tf.io.decode_raw(image_data, tf.float32)\n    image = tf.cast(image, tf.float32)   # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [129, 65, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = example['image_name']\n    return image, label # returns a dataset of (image, label) pairs\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:54:14.970652Z","iopub.execute_input":"2021-07-04T01:54:14.97108Z","iopub.status.idle":"2021-07-04T01:54:14.983567Z","shell.execute_reply.started":"2021-07-04T01:54:14.971047Z","shell.execute_reply":"2021-07-04T01:54:14.982799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# INITIALIZE VARIABLES\nIMAGE_SIZE= [129,65]; BATCH_SIZE = 32\nAUTO = tf.data.experimental.AUTOTUNE\nTRAINING_FILENAMES = tf.io.gfile.glob('train*.tfrec')\nprint('There are %i train images'%count_data_items(TRAINING_FILENAMES))","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:54:17.830284Z","iopub.execute_input":"2021-07-04T01:54:17.830897Z","iopub.status.idle":"2021-07-04T01:54:17.836872Z","shell.execute_reply.started":"2021-07-04T01:54:17.83086Z","shell.execute_reply":"2021-07-04T01:54:17.836142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# DISPLAY TRAIN IMAGES\ntraining_dataset = get_training_dataset()\ntraining_dataset = training_dataset.unbatch().batch(20)\ntrain_batch = iter(training_dataset)\n\ndisplay_batch_of_images(next(train_batch))","metadata":{"execution":{"iopub.status.busy":"2021-07-04T01:54:18.26459Z","iopub.execute_input":"2021-07-04T01:54:18.264982Z","iopub.status.idle":"2021-07-04T01:54:20.822942Z","shell.execute_reply.started":"2021-07-04T01:54:18.264951Z","shell.execute_reply":"2021-07-04T01:54:20.821851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}