{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport gc\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import mean_squared_error\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 sklearn.linear_model import SGDRegressor\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import HuberRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nimport xgboost as xgb\n\nimport os\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n    #for filename in filenames:\n        #print(os.path.join(dirname, filename))\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n        \nfrom sklearn.decomposition import PCA\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom scipy.ndimage import maximum_filter1d\nfrom scipy.ndimage import minimum_filter1d\n\nfrom datetime import datetime\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import StandardScaler\nStSc = StandardScaler()\nMMS = MinMaxScaler()\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(datetime.now())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"V_PATH = '/kaggle/input/predict-volcanic-eruptions-ingv-oe/'\nTRAIN_PATH = V_PATH + 'train/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SENSOR_COLS = ['sensor_1', 'sensor_2', 'sensor_3', 'sensor_4', 'sensor_5', 'sensor_6',\n       'sensor_7', 'sensor_8', 'sensor_9', 'sensor_10']\n\n\nSENSOR_RMEANS = [x+'_rmin' for x in SENSOR_COLS] \nSENSOR_RSTDS = [x+'_rstd' for x in SENSOR_COLS] \nSENSOR_RMINS = [x+'_rmin' for x in SENSOR_COLS] \nSENSOR_RMAXES = [x+'_rmax' for x in SENSOR_COLS]\nSENSOR_RGRADMEAN = [x+'_grad_rmean' for x in SENSOR_COLS]\nSENSOR_RGRADSTD = [x+'_grad_rstd' for x in SENSOR_COLS]\n\nSENSOR_RSTATS = [SENSOR_RMEANS, SENSOR_RSTDS, SENSOR_RMINS, SENSOR_RMAXES,\n               SENSOR_RGRADMEAN,  SENSOR_RGRADSTD]\n\nROLL_DESCR = ['rmin', 'rstd', 'rmin', 'rmax', 'grad_rmean','grad_rstd']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(V_PATH+'train.csv')\nprint(train.shape)\nprint(train.columns)\ntrain.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total_rows_estimate = 60001 * len(train) / 1000000\nprint('estimate of total TRAIN rows (millions)',total_rows_estimate)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission = pd.read_csv(V_PATH+'sample_submission.csv')\nprint(sample_submission.shape)\nprint(sample_submission.columns)\n\ntotal_rows_estimate = 60001 * len(sample_submission) / 1000000\nprint('estimate of total TEST rows (millions)',total_rows_estimate)\n\nsample_submission.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#examine the distribution of time until eruption\n\nsns.kdeplot(train['time_to_eruption'] / 1000000)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train['time_to_eruption'].min(), train['time_to_eruption'].max(), train['time_to_eruption'].mean())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sz = train['time_to_eruption'].size-1\ntrain['PCNT_TIME'] = train['time_to_eruption'].rank(method='max').apply(lambda x: 1.0*(x-1)/sz)\ntrain.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_rolling(df, cols, window=50):\n    for col in cols:\n        df[col+'_grad'] = np.gradient(df[col])\n        df[col+'_grad'] = df[col+'_grad'].fillna(method='bfill').fillna(method='ffill')\n        \n        df[col+'_grad_abs'] = np.gradient(np.abs(df[col]))\n        df[col+'_grad'] = df[col+'_grad'].fillna(method='bfill').fillna(method='ffill')\n        \n        df[col+'_rmin'] = minimum_filter1d(df[col].values, size=window)\n        df[col+'_rmax'] = maximum_filter1d(df[col].values, size=window)\n        \n        df[col+'_rmin'] = df[col+'_rmin'].fillna(method='bfill').fillna(method='ffill')\n        df[col+'_rmax'] = df[col+'_rmax'].fillna(method='bfill').fillna(method='ffill')\n        \n        df[col+'_rmean'] = df[col].rolling(window=window, center=True).mean().fillna(method='bfill').fillna(method='ffill')\n        df[col+'_rstd'] = df[col].rolling(window=window, center=True).std().fillna(method='bfill').fillna(method='ffill')\n        \n        #add also for gradients\n        df[col+'_grad_rmin'] = minimum_filter1d(df[col+'_grad_abs'].values, size=window)\n        df[col+'_grad_rmax'] = maximum_filter1d(df[col+'_grad_abs'].values, size=window)\n        \n        df[col+'_grad_rmin'] = df[col+'_grad_rmin'].fillna(method='bfill').fillna(method='ffill')\n        df[col+'_grad_rmax'] = df[col+'_grad_rmax'].fillna(method='bfill').fillna(method='ffill')\n        \n        df[col+'_grad_rmean'] = df[col+'_grad_abs'].rolling(window=window, center=True).mean().fillna(method='bfill').fillna(method='ffill')\n        df[col+'_grad_rstd'] = df[col+'_grad_abs'].rolling(window=window, center=True).std().fillna(method='bfill').fillna(method='ffill')\n        \n    return df\n\ndef get_stats(df, sensor_cols=SENSOR_COLS, rolling_cols=SENSOR_RSTATS):\n    #we create the min max etc of original sensor columns\n    df['max'] = df[sensor_cols].max(axis=1)\n    df['min'] = df[sensor_cols].min(axis=1)\n    df['std'] = df[sensor_cols].std(axis=1)\n    \n    #and with absolute values\n    df['max_abs'] = np.abs(df[sensor_cols]).max(axis=1)\n    df['min_abs'] = np.abs(df[sensor_cols]).min(axis=1)\n    df['std_abs'] = np.abs(df[sensor_cols]).std(axis=1)\n    \n    #we take mins and maxes of groups of rolling columns\n    for count,rc in enumerate(rolling_cols): #this takes a SINGLE mean, max across each GROUP of rolling\n        #columns - e.g. the max of all rolling mins\n        df[ROLL_DESCR[count]+'_max'] = df[rolling_cols[count]].max(axis=1)\n        df[ROLL_DESCR[count]+'_min'] = df[rolling_cols[count]].min(axis=1)\n        df[ROLL_DESCR[count]+'_std'] = df[rolling_cols[count]].std(axis=1)\n        df[ROLL_DESCR[count]+'_mean'] = df[rolling_cols[count]].mean(axis=1)    \n   \n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#credit - stack overflow\n\ndef percentile(n):\n    def percentile_(x):\n        return np.percentile(x, n)\n    percentile_.__name__ = 'percentile_%s' % n\n    return percentile_","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#lets drop the rolling mean - does not seem that useful\n\ndef get_all_stats(df, cols, rolling_cols, window=50):\n    \n    df = get_rolling(df, cols, window=window)\n    df = get_stats(df, sensor_cols=cols, rolling_cols=rolling_cols)\n    df = df.groupby(['segment'])[[x for x in df.columns if x != 'segment']].agg(['mean','max','skew','std',\n                                    percentile(0.1),percentile(0.25),\n                                        percentile(0.75),percentile(0.9)])\n    df.columns=[a+b for a,b in df.columns]\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nprint(datetime.now())\n#SAMPLE_COUNT = 200\n\n#sample_index = train.sample(n=SAMPLE_COUNT).index\nsample_index = train.index\nprint('number of samples', len(sample_index))\n\nloaded_dfs = pd.DataFrame()\n\nfor count,S in enumerate(sample_index):\n    \n    s_ID = train.loc[S, 'segment_id']\n    q = train.loc[S, 'PCNT_TIME']\n    print(s_ID)\n    \n    temp_df = pd.read_csv(TRAIN_PATH+str(s_ID)+'.csv')\n    print('count NAs Percent, ', temp_df.isna().sum().sum() / len(temp_df.values.flatten()))\n    #for col in temp_df.columns:\n    temp_df = temp_df.fillna(method='ffill').fillna(method='bfill')\n    temp_df = temp_df.fillna(value=0)\n    print('count NAs Percent, ', temp_df.isna().sum().sum() / len(temp_df.values.flatten()))\n    temp_df['time_to_eruption'] = q\n    temp_df['segment'] = s_ID\n    \n    temp_df = get_all_stats(temp_df, SENSOR_COLS, SENSOR_RSTATS, window=50)      \n    \n    print(temp_df.shape)    \n    loaded_dfs = pd.concat([loaded_dfs, temp_df], axis=0)\n    print(loaded_dfs.shape) \n    print('    ')\nloaded_dfs = loaded_dfs.reset_index(drop=True) \nprint(' Total DF Size ',loaded_dfs.shape)\nloaded_dfs.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loaded_dfs.to_csv('volcano_train_fts.csv', index=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(datetime.now())","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}