{"cells":[{"metadata":{},"cell_type":"markdown","source":"Earthquake prediction notebook based on the Shaking Earth notebook by Allunia"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nsns.set()\nfrom IPython.display import HTML\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from os import listdir\nprint(listdir('/kaggle/input/LANL-Earthquake-Prediction'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"the_dir = r'/kaggle/input/LANL-Earthquake-Prediction'\ntrain_data = os.path.join(the_dir, 'train.csv')\ntrain = pd.read_csv(train_data, nrows=10000000,\n                   dtype={'acoustic_data': np.int16, 'time_to_failure': np.float64})\ntrain.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.rename({'acoustic_data':'signal', 'time_to_failure':'quaketime'}, axis='columns', inplace=True)\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for n in range(5):\n    print(train.quaketime.values[n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(2,1, figsize=(20,12))\nax[0].plot(train.index.values, train.quaketime.values, c='darkred')\nax[0].set_title('Quaketime for 10mil rows')\nax[0].set_xlabel('index')\nax[0].set_ylabel('Quaketime in ms')\n\nax[1].plot(train.index.values, train.signal.values, c='darkgreen')\nax[1].set_title('Signal for 10mil rows')\nax[1].set_xlabel('index')\nax[1].set_ylabel('Acoustic signal')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(3,1, figsize=(20,18))\nax[0].plot(train.index.values[0:50000], train.quaketime.values[0:50000], c='r')\nax[0].set_ylabel('quaketime')\nax[0].set_xlabel('index')\nax[0].set_title('how does the second quaketime pattern look like?')\n\nax[1].plot(train.index.values[0:49999], np.diff(train.quaketime.values[0:50000]), c='g')\nax[1].set_ylabel('quaketime difference')\nax[1].set_xlabel('index')\nax[1].set_title('Are the jumps always the same?')\n\nax[2].plot(train.index.values[0:4000], train.quaketime.values[0:4000], c='b')\nax[2].set_ylabel('quaketime')\nax[2].set_xlabel('index')\nax[2].set_title('how does the second quaketime pattern look like?')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_path = os.path.join(the_dir,'test')\ntest_files = os.listdir(test_path)\nprint(test_files)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(test_files))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission = pd.read_csv(os.path.join(the_dir, 'sample_submission.csv'))\nsample_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(sample_submission.seg_id.values)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(4,1, figsize=(20,25))\n\nfor n in range(4):\n    seg = pd.read_csv(os.path.join(test_path,test_files[n]))\n    ax[n].plot(seg.acoustic_data.values, c='g')\n    ax[n].set_xlabel('index')\n    ax[n].set_ylabel('signal')\n    ax[n].set_title(\"Test {}\".format(test_files[n]))\n    ax[n].set_ylim(-300, 300)\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(1,2, figsize=(20,5))\nsns.distplot(train.signal.values, ax=ax[0], color='r', bins=100, kde=False)\nax[0].set_xlabel('signal')\nax[0].set_ylabel('density')\nax[0].set_title('signal distribution')\n\nlow = train.signal.mean() - 3*train.signal.std()\nhigh = train.signal.mean() + 3*train.signal.std()\nsns.distplot(train.loc[(train.signal >= low) & (train.signal <= high), 'signal'].values,\n            ax=ax[1],\n            color='Orange',\n            bins=150,\n            kde=False\n            )\nax[1].set_xlabel('signal')\nax[1].set_ylabel('density')\nax[1].set_title('signal distribution with out peak')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"stepsize = np.diff(train.quaketime)\ntrain = train.drop(train.index[len(train)-1])\ntrain['stepsize'] = stepsize\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train.stepsize = train.stepsize.apply(lambda l: np.around(1, decimals=10))\n# train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# stepsize_counts = train.stepsize.value_counts()\n# stepsize_counts","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import TimeSeriesSplit\n\ncs = TimeSeriesSplit(n_splits=5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"window_sizes = [10,50,100,1000]\nfor window in window_sizes:\n    train['rolling_mean_' + str(window)] = train.signal.rolling(window=window).mean()\n    train['rolling_std_' + str(window)] = train.signal.rolling(window=window).std()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(len(window_sizes), 1, figsize=(20, 6*len(window_sizes)))\n\nn=0\nfor col in train.columns.values:\n    if \"rolling_\" in col:\n        if 'mean' in col:\n            mean_df = train.iloc[4435000:4445000][col]\n            ax[n].plot(mean_df, label=col, color='darkgreen')\n        if 'std' in col:\n            std = train.iloc[4435000:4445000][col].values\n            ax[n].fill_between(mean_df.index.values,\n                              mean_df.values-std, \n                              mean_df.values+std, \n                              facecolor='lightgreen',\n                              alpha=0.5,\n                              label=col)\n            ax[n].legend()\n            n+=1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train[\"rolling_q25\"] = train.signal.rolling(window=50).quantile(0.25)\ntrain[\"rolling_q75\"] = train.signal.rolling(window=50).quantile(0.75)\ntrain[\"rolling_q50\"] = train.signal.rolling(window=50).quantile(0.5)\ntrain[\"rolling_iqr\"] = train.rolling_q75 - train.rolling_q25\ntrain[\"rolling_min\"] = train.signal.rolling(window=50).min()\ntrain[\"rolling_max\"] = train.signal.rolling(window=50).max()\ntrain[\"rolling_skew\"] = train.signal.rolling(window=50).skew()\ntrain[\"rolling_kurt\"] = train.signal.rolling(window=50).kurt()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}