{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-white')\n%matplotlib inline\n\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nimport lightgbm as lgbm\nfrom lightgbm import LGBMRegressor\nfrom xgboost import XGBRegressor\nfrom tqdm import tqdm\n\nfile_list = []\nfile_list_train = []\nfile_list_test = []\n\n\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        file_list.append(os.path.join(dirname, filename))\n        \nPATH = '/kaggle/input/predict-volcanic-eruptions-ingv-oe/'\n\nfor dirname, _, filenames in os.walk('/kaggle/input/predict-volcanic-eruptions-ingv-oe/train'):\n    for filename in filenames:\n        file_list_train.append(os.path.join(dirname, filename))\n        \nfor dirname, _, filenames in os.walk('/kaggle/input/predict-volcanic-eruptions-ingv-oe/test'):\n    for filename in filenames:\n        file_list_test.append(os.path.join(dirname, filename))","metadata":{"execution":{"iopub.status.busy":"2022-12-23T01:37:35.500159Z","iopub.execute_input":"2022-12-23T01:37:35.500700Z","iopub.status.idle":"2022-12-23T01:37:46.451028Z","shell.execute_reply.started":"2022-12-23T01:37:35.500584Z","shell.execute_reply":"2022-12-23T01:37:46.449841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Segment_id - номер сегменту з якого знімаються покази датчиків. Time_to_eruption - час до виверження","metadata":{}},{"cell_type":"code","source":"print(file_list[0])\n\n\nprint(pd.read_csv(file_list[0]))\nprint(pd.read_csv(file_list[0]).isna().sum())","metadata":{"execution":{"iopub.status.busy":"2022-12-23T01:37:46.453361Z","iopub.execute_input":"2022-12-23T01:37:46.453660Z","iopub.status.idle":"2022-12-23T01:37:46.484733Z","shell.execute_reply.started":"2022-12-23T01:37:46.453633Z","shell.execute_reply":"2022-12-23T01:37:46.483980Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Папка train містить файли з показниками показів датчиків","metadata":{}},{"cell_type":"markdown","source":"Десять хвилин журналів від десяти різних датчиків, розташованих навколо вулкана","metadata":{}},{"cell_type":"code","source":"print(file_list_train[0])\nprint(pd.read_csv(file_list_train[0]))","metadata":{"execution":{"iopub.status.busy":"2022-12-23T01:37:46.486344Z","iopub.execute_input":"2022-12-23T01:37:46.486721Z","iopub.status.idle":"2022-12-23T01:37:46.617056Z","shell.execute_reply.started":"2022-12-23T01:37:46.486691Z","shell.execute_reply":"2022-12-23T01:37:46.615806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(file_list[1])\nprint(pd.read_csv(file_list[1]))","metadata":{"execution":{"iopub.status.busy":"2022-12-23T01:37:46.618620Z","iopub.execute_input":"2022-12-23T01:37:46.619781Z","iopub.status.idle":"2022-12-23T01:37:46.638443Z","shell.execute_reply.started":"2022-12-23T01:37:46.619735Z","shell.execute_reply":"2022-12-23T01:37:46.637200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Папка test містить набори значень датчиків але вже без відповідного значення часу до виверження","metadata":{}},{"cell_type":"code","source":"print(file_list_test[0])\nprint(pd.read_csv(file_list_test[0]))","metadata":{"execution":{"iopub.status.busy":"2022-12-23T01:37:46.643083Z","iopub.execute_input":"2022-12-23T01:37:46.644188Z","iopub.status.idle":"2022-12-23T01:37:46.784225Z","shell.execute_reply.started":"2022-12-23T01:37:46.644146Z","shell.execute_reply":"2022-12-23T01:37:46.783001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(file_list_test)) \nkeys = list(pd.read_csv(file_list_test[0]).keys()) \nprint(keys)\nnanC = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nfor index in range(len(file_list_test)):\n    if(index % 200 == 0): \n        print(index)\n    df = pd.read_csv(file_list_test[index]) \n    for key in df.keys():\n        if df[key].isna().sum() == len(pd.read_csv(file_list_train[0])):            \n            nanC[keys.index(key)] += 1\n\nprint(nanC)\ndata={'sensors': keys, 'count': nanC}\nNaNDF = pd.DataFrame(data)\nprint(NaNDF)","metadata":{"execution":{"iopub.status.busy":"2022-12-23T01:37:46.785665Z","iopub.execute_input":"2022-12-23T01:37:46.788878Z","iopub.status.idle":"2022-12-23T02:37:44.190293Z","shell.execute_reply.started":"2022-12-23T01:37:46.788827Z","shell.execute_reply":"2022-12-23T02:37:44.188082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NaNDF.plot(figsize =(20, 20), x=\"sensors\", y=\"count\", kind=\"bar\",  rot=5, fontsize=14 )","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:44.193822Z","iopub.execute_input":"2022-12-23T02:37:44.194366Z","iopub.status.idle":"2022-12-23T02:37:44.646495Z","shell.execute_reply.started":"2022-12-23T02:37:44.194321Z","shell.execute_reply":"2022-12-23T02:37:44.645067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Кількість файлів у тестовому наборі","metadata":{}},{"cell_type":"code","source":"NaNDF.plot(figsize =(20, 20), x=\"sensors\", y=\"count\", kind=\"bar\",  rot=5, fontsize=14 )","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:44.648677Z","iopub.execute_input":"2022-12-23T02:37:44.649426Z","iopub.status.idle":"2022-12-23T02:37:45.035147Z","shell.execute_reply.started":"2022-12-23T02:37:44.649384Z","shell.execute_reply":"2022-12-23T02:37:45.033567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Перевірка чи наявні файли з однією назвою в наборах для навчання та тренування","metadata":{}},{"cell_type":"code","source":"files_train = [file.split('/')[-1].split('.')[-2] for file in file_list_train]\nfiles_test = [file.split('/')[-1].split('.')[-2] for file in file_list_test]","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:45.036661Z","iopub.execute_input":"2022-12-23T02:37:45.037027Z","iopub.status.idle":"2022-12-23T02:37:45.053015Z","shell.execute_reply.started":"2022-12-23T02:37:45.036995Z","shell.execute_reply":"2022-12-23T02:37:45.051949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Перші 10 файлів","metadata":{}},{"cell_type":"code","source":"print(files_train[0:10])","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:45.054915Z","iopub.execute_input":"2022-12-23T02:37:45.055383Z","iopub.status.idle":"2022-12-23T02:37:45.072035Z","shell.execute_reply.started":"2022-12-23T02:37:45.055348Z","shell.execute_reply":"2022-12-23T02:37:45.070593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(files_test[0:10])","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:45.074259Z","iopub.execute_input":"2022-12-23T02:37:45.074839Z","iopub.status.idle":"2022-12-23T02:37:45.085656Z","shell.execute_reply.started":"2022-12-23T02:37:45.074802Z","shell.execute_reply":"2022-12-23T02:37:45.084357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Кількість перетинів індексв файлів","metadata":{}},{"cell_type":"code","source":"test_set = set(files_test)\ntrain_set = set(files_train)\ninter = test_set.intersection(train_set)\n\nprint(inter)","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:45.087688Z","iopub.execute_input":"2022-12-23T02:37:45.088169Z","iopub.status.idle":"2022-12-23T02:37:45.099738Z","shell.execute_reply.started":"2022-12-23T02:37:45.088133Z","shell.execute_reply":"2022-12-23T02:37:45.098626Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Для подальшої роботи зчитуємо дані тренування у Data Frame","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv(PATH+'train.csv')","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:45.101557Z","iopub.execute_input":"2022-12-23T02:37:45.101914Z","iopub.status.idle":"2022-12-23T02:37:45.123830Z","shell.execute_reply.started":"2022-12-23T02:37:45.101882Z","shell.execute_reply":"2022-12-23T02:37:45.121939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Діаграмма розподілення часу","metadata":{}},{"cell_type":"code","source":"sns.distplot(train['time_to_eruption'],\n            hist=True,\n            kde=True,\n            bins=100,\n            color='blue',\n            hist_kws={'edgecolor':'black'})","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:45.132088Z","iopub.execute_input":"2022-12-23T02:37:45.133111Z","iopub.status.idle":"2022-12-23T02:37:45.600968Z","shell.execute_reply.started":"2022-12-23T02:37:45.133057Z","shell.execute_reply":"2022-12-23T02:37:45.599952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Описова статистика ознаки часу","metadata":{}},{"cell_type":"code","source":"train['time_to_eruption'].describe()","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:45.602804Z","iopub.execute_input":"2022-12-23T02:37:45.603427Z","iopub.status.idle":"2022-12-23T02:37:45.619744Z","shell.execute_reply.started":"2022-12-23T02:37:45.603390Z","shell.execute_reply":"2022-12-23T02:37:45.618427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Візуалізуємо покази датчиків. Наприклад, вже розглянутого раніше файлу train/800654756.csv","metadata":{}},{"cell_type":"code","source":"df_segment_id = pd.read_csv(PATH+'train/800654756.csv')\n\ndf_segment_id.plot(figsize=(20,20),\n                  subplots=True,\n                  layout=(10,1),\n                  rot=0,\n                  lw=1,\n                  title='sergment_id #800654756')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:45.621426Z","iopub.execute_input":"2022-12-23T02:37:45.621928Z","iopub.status.idle":"2022-12-23T02:37:48.546538Z","shell.execute_reply.started":"2022-12-23T02:37:45.621880Z","shell.execute_reply":"2022-12-23T02:37:48.545586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Візуалізуємо покази, які відповідають мінімальному та максимальному часу.","metadata":{}},{"cell_type":"code","source":"display(train.sort_values('time_to_eruption', axis=0, ascending=True).iloc[[0,-1],:])\n\nsegment_id_min = 601524801\nsegment_id_max = 1923243961\n\ndf_segment_id_min = pd.read_csv(PATH+'train/'+str(segment_id_min)+'.csv')\ndf_segment_id_max = pd.read_csv(PATH+'train/'+str(segment_id_max)+'.csv')","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:48.548247Z","iopub.execute_input":"2022-12-23T02:37:48.548896Z","iopub.status.idle":"2022-12-23T02:37:48.808536Z","shell.execute_reply.started":"2022-12-23T02:37:48.548858Z","shell.execute_reply":"2022-12-23T02:37:48.807552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_segment_id_min.plot(figsize=(20,20), subplots=True, layout=(10,1), rot=0, lw=1, title='segment_id #601524801 (min)')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:48.810302Z","iopub.execute_input":"2022-12-23T02:37:48.811084Z","iopub.status.idle":"2022-12-23T02:37:51.418064Z","shell.execute_reply.started":"2022-12-23T02:37:48.811037Z","shell.execute_reply":"2022-12-23T02:37:51.416795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_segment_id_max.plot(figsize=(20,20), subplots=True, layout=(10,1), rot=0, lw=1, title='segment_id #1923243961 (max)')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:51.419662Z","iopub.execute_input":"2022-12-23T02:37:51.420064Z","iopub.status.idle":"2022-12-23T02:37:54.314824Z","shell.execute_reply.started":"2022-12-23T02:37:51.420023Z","shell.execute_reply":"2022-12-23T02:37:54.313683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Як бачимо покази, що відповідають максимальному часу відрізняються за характеристиками амплітуди та частоти від показів, які відповідають мінімальному часу. Конкретна інтерпретація цих показів неможливо без знань типів датчиків та не входить до нашої задачі.","metadata":{}},{"cell_type":"markdown","source":"Підготовка даних для навчання (Data Preparation)","metadata":{}},{"cell_type":"code","source":"def build_features(signal, ts, sensor_id):\n    X = pd.DataFrame()\n    f = np.fft.fft(signal)\n    f_real = np.real(f)\n    X.loc[ts, f'{sensor_id}_sum'] = signal.sum()\n    X.loc[ts, f'{sensor_id}_mean'] = signal.mean()\n    X.loc[ts, f'{sensor_id}_std'] = signal.std()\n    X.loc[ts, f'{sensor_id}_var'] = signal.var()\n    X.loc[ts, f'{sensor_id}_max'] = signal.max()\n    X.loc[ts, f'{sensor_id}_min'] = signal.min()\n    X.loc[ts, f'{sensor_id}_skew'] = signal.skew()\n    X.loc[ts, f'{sensor_id}_mad'] = signal.mad()\n    X.loc[ts, f'{sensor_id}_kurtosis'] = signal.kurtosis()\n    X.loc[ts, f'{sensor_id}_quantile99'] = np.quantile(signal, 0.99)\n    X.loc[ts, f'{sensor_id}_quantile95'] = np.quantile(signal, 0.95)\n    X.loc[ts, f'{sensor_id}_quantile85'] = np.quantile(signal, 0.85)\n    X.loc[ts, f'{sensor_id}_quantile75'] = np.quantile(signal, 0.75)\n    X.loc[ts, f'{sensor_id}_quantile55'] = np.quantile(signal, 0.55)\n    X.loc[ts, f'{sensor_id}_quantile45'] = np.quantile(signal, 0.45)\n    X.loc[ts, f'{sensor_id}_quantile25'] = np.quantile(signal, 0.25)\n    X.loc[ts, f'{sensor_id}_quantile15'] = np.quantile(signal, 0.15)\n    X.loc[ts, f'{sensor_id}_quantile05'] = np.quantile(signal, 0.05)\n    X.loc[ts, f'{sensor_id}_quantile01'] = np.quantile(signal, 0.01)\n    X.loc[ts, f'{sensor_id}_fft_real_mean'] = f_real.mean()\n    X.loc[ts, f'{sensor_id}_fft_real_std'] = f_real.std()\n    X.loc[ts, f'{sensor_id}_fft_real_max'] = f_real.max()\n    X.loc[ts, f'{sensor_id}_fft_real_min'] = f_real.min()\n    \n    return X","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:54.316460Z","iopub.execute_input":"2022-12-23T02:37:54.316967Z","iopub.status.idle":"2022-12-23T02:37:54.334748Z","shell.execute_reply.started":"2022-12-23T02:37:54.316916Z","shell.execute_reply":"2022-12-23T02:37:54.333566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Формування DataFrame з даними тренування","metadata":{}},{"cell_type":"code","source":"train_set = list()\nseg = 0\n\nfor seg, segment_id in enumerate(train.segment_id):\n    signals = pd.read_csv(PATH+'train/'+str(segment_id)+'.csv')\n    train_row = []\n    \n    if seg%200 == 0:\n        print('Processing segment_id={}'.format(seg))\n        \n    for sensor in range(0, 10):\n        sensor_id = f'sensor_{sensor+1}'\n        train_row.append(build_features(signals[sensor_id].fillna(0), segment_id, sensor_id))\n        \n    train_row = pd.concat(train_row, axis=1)\n    train_set.append(train_row)\n    seg+=1\n    \ntrain_set = pd.concat(train_set)","metadata":{"execution":{"iopub.status.busy":"2022-12-23T02:37:54.336712Z","iopub.execute_input":"2022-12-23T02:37:54.337256Z","iopub.status.idle":"2022-12-23T03:20:47.355221Z","shell.execute_reply.started":"2022-12-23T02:37:54.337198Z","shell.execute_reply":"2022-12-23T03:20:47.354154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_set = train_set.reset_index()\ntrain_set = train_set.rename(columns={'index':  'segment_id'})\n\ntrain_set = pd.merge(train_set, train, on='segment_id')","metadata":{"execution":{"iopub.status.busy":"2022-12-23T03:20:47.357030Z","iopub.execute_input":"2022-12-23T03:20:47.357387Z","iopub.status.idle":"2022-12-23T03:20:47.400777Z","shell.execute_reply.started":"2022-12-23T03:20:47.357354Z","shell.execute_reply":"2022-12-23T03:20:47.399327Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(train_set.head(3))","metadata":{"execution":{"iopub.status.busy":"2022-12-23T03:20:47.402873Z","iopub.execute_input":"2022-12-23T03:20:47.403859Z","iopub.status.idle":"2022-12-23T03:20:47.420227Z","shell.execute_reply.started":"2022-12-23T03:20:47.403807Z","shell.execute_reply":"2022-12-23T03:20:47.419001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Дані для тесту","metadata":{}},{"cell_type":"code","source":"test_files = []\nfor dirname, _, filenames in os.walk(PATH+'test/'):\n    for filename in filenames:\n        test_files.append(filename[:-4])\n        \ntest = pd.DataFrame(test_files, columns=['segment_id'])","metadata":{"execution":{"iopub.status.busy":"2022-12-23T03:20:47.421754Z","iopub.execute_input":"2022-12-23T03:20:47.422199Z","iopub.status.idle":"2022-12-23T03:20:49.958591Z","shell.execute_reply.started":"2022-12-23T03:20:47.422167Z","shell.execute_reply":"2022-12-23T03:20:49.957340Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_set = list()\nseg = 0\n\nfor seg, segment_id in enumerate(test.segment_id):\n    signals = pd.read_csv(PATH+'test/'+str(segment_id)+'.csv')\n    test_row = []\n    \n    if seg%200 == 0:\n        print('Processing segment_id={}'.format(seg))\n        \n    for sensor in range(0, 10):\n        sensor_id = f'sensor_{sensor+1}'\n        test_row.append(build_features(signals[sensor_id].fillna(0), segment_id, sensor_id))\n        \n    test_row = pd.concat(test_row, axis=1)\n    test_set.append(test_row)\n    seg+=1\n    \ntest_set = pd.concat(test_set)","metadata":{"execution":{"iopub.status.busy":"2022-12-23T03:20:49.960700Z","iopub.execute_input":"2022-12-23T03:20:49.961141Z","iopub.status.idle":"2022-12-23T04:03:28.997767Z","shell.execute_reply.started":"2022-12-23T03:20:49.961106Z","shell.execute_reply":"2022-12-23T04:03:28.996568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_set = test_set.reset_index()\ntest_set = test_set.rename(columns={'index':  'segment_id'})\n\ntest_set = pd.merge(test_set, test, on='segment_id')","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:03:29.000190Z","iopub.execute_input":"2022-12-23T04:03:29.001351Z","iopub.status.idle":"2022-12-23T04:03:29.050389Z","shell.execute_reply.started":"2022-12-23T04:03:29.001313Z","shell.execute_reply":"2022-12-23T04:03:29.049027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(test_set.head(3))","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:03:29.052188Z","iopub.execute_input":"2022-12-23T04:03:29.052548Z","iopub.status.idle":"2022-12-23T04:03:29.071788Z","shell.execute_reply.started":"2022-12-23T04:03:29.052514Z","shell.execute_reply":"2022-12-23T04:03:29.070279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Розділення даних тренування на набори для безпосередньо тренування та валідації","metadata":{}},{"cell_type":"code","source":"X = train_set.drop(['segment_id', 'time_to_eruption'], axis=1)\ny = train_set['time_to_eruption']\n\nX_train, X_valid, y_train, y_valid = train_test_split(X, y, \n                                                      test_size=0.2,\n                                                      random_state=42)","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:03:29.074049Z","iopub.execute_input":"2022-12-23T04:03:29.074989Z","iopub.status.idle":"2022-12-23T04:03:29.113181Z","shell.execute_reply.started":"2022-12-23T04:03:29.074940Z","shell.execute_reply":"2022-12-23T04:03:29.112008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Вхідні дані тренування (статистичні характеристики показів датчиків)","metadata":{}},{"cell_type":"code","source":"print(X_train.head(3))\nprint('np.shape(X_train) = ', np.shape(X_train))","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:03:29.115088Z","iopub.execute_input":"2022-12-23T04:03:29.116220Z","iopub.status.idle":"2022-12-23T04:03:29.133909Z","shell.execute_reply.started":"2022-12-23T04:03:29.116160Z","shell.execute_reply":"2022-12-23T04:03:29.132894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Вихідні дані тренування (дані часу)","metadata":{}},{"cell_type":"code","source":"print(y_train.head(3))\nprint('np.shape(y_train) = ', np.shape(y_train))","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:03:29.135625Z","iopub.execute_input":"2022-12-23T04:03:29.136004Z","iopub.status.idle":"2022-12-23T04:03:29.152217Z","shell.execute_reply.started":"2022-12-23T04:03:29.135958Z","shell.execute_reply":"2022-12-23T04:03:29.150865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Побудуємо просту модель регресії методом Випадкових лісів.","metadata":{}},{"cell_type":"code","source":"from sklearn.ensemble import RandomForestRegressor\n\nmodel = RandomForestRegressor(max_depth=20, random_state=0)\nmodel.fit(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:03:29.153869Z","iopub.execute_input":"2022-12-23T04:03:29.154287Z","iopub.status.idle":"2022-12-23T04:04:18.246257Z","shell.execute_reply.started":"2022-12-23T04:03:29.154247Z","shell.execute_reply":"2022-12-23T04:04:18.245003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Оцінка точності моделі (Evaluation)","metadata":{}},{"cell_type":"code","source":"y_pred = model.predict(X_valid)","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:04:18.249643Z","iopub.execute_input":"2022-12-23T04:04:18.249986Z","iopub.status.idle":"2022-12-23T04:04:18.301118Z","shell.execute_reply.started":"2022-12-23T04:04:18.249955Z","shell.execute_reply":"2022-12-23T04:04:18.299926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import mean_squared_error\n\nmse = mean_squared_error(y_valid, y_pred)\nfig = plt.figure()\nmulreg = fig.add_subplot(1, 1, 1)\nmulreg.scatter(y_valid, y_pred, color='r')\nmulreg.set_title('Nonlinear Regression')","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:04:18.302524Z","iopub.execute_input":"2022-12-23T04:04:18.302822Z","iopub.status.idle":"2022-12-23T04:04:18.536436Z","shell.execute_reply.started":"2022-12-23T04:04:18.302796Z","shell.execute_reply":"2022-12-23T04:04:18.535454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Впровадження моделі (Deployment) Прогноз на тестових даних","metadata":{}},{"cell_type":"code","source":"prediction = model.predict(test_set.drop(columns=['segment_id']))","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:04:18.537887Z","iopub.execute_input":"2022-12-23T04:04:18.538240Z","iopub.status.idle":"2022-12-23T04:04:18.676021Z","shell.execute_reply.started":"2022-12-23T04:04:18.538209Z","shell.execute_reply":"2022-12-23T04:04:18.674793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame()  \nsubmission['segment_id'] = test_set['segment_id']\nsubmission['time_to_eruption'] = prediction\nsubmission.to_csv('submission.csv', header=True, index=False)","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:04:18.677701Z","iopub.execute_input":"2022-12-23T04:04:18.678029Z","iopub.status.idle":"2022-12-23T04:04:18.700412Z","shell.execute_reply.started":"2022-12-23T04:04:18.677998Z","shell.execute_reply":"2022-12-23T04:04:18.699627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"keys = list(pd.read_csv(file_list_test[0]).keys()) \nprint(keys)\nnanC = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nfor index in range(len(file_list_test)):\n    df = pd.read_csv(file_list_test[index]) \n    for key in df.keys():\n        if df[key].isna().sum() == len(pd.read_csv(file_list_train[0])):      \n            nanC[keys.index(key)] += 1\n\nprint(nanC)\ndata={'sensors': keys, 'count': nanC}\nNaNDF = pd.DataFrame(data)\nprint(NaNDF)","metadata":{"execution":{"iopub.status.busy":"2022-12-23T04:04:18.701536Z","iopub.execute_input":"2022-12-23T04:04:18.702666Z","iopub.status.idle":"2022-12-23T05:00:30.853972Z","shell.execute_reply.started":"2022-12-23T04:04:18.702631Z","shell.execute_reply":"2022-12-23T05:00:30.851027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NaNDF.plot(figsize =(20, 20), x=\"sensors\", y=\"count\", kind=\"bar\",  rot=5, fontsize=14 )","metadata":{"execution":{"iopub.status.busy":"2022-12-23T05:00:30.860342Z","iopub.execute_input":"2022-12-23T05:00:30.861207Z","iopub.status.idle":"2022-12-23T05:00:31.273680Z","shell.execute_reply.started":"2022-12-23T05:00:30.861153Z","shell.execute_reply":"2022-12-23T05:00:31.272806Z"},"trusted":true},"execution_count":null,"outputs":[]}]}