[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "\n\n[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.4060151.svg)](https://doi.org/10.5281/zenodo.4060151)\n\n\n# EEG_classification\nDescription of the approach : https://towardsdatascience.com/sleep-stage-classification-from-single-channel-eeg-using-convolutional-neural-networks-5c710d92d38e\n\n\nSleep Stage Classification from Single Channel EEG using Convolutional Neural\nNetworks\n\n*****\n\n<span class=\"figcaption_hack\">Photo by [Paul\nM](https://unsplash.com/photos/7i9yLoUgoP8?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)\non\n[Unsplash](https://unsplash.com/search/photos/owl?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)</span>\n\nQuality Sleep is an important part of a healthy lifestyle as lack of it can\ncause a list of\n[issues](https://www.webmd.com/sleep-disorders/features/10-results-sleep-loss#1)\nlike a higher risk of cancer and chronic fatigue. This means that having the\ntools to automatically and easily monitor sleep can be powerful to help people\nsleep better.<br> Doctors use a recording of a signal called EEG which measures\nthe electrical activity of the brain using an electrode to understand sleep\nstages of a patient and make a diagnosis about the quality if their sleep.\n\nIn this post we will train a neural network to do the sleep stage classification\nautomatically from EEGs.\n\n### **Data**\n\nIn our input we have a sequence of 30s epochs of EEG where each epoch has a\nlabel [{“W”, “N1”, “N2”, “N3”,\n“REM”}](https://en.wikipedia.org/wiki/Sleep_cycle).\n\n<span class=\"figcaption_hack\">Fig 1 : EEG Epoch</span>\n\n<span class=\"figcaption_hack\">Fig 2 : Sleep stages through the night</span>\n\nThis post is based on a publicly available EEG Sleep data (\n[Sleep-EDF](https://www.physionet.org/physiobank/database/sleep-edfx/) ) that\nwas done on 20 subject, 19 of which have 2 full nights of sleep. We use the\npre-processing scripts available in this\n[repo](https://github.com/akaraspt/deepsleepnet) and split the train/test so\nthat no study subject is in both at the same time.\n\nThe general objective is to go from a 1D sequence like in fig 1 and predict the\noutput hypnogram like in fig 2.\n\n### Model Description\n\nRecent approaches [[1]](https://arxiv.org/pdf/1703.04046.pdf) use a sub-model\nthat encodes each epoch into a 1D vector of fixed size and then a second\nsequential sub-model that maps each epoch’s vector into a class from [{“W”,\n“N1”, “N2”, “N3”, “REM”}](https://en.wikipedia.org/wiki/Sleep_cycle).\n\nHere we use a 1D CNN to encode each Epoch and then another 1D CNN or LSTM that\nlabels the sequence of epochs to create the final\n[hypnogram](https://en.wikipedia.org/wiki/Hypnogram). This allows the prediction\nfor an epoch to take into account the context.\n\n<span class=\"figcaption_hack\">Sub-model 1 : Epoch encoder</span>\n\n<span class=\"figcaption_hack\">Sub-model 2 : Sequential model for epoch classification</span>\n\nThe full model takes as input the sequence of EEG epochs ( 30 seconds each)\nwhere the sub-model 1 is applied to each epoch using the TimeDistributed Layer\nof [Keras](https://keras.io/) which produces a sequence of vectors. The sequence\nof vectors is then fed into a another sub-model like an LSTM or a CNN that\nproduces the sequence of output labels.<br> We also use a linear Chain\n[CRF](https://en.wikipedia.org/wiki/Conditional_random_field) for one of the\nmodels and show that it can improve the performance.\n\n### Training Procedure\n\nThe full model is trained end-to-end from scratch using Adam optimizer with an\ninitial learning rate of 1e⁻³ that is reduced each time the validation accuracy\nplateaus using the ReduceLROnPlateau Keras Callbacks.\n\n<span class=\"figcaption_hack\">Accuracy Training curves</span>\n\n### Results\n\nWe compare 3 different models :\n\n* CNN-CNN : This ones used a 1D CNN for the epoch encoding and then another 1D CNN\nfor the sequence labeling.\n* CNN-CNN-CRF : This model used a 1D CNN for the epoch encoding and then a 1D\nCNN-CRF for the sequence labeling.\n* CNN-LSTM : This ones used a 1D CNN for the epoch encoding and then an LSTM for\nthe sequence labeling.\n\nWe evaluate each model on an independent test set and get the following results\n:\n\n* CNN-CNN : F1 = 0.81, ACCURACY = 0.87\n* CNN-CNN-CRF : F1 = 0.82, ACCURACY =0.89\n* CNN-LSTM : F1 = 0.71, ACCURACY = 0.76\n\nThe CNN-CNN-CRF outperforms the two other models because the CRF helps learn the\ntransition probabilities between classes. The LSTM based model does not work as\nwell because it is most sensitive to hyper-parameters like the optimizer and the\nbatch size and requires extensive tuning to perform well.\n\n<span class=\"figcaption_hack\">Ground Truth Hypnogram</span>\n\n<span class=\"figcaption_hack\">Predicted Hypnogram using CNN-CNN-CRF</span>\n\nSource code available here :\n[https://github.com/CVxTz/EEG_classification](https://github.com/CVxTz/EEG_classification)\n\nI look forward to your suggestions and feedback.\n\n[[1] DeepSleepNet: a Model for Automatic Sleep Stage Scoring based on Raw\nSingle-Channel EEG](https://arxiv.org/pdf/1703.04046.pdf)\n\nHow to cite:\n```\n@software{mansar_youness_2020_4060151,\n  author       = {Mansar Youness},\n  title        = {CVxTz/EEG\\_classification: v1.0},\n  month        = sep,\n  year         = 2020,\n  publisher    = {Zenodo},\n  version      = {v1.0},\n  doi          = {10.5281/zenodo.4060151},\n  url          = {https://doi.org/10.5281/zenodo.4060151}\n}\n```\n"
  },
  {
    "path": "code/baseline.py",
    "content": "import numpy as np\nfrom glob import glob\nimport os\nfrom sklearn.model_selection import train_test_split\n\nbase_path = \"/media/ml/data_ml/EEG/deepsleepnet/data_npy\"\n\nfiles = glob(os.path.join(base_path, \"*.npz\"))\ntrain_val, test = train_test_split(files, test_size=0.15, random_state=1337)\n\ntrain, val = train_test_split(train_val, test_size=0.1, random_state=1337)\n\ntrain_dict = {k: np.load(k) for k in train}\ntest_dict = {k: np.load(k) for k in test}\nval_dict = {k: np.load(k) for k in val}\n\n\n\n"
  },
  {
    "path": "code/cnn_crf_model.py",
    "content": "from models import get_model_cnn_crf\nimport numpy as np\nfrom utils import gen, chunker, WINDOW_SIZE, rescale_array\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom sklearn.metrics import f1_score, accuracy_score, classification_report\nfrom glob import glob\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\n\nbase_path = \"/media/ml/data_ml/EEG/deepsleepnet/data_npy\"\n\nfiles = sorted(glob(os.path.join(base_path, \"*.npz\")))\n\nids = sorted(list(set([x.split(\"/\")[-1][:5] for x in files])))\n#split by test subject\ntrain_ids, test_ids = train_test_split(ids, test_size=0.15, random_state=1338)\n\ntrain_val, test = [x for x in files if x.split(\"/\")[-1][:5] in train_ids],\\\n                  [x for x in files if x.split(\"/\")[-1][:5] in test_ids]\n\ntrain, val = train_test_split(train_val, test_size=0.1, random_state=1337)\n\ntrain_dict = {k: np.load(k) for k in train}\ntest_dict = {k: np.load(k) for k in test}\nval_dict = {k: np.load(k) for k in val}\n\nmodel = get_model_cnn_crf()\n\nfile_path = \"cnn_crf_model.h5\"\n# model.load_weights(file_path)\n\ncheckpoint = ModelCheckpoint(file_path, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\nearly = EarlyStopping(monitor=\"val_acc\", mode=\"max\", patience=20, verbose=1)\nredonplat = ReduceLROnPlateau(monitor=\"val_acc\", mode=\"max\", patience=5, verbose=2)\ncallbacks_list = [checkpoint, early, redonplat]  # early\n\nmodel.fit_generator(gen(train_dict, aug=False), validation_data=gen(val_dict), epochs=100, verbose=2,\n                    steps_per_epoch=1000, validation_steps=300, callbacks=callbacks_list)\nmodel.load_weights(file_path)\n\n\npreds = []\ngt = []\n\nfor record in tqdm(test_dict):\n    all_rows = test_dict[record]['x']\n    record_y_gt = []\n    record_y_pred = []\n    for batch_hyp in chunker(range(all_rows.shape[0])):\n\n\n        X = all_rows[min(batch_hyp):max(batch_hyp)+1, ...]\n        Y = test_dict[record]['y'][min(batch_hyp):max(batch_hyp)+1]\n\n        X = np.expand_dims(X, 0)\n\n        X = rescale_array(X)\n\n        Y_pred = model.predict(X)\n        Y_pred = Y_pred.argmax(axis=-1).ravel().tolist()\n\n        gt += Y.ravel().tolist()\n        preds += Y_pred\n\n        record_y_gt += Y.ravel().tolist()\n        record_y_pred += Y_pred\n\n    # fig_1 = plt.figure(figsize=(12, 6))\n    # plt.plot(record_y_gt)\n    # plt.title(\"Sleep Stages\")\n    # plt.ylabel(\"Classes\")\n    # plt.xlabel(\"Time\")\n    # plt.show()\n    #\n    # fig_2 = plt.figure(figsize=(12, 6))\n    # plt.plot(record_y_pred)\n    # plt.title(\"Predicted Sleep Stages\")\n    # plt.ylabel(\"Classes\")\n    # plt.xlabel(\"Time\")\n    # plt.show()\n\n\n\nf1 = f1_score(gt, preds, average=\"macro\")\n\nprint(\"Seq Test f1 score : %s \"% f1)\n\nacc = accuracy_score(gt, preds)\n\nprint(\"Seq Test accuracy score : %s \"% acc)\n\nprint(classification_report(gt, preds))"
  },
  {
    "path": "code/cnn_crf_model_20_folds.py",
    "content": "from models import get_model_cnn_crf\nimport numpy as np\nfrom utils import gen, chunker, WINDOW_SIZE, rescale_array\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom sklearn.metrics import f1_score, accuracy_score, classification_report\nfrom glob import glob\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\n\nbase_path = \"/media/ml/data_ml/EEG/deepsleepnet/data_npy\"\n\nfiles = sorted(glob(os.path.join(base_path, \"*.npz\")))\n\nids = list(set([x.split(\"/\")[-1][:5] for x in files]))\nlist_f1 = []\nlist_acc = []\npreds = []\ngt = []\nfor id in ids:\n    test_ids = {id}\n    train_ids = set([x.split(\"/\")[-1][:5] for x in files]) - test_ids\n\n    train_val, test = [x for x in files if x.split(\"/\")[-1][:5] in train_ids],\\\n                      [x for x in files if x.split(\"/\")[-1][:5] in test_ids]\n\n    train, val = train_test_split(train_val, test_size=0.1, random_state=1337)\n\n    train_dict = {k: np.load(k) for k in train}\n    test_dict = {k: np.load(k) for k in test}\n    val_dict = {k: np.load(k) for k in val}\n\n    model = get_model_cnn_crf(lr=0.0001)\n\n    file_path = \"cnn_crf_model_20_folds.h5\"\n    # model.load_weights(file_path)\n\n    checkpoint = ModelCheckpoint(file_path, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\n    early = EarlyStopping(monitor=\"val_acc\", mode=\"max\", patience=20, verbose=1)\n    redonplat = ReduceLROnPlateau(monitor=\"val_acc\", mode=\"max\", patience=5, verbose=2)\n    callbacks_list = [checkpoint, redonplat]  # early\n\n    model.fit_generator(gen(train_dict, aug=False), validation_data=gen(val_dict), epochs=40, verbose=2,\n                        steps_per_epoch=1000, validation_steps=300, callbacks=callbacks_list)\n    model.load_weights(file_path)\n\n\n\n\n    for record in tqdm(test_dict):\n        all_rows = test_dict[record]['x']\n        record_y_gt = []\n        record_y_pred = []\n        for batch_hyp in chunker(range(all_rows.shape[0])):\n\n\n            X = all_rows[min(batch_hyp):max(batch_hyp)+1, ...]\n            Y = test_dict[record]['y'][min(batch_hyp):max(batch_hyp)+1]\n\n            X = np.expand_dims(X, 0)\n\n            X = rescale_array(X)\n\n            Y_pred = model.predict(X)\n            Y_pred = Y_pred.argmax(axis=-1).ravel().tolist()\n\n            gt += Y.ravel().tolist()\n            preds += Y_pred\n\n            record_y_gt += Y.ravel().tolist()\n            record_y_pred += Y_pred\n\n\nf1 = f1_score(gt, preds, average=\"macro\")\n\nacc = accuracy_score(gt, preds)\n\nprint(\"acc %s, f1 %s\"%(acc, f1))\n\n"
  },
  {
    "path": "code/cnn_model.py",
    "content": "from models import get_model_cnn\nimport numpy as np\nfrom utils import gen, chunker, WINDOW_SIZE, rescale_array\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom sklearn.metrics import f1_score, accuracy_score, classification_report\nfrom glob import glob\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\n\n\nbase_path = \"/media/ml/data_ml/EEG/deepsleepnet/data_npy\"\n\nfiles = sorted(glob(os.path.join(base_path, \"*.npz\")))\n\nids = sorted(list(set([x.split(\"/\")[-1][:5] for x in files])))\n#split by test subject\ntrain_ids, test_ids = train_test_split(ids, test_size=0.15, random_state=1338)\n\ntrain_val, test = [x for x in files if x.split(\"/\")[-1][:5] in train_ids],\\\n                  [x for x in files if x.split(\"/\")[-1][:5] in test_ids]\n\ntrain, val = train_test_split(train_val, test_size=0.1, random_state=1337)\n\ntrain_dict = {k: np.load(k) for k in train}\ntest_dict = {k: np.load(k) for k in test}\nval_dict = {k: np.load(k) for k in val}\n\nmodel = get_model_cnn()\n\nfile_path = \"cnn_model.h5\"\n# model.load_weights(file_path)\n\ncheckpoint = ModelCheckpoint(file_path, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\nearly = EarlyStopping(monitor=\"val_acc\", mode=\"max\", patience=20, verbose=1)\nredonplat = ReduceLROnPlateau(monitor=\"val_acc\", mode=\"max\", patience=5, verbose=2)\ncallbacks_list = [checkpoint, early, redonplat]  # early\n\nmodel.fit_generator(gen(train_dict, aug=False), validation_data=gen(val_dict), epochs=100, verbose=2,\n                    steps_per_epoch=1000, validation_steps=300, callbacks=callbacks_list)\nmodel.load_weights(file_path)\n\n\npreds = []\ngt = []\n\nfor record in tqdm(test_dict):\n    all_rows = test_dict[record]['x']\n    for batch_hyp in chunker(range(all_rows.shape[0])):\n\n\n        X = all_rows[min(batch_hyp):max(batch_hyp)+1, ...]\n        Y = test_dict[record]['y'][min(batch_hyp):max(batch_hyp)+1]\n\n        X = np.expand_dims(X, 0)\n\n        X = rescale_array(X)\n\n        Y_pred = model.predict(X)\n        Y_pred = Y_pred.argmax(axis=-1).ravel().tolist()\n\n        gt += Y.ravel().tolist()\n        preds += Y_pred\n\n\n\nf1 = f1_score(gt, preds, average=\"macro\")\n\nprint(\"Seq Test f1 score : %s \"% f1)\n\nacc = accuracy_score(gt, preds)\n\nprint(\"Seq Test accuracy score : %s \"% acc)\n\nprint(classification_report(gt, preds))"
  },
  {
    "path": "code/eda.py",
    "content": "import os\nimport h5py\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime as dt\nimport collections\nimport librosa\n\npath = \"/media/ml/data_ml/EEG/deepsleepnet/data_npy/SC4061E0.npz\"\n\ndata = np.load(path)\n\nx = data['x']\ny = data['y']\n\nfig_1 = plt.figure(figsize=(12, 6))\nplt.plot(x[100, ...].ravel())\nplt.title(\"EEG Epoch\")\nplt.ylabel(\"Amplitude\")\nplt.xlabel(\"Time\")\nplt.show()\n\nfig_2 = plt.figure(figsize=(12, 6))\nplt.plot(y.ravel())\nplt.title(\"Sleep Stages\")\nplt.ylabel(\"Classes\")\nplt.xlabel(\"Time\")\nplt.show()"
  },
  {
    "path": "code/lstm_model.py",
    "content": "from models import get_model_lstm\nimport numpy as np\nfrom utils import gen, chunker, WINDOW_SIZE, rescale_array\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom sklearn.metrics import f1_score, accuracy_score, classification_report\nfrom glob import glob\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\n\n\nbase_path = \"/media/ml/data_ml/EEG/deepsleepnet/data_npy\"\n\nfiles = sorted(glob(os.path.join(base_path, \"*.npz\")))\n\nids = sorted(list(set([x.split(\"/\")[-1][:5] for x in files])))\n#split by test subject\ntrain_ids, test_ids = train_test_split(ids, test_size=0.15, random_state=1338)\n\ntrain_val, test = [x for x in files if x.split(\"/\")[-1][:5] in train_ids],\\\n                  [x for x in files if x.split(\"/\")[-1][:5] in test_ids]\n\ntrain, val = train_test_split(train_val, test_size=0.1, random_state=1337)\n\ntrain_dict = {k: np.load(k) for k in train}\ntest_dict = {k: np.load(k) for k in test}\nval_dict = {k: np.load(k) for k in val}\n\nmodel = get_model_lstm()\n\nfile_path = \"lstm_model.h5\"\n# model.load_weights(file_path)\n\ncheckpoint = ModelCheckpoint(file_path, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\nearly = EarlyStopping(monitor=\"val_acc\", mode=\"max\", patience=20, verbose=1)\nredonplat = ReduceLROnPlateau(monitor=\"val_acc\", mode=\"max\", patience=5, verbose=2)\ncallbacks_list = [checkpoint, early, redonplat]  # early\n\nmodel.fit_generator(gen(train_dict, aug=False), validation_data=gen(val_dict), epochs=100, verbose=2,\n                    steps_per_epoch=1000, validation_steps=300, callbacks=callbacks_list)\nmodel.load_weights(file_path)\n\n\npreds = []\ngt = []\n\nfor record in tqdm(test_dict):\n    all_rows = test_dict[record]['x']\n    for batch_hyp in chunker(range(all_rows.shape[0])):\n\n\n        X = all_rows[min(batch_hyp):max(batch_hyp)+1, ...]\n        Y = test_dict[record]['y'][min(batch_hyp):max(batch_hyp)+1]\n\n        X = np.expand_dims(X, 0)\n\n        X = rescale_array(X)\n\n        Y_pred = model.predict(X)\n        Y_pred = Y_pred.argmax(axis=-1).ravel().tolist()\n\n        gt += Y.ravel().tolist()\n        preds += Y_pred\n\n\n\nf1 = f1_score(gt, preds, average=\"macro\")\n\nprint(\"Seq Test f1 score : %s \"% f1)\n\nacc = accuracy_score(gt, preds)\n\nprint(\"Seq Test accuracy score : %s \"% acc)\n\nprint(classification_report(gt, preds))"
  },
  {
    "path": "code/models.py",
    "content": "from keras import optimizers, losses, activations, models\nfrom keras.layers import Dense, Input, Dropout, Convolution1D, MaxPool1D, GlobalMaxPool1D, GlobalAveragePooling1D, \\\n    concatenate, SpatialDropout1D, TimeDistributed, Bidirectional, LSTM\nfrom keras_contrib.layers import CRF\n\nfrom utils import WINDOW_SIZE\n\ndef get_model():\n    nclass = 5\n    inp = Input(shape=(3000, 1))\n    img_1 = Convolution1D(16, kernel_size=5, activation=activations.relu, padding=\"valid\")(inp)\n    img_1 = Convolution1D(16, kernel_size=5, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = MaxPool1D(pool_size=2)(img_1)\n    img_1 = SpatialDropout1D(rate=0.01)(img_1)\n    img_1 = Convolution1D(32, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = Convolution1D(32, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = MaxPool1D(pool_size=2)(img_1)\n    img_1 = SpatialDropout1D(rate=0.01)(img_1)\n    img_1 = Convolution1D(32, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = Convolution1D(32, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = MaxPool1D(pool_size=2)(img_1)\n    img_1 = SpatialDropout1D(rate=0.01)(img_1)\n    img_1 = Convolution1D(256, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = Convolution1D(256, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = GlobalMaxPool1D()(img_1)\n    img_1 = Dropout(rate=0.01)(img_1)\n\n    dense_1 = Dropout(rate=0.01)(Dense(64, activation=activations.relu, name=\"dense_1\")(img_1))\n    dense_1 = Dropout(rate=0.05)(Dense(64, activation=activations.relu, name=\"dense_2\")(dense_1))\n    dense_1 = Dense(nclass, activation=activations.softmax, name=\"dense_3\")(dense_1)\n\n    model = models.Model(inputs=inp, outputs=dense_1)\n    opt = optimizers.Adam(0.001)\n\n    model.compile(optimizer=opt, loss=losses.sparse_categorical_crossentropy, metrics=['acc'])\n    model.summary()\n    return model\n\ndef get_base_model():\n    inp = Input(shape=(3000, 1))\n    img_1 = Convolution1D(16, kernel_size=5, activation=activations.relu, padding=\"valid\")(inp)\n    img_1 = Convolution1D(16, kernel_size=5, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = MaxPool1D(pool_size=2)(img_1)\n    img_1 = SpatialDropout1D(rate=0.01)(img_1)\n    img_1 = Convolution1D(32, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = Convolution1D(32, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = MaxPool1D(pool_size=2)(img_1)\n    img_1 = SpatialDropout1D(rate=0.01)(img_1)\n    img_1 = Convolution1D(32, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = Convolution1D(32, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = MaxPool1D(pool_size=2)(img_1)\n    img_1 = SpatialDropout1D(rate=0.01)(img_1)\n    img_1 = Convolution1D(256, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = Convolution1D(256, kernel_size=3, activation=activations.relu, padding=\"valid\")(img_1)\n    img_1 = GlobalMaxPool1D()(img_1)\n    img_1 = Dropout(rate=0.01)(img_1)\n\n    dense_1 = Dropout(0.01)(Dense(64, activation=activations.relu, name=\"dense_1\")(img_1))\n\n    base_model = models.Model(inputs=inp, outputs=dense_1)\n    opt = optimizers.Adam(0.001)\n\n    base_model.compile(optimizer=opt, loss=losses.sparse_categorical_crossentropy, metrics=['acc'])\n    #model.summary()\n    return base_model\n\n\ndef get_model_cnn():\n    nclass = 5\n\n    seq_input = Input(shape=(None, 3000, 1))\n    base_model = get_base_model()\n    # for layer in base_model.layers:\n    #     layer.trainable = False\n    encoded_sequence = TimeDistributed(base_model)(seq_input)\n    encoded_sequence = SpatialDropout1D(rate=0.01)(Convolution1D(128,\n                                                               kernel_size=3,\n                                                               activation=\"relu\",\n                                                               padding=\"same\")(encoded_sequence))\n    encoded_sequence = Dropout(rate=0.05)(Convolution1D(128,\n                                                               kernel_size=3,\n                                                               activation=\"relu\",\n                                                               padding=\"same\")(encoded_sequence))\n\n    #out = TimeDistributed(Dense(nclass, activation=\"softmax\"))(encoded_sequence)\n    out = Convolution1D(nclass, kernel_size=3, activation=\"softmax\", padding=\"same\")(encoded_sequence)\n\n    model = models.Model(seq_input, out)\n\n    model.compile(optimizers.Adam(0.001), losses.sparse_categorical_crossentropy, metrics=['acc'])\n    model.summary()\n\n    return model\n\ndef get_model_lstm():\n    nclass = 5\n\n    seq_input = Input(shape=(None, 3000, 1))\n    base_model = get_base_model()\n    for layer in base_model.layers:\n        layer.trainable = False\n    encoded_sequence = TimeDistributed(base_model)(seq_input)\n    encoded_sequence = Bidirectional(LSTM(100, return_sequences=True))(encoded_sequence)\n    encoded_sequence = Dropout(rate=0.5)(encoded_sequence)\n    encoded_sequence = Bidirectional(LSTM(100, return_sequences=True))(encoded_sequence)\n    #out = TimeDistributed(Dense(nclass, activation=\"softmax\"))(encoded_sequence)\n    out = Convolution1D(nclass, kernel_size=1, activation=\"softmax\", padding=\"same\")(encoded_sequence)\n\n    model = models.Model(seq_input, out)\n\n    model.compile(optimizers.Adam(0.001), losses.sparse_categorical_crossentropy, metrics=['acc'])\n    model.summary()\n\n    return model\n\ndef get_model_cnn_crf(lr=0.001):\n    nclass = 5\n\n    seq_input = Input(shape=(None, 3000, 1))\n    base_model = get_base_model()\n    # for layer in base_model.layers:\n    #     layer.trainable = False\n    encoded_sequence = TimeDistributed(base_model)(seq_input)\n    encoded_sequence = SpatialDropout1D(rate=0.01)(Convolution1D(128,\n                                                               kernel_size=3,\n                                                               activation=\"relu\",\n                                                               padding=\"same\")(encoded_sequence))\n    encoded_sequence = Dropout(rate=0.05)(Convolution1D(128,\n                                                               kernel_size=3,\n                                                               activation=\"linear\",\n                                                               padding=\"same\")(encoded_sequence))\n\n    #out = TimeDistributed(Dense(nclass, activation=\"softmax\"))(encoded_sequence)\n    # out = Convolution1D(nclass, kernel_size=3, activation=\"linear\", padding=\"same\")(encoded_sequence)\n\n    crf = CRF(nclass, sparse_target=True)\n\n    out = crf(encoded_sequence)\n\n\n    model = models.Model(seq_input, out)\n\n    model.compile(optimizers.Adam(lr), crf.loss_function, metrics=[crf.accuracy])\n    model.summary()\n\n    return model\n"
  },
  {
    "path": "code/run.sh",
    "content": "#python cnn_model.py > cnn_logs.txt\n#python cnn_crf_model.py > cnn_crf_logs.txt\n#python lstm_model.py > lstm_logs.txt\npython cnn_crf_model_20_folds.py > cnn_crf_folds_logs.txt"
  },
  {
    "path": "code/utils.py",
    "content": "import h5py\nimport numpy as np\nimport random\n\nWINDOW_SIZE = 100\n\ndef rescale_array(X):\n    X = X / 20\n    X = np.clip(X, -5, 5)\n    return X\n\n\ndef aug_X(X):\n    scale = 1 + np.random.uniform(-0.1, 0.1)\n    offset = np.random.uniform(-0.1, 0.1)\n    noise = np.random.normal(scale=0.05, size=X.shape)\n    X = scale * X + offset + noise\n    return X\n\ndef gen(dict_files, aug=False):\n    while True:\n        record_name = random.choice(list(dict_files.keys()))\n        batch_data = dict_files[record_name]\n        all_rows = batch_data['x']\n\n        for i in range(10):\n            start_index = random.choice(range(all_rows.shape[0]-WINDOW_SIZE))\n\n            X = all_rows[start_index:start_index+WINDOW_SIZE, ...]\n            Y = batch_data['y'][start_index:start_index+WINDOW_SIZE]\n\n            X = np.expand_dims(X, 0)\n            Y = np.expand_dims(Y, -1)\n            Y = np.expand_dims(Y, 0)\n\n            if aug:\n                X = aug_X(X)\n            X = rescale_array(X)\n\n            yield X, Y\n\n\ndef chunker(seq, size=WINDOW_SIZE):\n    return (seq[pos:pos + size] for pos in range(0, len(seq), size))"
  },
  {
    "path": "deepsleepnet_data/dhedfreader.py",
    "content": "#Source : https://github.com/akaraspt/deepsleepnet\n\n'''\nReader for EDF+ files.\nTODO:\n - add support for log-transformed channels:\n   http://www.edfplus.info/specs/edffloat.html and test with\n   data generated with\n   http://www.edfplus.info/downloads/software/NeuroLoopGain.zip.\n - check annotations with Schalk's Physiobank data.\nCopyright (c) 2012 Boris Reuderink.\n'''\n\nimport re, datetime, operator, logging\nimport numpy as np\nfrom collections import namedtuple\n\nEVENT_CHANNEL = 'EDF Annotations'\nlog = logging.getLogger(__name__)\n\nclass EDFEndOfData: pass\n\n\ndef tal(tal_str):\n  '''Return a list with (onset, duration, annotation) tuples for an EDF+ TAL\n  stream.\n  '''\n  exp = '(?P<onset>[+\\-]\\d+(?:\\.\\d*)?)' + \\\n    '(?:\\x15(?P<duration>\\d+(?:\\.\\d*)?))?' + \\\n    '(\\x14(?P<annotation>[^\\x00]*))?' + \\\n    '(?:\\x14\\x00)'\n\n  def annotation_to_list(annotation):\n    return unicode(annotation, 'utf-8').split('\\x14') if annotation else []\n\n  def parse(dic):\n    return (\n      float(dic['onset']),\n      float(dic['duration']) if dic['duration'] else 0.,\n      annotation_to_list(dic['annotation']))\n\n  return [parse(m.groupdict()) for m in re.finditer(exp, tal_str)]\n\n\ndef edf_header(f):\n  h = {}\n  assert f.tell() == 0  # check file position\n  assert f.read(8) == '0       '\n\n  # recording info)\n  h['local_subject_id'] = f.read(80).strip()\n  h['local_recording_id'] = f.read(80).strip()\n\n  # parse timestamp\n  (day, month, year) = [int(x) for x in re.findall('(\\d+)', f.read(8))]\n  (hour, minute, sec)= [int(x) for x in re.findall('(\\d+)', f.read(8))]\n  h['date_time'] = str(datetime.datetime(year + 2000, month, day,\n    hour, minute, sec))\n\n  # misc\n  header_nbytes = int(f.read(8))\n  subtype = f.read(44)[:5]\n  h['EDF+'] = subtype in ['EDF+C', 'EDF+D']\n  h['contiguous'] = subtype != 'EDF+D'\n  h['n_records'] = int(f.read(8))\n  h['record_length'] = float(f.read(8))  # in seconds\n  nchannels = h['n_channels'] = int(f.read(4))\n\n  # read channel info\n  channels = range(h['n_channels'])\n  h['label'] = [f.read(16).strip() for n in channels]\n  h['transducer_type'] = [f.read(80).strip() for n in channels]\n  h['units'] = [f.read(8).strip() for n in channels]\n  h['physical_min'] = np.asarray([float(f.read(8)) for n in channels])\n  h['physical_max'] = np.asarray([float(f.read(8)) for n in channels])\n  h['digital_min'] = np.asarray([float(f.read(8)) for n in channels])\n  h['digital_max'] = np.asarray([float(f.read(8)) for n in channels])\n  h['prefiltering'] = [f.read(80).strip() for n in channels]\n  h['n_samples_per_record'] = [int(f.read(8)) for n in channels]\n  f.read(32 * nchannels)  # reserved\n\n  assert f.tell() == header_nbytes\n  return h\n\n\nclass BaseEDFReader:\n  def __init__(self, file):\n    self.file = file\n\n\n  def read_header(self):\n    self.header = h = edf_header(self.file)\n\n    # calculate ranges for rescaling\n    self.dig_min = h['digital_min']\n    self.phys_min = h['physical_min']\n    phys_range = h['physical_max'] - h['physical_min']\n    dig_range = h['digital_max'] - h['digital_min']\n    assert np.all(phys_range > 0)\n    assert np.all(dig_range > 0)\n    self.gain = phys_range / dig_range\n\n\n  def read_raw_record(self):\n    '''Read a record with data and return a list containing arrays with raw\n    bytes.\n    '''\n    result = []\n    for nsamp in self.header['n_samples_per_record']:\n      samples = self.file.read(nsamp * 2)\n      if len(samples) != nsamp * 2:\n        raise EDFEndOfData\n      result.append(samples)\n    return result\n\n\n  def convert_record(self, raw_record):\n    '''Convert a raw record to a (time, signals, events) tuple based on\n    information in the header.\n    '''\n    h = self.header\n    dig_min, phys_min, gain = self.dig_min, self.phys_min, self.gain\n    time = float('nan')\n    signals = []\n    events = []\n    for (i, samples) in enumerate(raw_record):\n      if h['label'][i] == EVENT_CHANNEL:\n        ann = tal(samples)\n        time = ann[0][0]\n        events.extend(ann[1:])\n        # print(i, samples)\n        # exit()\n      else:\n        # 2-byte little-endian integers\n        dig = np.fromstring(samples, '<i2').astype(np.float32)\n        phys = (dig - dig_min[i]) * gain[i] + phys_min[i]\n        signals.append(phys)\n\n    return time, signals, events\n\n\n  def read_record(self):\n    return self.convert_record(self.read_raw_record())\n\n\n  def records(self):\n    '''\n    Record generator.\n    '''\n    try:\n      while True:\n        yield self.read_record()\n    except EDFEndOfData:\n      pass\n\n\ndef load_edf(edffile):\n  '''Load an EDF+ file.\n  Very basic reader for EDF and EDF+ files. While BaseEDFReader does support\n  exotic features like non-homogeneous sample rates and loading only parts of\n  the stream, load_edf expects a single fixed sample rate for all channels and\n  tries to load the whole file.\n  Parameters\n  ----------\n  edffile : file-like object or string\n  Returns\n  -------\n  Named tuple with the fields:\n    X : NumPy array with shape p by n.\n      Raw recording of n samples in p dimensions.\n    sample_rate : float\n      The sample rate of the recording. Note that mixed sample-rates are not\n      supported.\n    sens_lab : list of length p with strings\n      The labels of the sensors used to record X.\n    time : NumPy array with length n\n      The time offset in the recording for each sample.\n    annotations : a list with tuples\n      EDF+ annotations are stored in (start, duration, description) tuples.\n      start : float\n        Indicates the start of the event in seconds.\n      duration : float\n        Indicates the duration of the event in seconds.\n      description : list with strings\n        Contains (multiple?) descriptions of the annotation event.\n  '''\n  if isinstance(edffile, basestring):\n    with open(edffile, 'rb') as f:\n      return load_edf(f)  # convert filename to file\n\n  reader = BaseEDFReader(edffile)\n  reader.read_header()\n\n  h = reader.header\n  log.debug('EDF header: %s' % h)\n\n  # get sample rate info\n  nsamp = np.unique(\n    [n for (l, n) in zip(h['label'], h['n_samples_per_record'])\n    if l != EVENT_CHANNEL])\n  assert nsamp.size == 1, 'Multiple sample rates not supported!'\n  sample_rate = float(nsamp[0]) / h['record_length']\n\n  rectime, X, annotations = zip(*reader.records())\n  X = np.hstack(X)\n  annotations = reduce(operator.add, annotations)\n  chan_lab = [lab for lab in reader.header['label'] if lab != EVENT_CHANNEL]\n\n  # create timestamps\n  if reader.header['contiguous']:\n    time = np.arange(X.shape[1]) / sample_rate\n  else:\n    reclen = reader.header['record_length']\n    within_rec_time = np.linspace(0, reclen, nsamp, endpoint=False)\n    time = np.hstack([t + within_rec_time for t in rectime])\n\n  tup = namedtuple('EDF', 'X sample_rate chan_lab time annotations')\n  return tup(X, sample_rate, chan_lab, time, annotations)\n"
  },
  {
    "path": "deepsleepnet_data/download_physionet.sh",
    "content": "#Source : https://github.com/akaraspt/deepsleepnet\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4001E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4001E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4001EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4002E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4002E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4002EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4011E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4011E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4011EH-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4012E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4012E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4012EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4021E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4021E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4021EH-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4022E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4022E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4022EJ-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4031E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4031E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4031EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4032E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4032E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4032EP-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4041E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4041E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4041EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4042E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4042E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4042EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4051E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4051E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4051EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4052E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4052E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4052EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4061E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4061E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4061EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4062E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4062E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4062EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4071E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4071E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4071EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4072E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4072E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4072EH-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4081E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4081E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4081EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4082E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4082E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4082EP-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4091E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4091E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4091EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4092E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4092E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4092EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4101E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4101E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4101EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4102E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4102E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4102EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4111E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4111E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4111EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4112E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4112E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4112EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4121E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4121E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4121EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4122E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4122E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4122EV-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4131E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4131E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4131EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4141E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4141E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4141EU-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4142E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4142E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4142EU-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4151E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4151E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4151EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4152E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4152E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4152EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4161E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4161E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4161EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4162E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4162E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4162EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4171E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4171E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4171EU-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4172E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4172E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4172EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4181E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4181E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4181EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4182E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4182E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4182EC-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4191E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4191E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4191EP-Hypnogram.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4192E0-PSG.edf\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4192E0-PSG.edf.hyp\nwget https://www.physionet.org/physiobank/database/sleep-edfx/sleep-cassette/SC4192EV-Hypnogram.edf\n"
  },
  {
    "path": "deepsleepnet_data/prepare_physionet.py",
    "content": "#Source : https://github.com/akaraspt/deepsleepnet\n\nimport argparse\nimport glob\nimport math\nimport ntpath\nimport os\nimport shutil\nimport urllib\nimport urllib2\n\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\n\nfrom mne import Epochs, pick_types, find_events\nfrom mne.io import concatenate_raws, read_raw_edf\n\nimport dhedfreader\n\n\n# Label values\nW = 0\nN1 = 1\nN2 = 2\nN3 = 3\nREM = 4\nUNKNOWN = 5\n\nstage_dict = {\n    \"W\": W,\n    \"N1\": N1,\n    \"N2\": N2,\n    \"N3\": N3,\n    \"REM\": REM,\n    \"UNKNOWN\": UNKNOWN\n}\n\nclass_dict = {\n    0: \"W\",\n    1: \"N1\",\n    2: \"N2\",\n    3: \"N3\",\n    4: \"REM\",\n    5: \"UNKNOWN\"\n}\n\nann2label = {\n    \"Sleep stage W\": 0,\n    \"Sleep stage 1\": 1,\n    \"Sleep stage 2\": 2,\n    \"Sleep stage 3\": 3,\n    \"Sleep stage 4\": 3,\n    \"Sleep stage R\": 4,\n    \"Sleep stage ?\": 5,\n    \"Movement time\": 5\n}\n\nEPOCH_SEC_SIZE = 30\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--data_dir\", type=str, default=\"/data/physionet_sleep\",\n                        help=\"File path to the CSV or NPY file that contains walking data.\")\n    parser.add_argument(\"--output_dir\", type=str, default=\"/data/physionet_sleep/eeg_fpz_cz\",\n                        help=\"Directory where to save outputs.\")\n    parser.add_argument(\"--select_ch\", type=str, default=\"EEG Fpz-Cz\",\n                        help=\"File path to the trained model used to estimate walking speeds.\")\n    args = parser.parse_args()\n\n    # Output dir\n    if not os.path.exists(args.output_dir):\n        os.makedirs(args.output_dir)\n    else:\n        shutil.rmtree(args.output_dir)\n        os.makedirs(args.output_dir)\n\n    # Select channel\n    select_ch = args.select_ch\n\n    # Read raw and annotation EDF files\n    psg_fnames = glob.glob(os.path.join(args.data_dir, \"*PSG.edf\"))\n    ann_fnames = glob.glob(os.path.join(args.data_dir, \"*Hypnogram.edf\"))\n    psg_fnames.sort()\n    ann_fnames.sort()\n    psg_fnames = np.asarray(psg_fnames)\n    ann_fnames = np.asarray(ann_fnames)\n\n    for i in range(len(psg_fnames)):\n        # if not \"ST7171J0-PSG.edf\" in psg_fnames[i]:\n        #     continue\n\n        raw = read_raw_edf(psg_fnames[i], preload=True, stim_channel=None)\n        sampling_rate = raw.info['sfreq']\n        raw_ch_df = raw.to_data_frame(scaling_time=100.0)[select_ch]\n        raw_ch_df = raw_ch_df.to_frame()\n        raw_ch_df.set_index(np.arange(len(raw_ch_df)))\n\n        # Get raw header\n        f = open(psg_fnames[i], 'r')\n        reader_raw = dhedfreader.BaseEDFReader(f)\n        reader_raw.read_header()\n        h_raw = reader_raw.header\n        f.close()\n        raw_start_dt = datetime.strptime(h_raw['date_time'], \"%Y-%m-%d %H:%M:%S\")\n\n        # Read annotation and its header\n        f = open(ann_fnames[i], 'r')\n        reader_ann = dhedfreader.BaseEDFReader(f)\n        reader_ann.read_header()\n        h_ann = reader_ann.header\n        _, _, ann = zip(*reader_ann.records())\n        f.close()\n        ann_start_dt = datetime.strptime(h_ann['date_time'], \"%Y-%m-%d %H:%M:%S\")\n\n        # Assert that raw and annotation files start at the same time\n        assert raw_start_dt == ann_start_dt\n\n        # Generate label and remove indices\n        remove_idx = []    # indicies of the data that will be removed\n        labels = []        # indicies of the data that have labels\n        label_idx = []\n        for a in ann[0]:\n            onset_sec, duration_sec, ann_char = a\n            ann_str = \"\".join(ann_char)\n            label = ann2label[ann_str]\n            if label != UNKNOWN:\n                if duration_sec % EPOCH_SEC_SIZE != 0:\n                    raise Exception(\"Something wrong\")\n                duration_epoch = int(duration_sec / EPOCH_SEC_SIZE)\n                label_epoch = np.ones(duration_epoch, dtype=np.int) * label\n                labels.append(label_epoch)\n                idx = int(onset_sec * sampling_rate) + np.arange(duration_sec * sampling_rate, dtype=np.int)\n                label_idx.append(idx)\n\n                print \"Include onset:{}, duration:{}, label:{} ({})\".format(\n                    onset_sec, duration_sec, label, ann_str\n                )\n            else:\n                idx = int(onset_sec * sampling_rate) + np.arange(duration_sec * sampling_rate, dtype=np.int)\n                remove_idx.append(idx)\n\n                print \"Remove onset:{}, duration:{}, label:{} ({})\".format(\n                    onset_sec, duration_sec, label, ann_str\n                )\n        labels = np.hstack(labels)\n        \n        print \"before remove unwanted: {}\".format(np.arange(len(raw_ch_df)).shape)\n        if len(remove_idx) > 0:\n            remove_idx = np.hstack(remove_idx)\n            select_idx = np.setdiff1d(np.arange(len(raw_ch_df)), remove_idx)\n        else:\n            select_idx = np.arange(len(raw_ch_df))\n        print \"after remove unwanted: {}\".format(select_idx.shape)\n\n        # Select only the data with labels\n        print \"before intersect label: {}\".format(select_idx.shape)\n        label_idx = np.hstack(label_idx)\n        select_idx = np.intersect1d(select_idx, label_idx)\n        print \"after intersect label: {}\".format(select_idx.shape)\n\n        # Remove extra index\n        if len(label_idx) > len(select_idx):\n            print \"before remove extra labels: {}, {}\".format(select_idx.shape, labels.shape)\n            extra_idx = np.setdiff1d(label_idx, select_idx)\n            # Trim the tail\n            if np.all(extra_idx > select_idx[-1]):\n                n_trims = len(select_idx) % int(EPOCH_SEC_SIZE * sampling_rate)\n                n_label_trims = int(math.ceil(n_trims / (EPOCH_SEC_SIZE * sampling_rate)))\n                select_idx = select_idx[:-n_trims]\n                labels = labels[:-n_label_trims]\n            print \"after remove extra labels: {}, {}\".format(select_idx.shape, labels.shape)\n\n        # Remove movement and unknown stages if any\n        raw_ch = raw_ch_df.values[select_idx]\n\n        # Verify that we can split into 30-s epochs\n        if len(raw_ch) % (EPOCH_SEC_SIZE * sampling_rate) != 0:\n            raise Exception(\"Something wrong\")\n        n_epochs = len(raw_ch) / (EPOCH_SEC_SIZE * sampling_rate)\n\n        # Get epochs and their corresponding labels\n        x = np.asarray(np.split(raw_ch, n_epochs)).astype(np.float32)\n        y = labels.astype(np.int32)\n\n        assert len(x) == len(y)\n\n        # Select on sleep periods\n        w_edge_mins = 30\n        nw_idx = np.where(y != stage_dict[\"W\"])[0]\n        start_idx = nw_idx[0] - (w_edge_mins * 2)\n        end_idx = nw_idx[-1] + (w_edge_mins * 2)\n        if start_idx < 0: start_idx = 0\n        if end_idx >= len(y): end_idx = len(y) - 1\n        select_idx = np.arange(start_idx, end_idx+1)\n        print(\"Data before selection: {}, {}\".format(x.shape, y.shape))\n        x = x[select_idx]\n        y = y[select_idx]\n        print(\"Data after selection: {}, {}\".format(x.shape, y.shape))\n\n        # Save\n        filename = ntpath.basename(psg_fnames[i]).replace(\"-PSG.edf\", \".npz\")\n        save_dict = {\n            \"x\": x, \n            \"y\": y, \n            \"fs\": sampling_rate,\n            \"ch_label\": select_ch,\n            \"header_raw\": h_raw,\n            \"header_annotation\": h_ann,\n        }\n        np.savez(os.path.join(args.output_dir, filename), **save_dict)\n\n        print \"\\n=======================================\\n\"\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "deepsleepnet_data/readme.md",
    "content": "The files in this folders were copied with minor modifications from #Source : https://github.com/akaraspt/deepsleepnet\n\n#To get the dataset :\n\ncd data\nchmod +x download_physionet.sh\n./download_physionet.sh\n\n###Those scripts taken from the deepsleepnet only work with python2\npython2 prepare_physionet.py --data_dir data --output_dir data/eeg_fpz_cz --select_ch 'EEG Fpz-Cz'\n\nThis subfolder is under the following license : \n\nCopyright 2017 Akara Supratak and Hao Dong.  All rights reserved.\n\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2017 Akara Supratak and Hao Dong\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "requirements.txt",
    "content": "librosa==0.5.1\nnumpy==1.15.2\nKeras==2.2.2\ntqdm==4.23.2\nkeras_contrib==2.0.8\nh5py==2.8.0\nmatplotlib==2.1.0\nscikit_learn==0.20.0\n"
  }
]