{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"# Credit goes to the top solution of the previous earthquake competition","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\nfrom glob import glob\n\nimport os\nimport dask.dataframe as dd\n\nfrom tsfresh.feature_extraction import feature_calculators\nimport librosa\nimport pywt\n\nfrom joblib import Parallel, delayed\nfrom tqdm import tqdm_notebook\nimport scipy as sp\nimport itertools\nimport gc\n\nfrom sklearn.metrics import mean_absolute_error\nfrom lightgbm import LGBMRegressor\nfrom catboost import CatBoostRegressor\nfrom xgboost import XGBRegressor\nimport lightgbm as lgb\nimport gc\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/predict-volcanic-eruptions-ingv-oe/train.csv')\ntrain['segment_id'] = train['segment_id'].astype(str)\ntrain = train.sort_values('segment_id')\ny = train['time_to_eruption']\ndel(train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_paths = sorted(glob('/kaggle/input/predict-volcanic-eruptions-ingv-oe/train/*'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/predict-volcanic-eruptions-ingv-oe/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#+- 600\n# std 100,800\n# plt.plot(train_sample['sensor_1'].rolling(10).std())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.random.seed(1337)\nnoise = np.random.normal(-10, 200, 60_001)\n\n\ndef denoise_signal_simple(x, wavelet='db4', level=1):\n    coeff = pywt.wavedec(x, wavelet, mode=\"per\")\n    #univeral threshold\n    uthresh = 10\n    coeff[1:] = (pywt.threshold(i, value=uthresh, mode='hard') for i in coeff[1:])\n    # Reconstruct the signal using the thresholded coefficients\n    return pywt.waverec(coeff, wavelet, mode='per')\n\n\ndef feature_gen(path):\n    X = (pd.read_csv(path).fillna(200).values.T + noise).T\n    z = X - np.median(X,axis=0)\n    features = []\n    for i in range(X.shape[1]):\n        sig = z[:,i]\n        den_sample_simple = denoise_signal_simple(sig)\n        mfcc = librosa.feature.mfcc(sig)\n        mfcc_mean = mfcc.mean(axis=1)\n        percentile_roll50_std_20 = np.percentile(pd.Series(sig).rolling(50).std().dropna().values, 20)\n        features.extend([feature_calculators.number_peaks(den_sample_simple, 2),percentile_roll50_std_20,mfcc_mean[18],mfcc_mean[4]])\n    return features","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntrain_samples = [Parallel(n_jobs=4)(delayed(feature_gen)(train_path) for train_path in tqdm_notebook(train_paths))]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_samples = np.array(train_samples).reshape(-1,40)\n# del(samples)\ndel(train_paths)\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cat = CatBoostRegressor(loss_function='MAE',iterations = 5000)\ncat.fit(train_samples,y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(mean_absolute_error(y,cat.predict(train_samples)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_paths = sorted(glob('/kaggle/input/predict-volcanic-eruptions-ingv-oe/test/*'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntest_samples = [Parallel(n_jobs=4)(delayed(feature_gen)(test_path) for test_path in tqdm_notebook(test_paths))]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# len(train_paths), len(test_paths)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_samples = np.array(test_samples).reshape(-1,40)\ndel(test_paths)\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = cat.predict(test_samples)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub['time_to_eruption'] = preds","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.to_csv('submission.csv', header=True, index=False)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}