{"cells":[{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_kg_hide-input":false,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import numpy as np\nimport scipy as sp\nimport pandas as pd\nimport os\n\nimport random\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\npd.options.display.precision = 15\n\nimport gc\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom fastai.tabular import * \nfrom tqdm import tqdm_notebook\nfrom fastai.callbacks import *","execution_count":1,"outputs":[]},{"metadata":{"_uuid":"bc314853a64c3ee3b7b14dd2ad99c06e77e16561","trusted":true,"scrolled":true},"cell_type":"code","source":"%%time\ntrain = pd.read_csv('../input/train.csv', dtype={'acoustic_data': np.int16, 'time_to_failure': np.float32},nrows=6e8)","execution_count":2,"outputs":[{"output_type":"stream","text":"CPU times: user 2min 1s, sys: 10.1 s, total: 2min 11s\nWall time: 2min 12s\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"min = -100\nmax = 100\nspread = 110\ndef get_counts(sequence):     \n    counts = [0]*spread\n    unique_count = np.unique(sequence, return_counts=True)\n    for i in range(0,len(unique_count[0])):\n        val = unique_count[0][i]\n        count = unique_count[1][i]\n        r = count*val\n        if val <= min:\n            counts[0] += r\n        elif val >= max:\n            counts[-1] += r\n        else:\n            counts[int(val/2)+int(spread/2)] += r\n\n    return counts","execution_count":3,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"interval = 75000\ncounts = [get_counts(train.acoustic_data.values[i:i+150000]) for i in tqdm_notebook(range(0,len(train),interval))]\nttfs = [train.time_to_failure.values[i] for i in range(0,len(train),interval)]\ndel train\n\nlabels = [\"D\"+str(i) for i in range(0,len(counts[0]))]\n\ndf = pd.DataFrame(counts, columns=labels)\nttf_df = pd.DataFrame(ttfs, columns=[\"expected\"])\ndf = df.join(ttf_df)","execution_count":4,"outputs":[{"output_type":"display_data","data":{"text/plain":"HBox(children=(IntProgress(value=0, max=8000), HTML(value='')))","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"7dee40d8ce7e4c8c9c05120f7f4ac664"}},"metadata":{}},{"output_type":"stream","text":"\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head(3)","execution_count":5,"outputs":[{"output_type":"execute_result","execution_count":5,"data":{"text/plain":"     D0  D1  D2  D3        ...          D107  D108  D109           expected\n0     0   0   0   0        ...             0     0   206  1.469099998474121\n1 -3169   0   0   0        ...             0     0  5113  1.449998617172241\n2 -3703   0   0   0        ...             0     0  5326  1.430797219276428\n\n[3 rows x 111 columns]","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>D0</th>\n      <th>D1</th>\n      <th>D2</th>\n      <th>D3</th>\n      <th>D4</th>\n      <th>D5</th>\n      <th>D6</th>\n      <th>D7</th>\n      <th>D8</th>\n      <th>D9</th>\n      <th>D10</th>\n      <th>D11</th>\n      <th>D12</th>\n      <th>D13</th>\n      <th>D14</th>\n      <th>D15</th>\n      <th>D16</th>\n      <th>D17</th>\n      <th>D18</th>\n      <th>D19</th>\n      <th>D20</th>\n      <th>D21</th>\n      <th>D22</th>\n      <th>D23</th>\n      <th>D24</th>\n      <th>D25</th>\n      <th>D26</th>\n      <th>D27</th>\n      <th>D28</th>\n      <th>D29</th>\n      <th>D30</th>\n      <th>D31</th>\n      <th>D32</th>\n      <th>D33</th>\n      <th>D34</th>\n      <th>D35</th>\n      <th>D36</th>\n      <th>D37</th>\n      <th>D38</th>\n      <th>D39</th>\n      <th>...</th>\n      <th>D71</th>\n      <th>D72</th>\n      <th>D73</th>\n      <th>D74</th>\n      <th>D75</th>\n      <th>D76</th>\n      <th>D77</th>\n      <th>D78</th>\n      <th>D79</th>\n      <th>D80</th>\n      <th>D81</th>\n      <th>D82</th>\n      <th>D83</th>\n      <th>D84</th>\n      <th>D85</th>\n      <th>D86</th>\n      <th>D87</th>\n      <th>D88</th>\n      <th>D89</th>\n      <th>D90</th>\n      <th>D91</th>\n      <th>D92</th>\n      <th>D93</th>\n      <th>D94</th>\n      <th>D95</th>\n      <th>D96</th>\n      <th>D97</th>\n      <th>D98</th>\n      <th>D99</th>\n      <th>D100</th>\n      <th>D101</th>\n      <th>D102</th>\n      <th>D103</th>\n      <th>D104</th>\n      <th>D105</th>\n      <th>D106</th>\n      <th>D107</th>\n      <th>D108</th>\n      <th>D109</th>\n      <th>expected</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-98</td>\n      <td>0</td>\n      <td>-95</td>\n      <td>-92</td>\n      <td>-91</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-85</td>\n      <td>-82</td>\n      <td>-161</td>\n      <td>-78</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-146</td>\n      <td>0</td>\n      <td>-138</td>\n      <td>-67</td>\n      <td>-194</td>\n      <td>-63</td>\n      <td>-60</td>\n      <td>-233</td>\n      <td>-170</td>\n      <td>-271</td>\n      <td>-527</td>\n      <td>-100</td>\n      <td>-242</td>\n      <td>-373</td>\n      <td>-400</td>\n      <td>-213</td>\n      <td>-443</td>\n      <td>-271</td>\n      <td>-511</td>\n      <td>-553</td>\n      <td>-618</td>\n      <td>...</td>\n      <td>1399</td>\n      <td>1343</td>\n      <td>1059</td>\n      <td>1273</td>\n      <td>688</td>\n      <td>594</td>\n      <td>1021</td>\n      <td>560</td>\n      <td>437</td>\n      <td>455</td>\n      <td>525</td>\n      <td>489</td>\n      <td>396</td>\n      <td>176</td>\n      <td>422</td>\n      <td>252</td>\n      <td>65</td>\n      <td>265</td>\n      <td>137</td>\n      <td>141</td>\n      <td>218</td>\n      <td>75</td>\n      <td>76</td>\n      <td>156</td>\n      <td>80</td>\n      <td>82</td>\n      <td>85</td>\n      <td>344</td>\n      <td>89</td>\n      <td>0</td>\n      <td>93</td>\n      <td>0</td>\n      <td>0</td>\n      <td>98</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>206</td>\n      <td>1.469099998474121</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>-3169</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-296</td>\n      <td>-194</td>\n      <td>-95</td>\n      <td>-93</td>\n      <td>-90</td>\n      <td>0</td>\n      <td>-348</td>\n      <td>-85</td>\n      <td>-411</td>\n      <td>-240</td>\n      <td>-158</td>\n      <td>-230</td>\n      <td>-223</td>\n      <td>-653</td>\n      <td>-425</td>\n      <td>-273</td>\n      <td>-201</td>\n      <td>-64</td>\n      <td>-250</td>\n      <td>-180</td>\n      <td>-235</td>\n      <td>-282</td>\n      <td>-326</td>\n      <td>-578</td>\n      <td>-759</td>\n      <td>-96</td>\n      <td>-93</td>\n      <td>-445</td>\n      <td>-550</td>\n      <td>-812</td>\n      <td>-536</td>\n      <td>-584</td>\n      <td>-725</td>\n      <td>-717</td>\n      <td>...</td>\n      <td>1855</td>\n      <td>1623</td>\n      <td>1604</td>\n      <td>1310</td>\n      <td>1177</td>\n      <td>723</td>\n      <td>666</td>\n      <td>697</td>\n      <td>630</td>\n      <td>407</td>\n      <td>473</td>\n      <td>219</td>\n      <td>621</td>\n      <td>352</td>\n      <td>362</td>\n      <td>375</td>\n      <td>321</td>\n      <td>133</td>\n      <td>274</td>\n      <td>842</td>\n      <td>437</td>\n      <td>672</td>\n      <td>228</td>\n      <td>314</td>\n      <td>481</td>\n      <td>83</td>\n      <td>0</td>\n      <td>87</td>\n      <td>265</td>\n      <td>543</td>\n      <td>371</td>\n      <td>379</td>\n      <td>193</td>\n      <td>98</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5113</td>\n      <td>1.449998617172241</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>-3703</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>-296</td>\n      <td>-291</td>\n      <td>-190</td>\n      <td>-93</td>\n      <td>-90</td>\n      <td>-88</td>\n      <td>-348</td>\n      <td>-85</td>\n      <td>-411</td>\n      <td>-320</td>\n      <td>-158</td>\n      <td>-230</td>\n      <td>-223</td>\n      <td>-653</td>\n      <td>-495</td>\n      <td>-273</td>\n      <td>-201</td>\n      <td>-64</td>\n      <td>-376</td>\n      <td>-180</td>\n      <td>-293</td>\n      <td>-282</td>\n      <td>-326</td>\n      <td>-683</td>\n      <td>-809</td>\n      <td>-290</td>\n      <td>-233</td>\n      <td>-490</td>\n      <td>-719</td>\n      <td>-892</td>\n      <td>-688</td>\n      <td>-619</td>\n      <td>-966</td>\n      <td>-1303</td>\n      <td>...</td>\n      <td>2439</td>\n      <td>2101</td>\n      <td>1859</td>\n      <td>1730</td>\n      <td>1665</td>\n      <td>934</td>\n      <td>1288</td>\n      <td>1116</td>\n      <td>1068</td>\n      <td>356</td>\n      <td>473</td>\n      <td>438</td>\n      <td>792</td>\n      <td>587</td>\n      <td>602</td>\n      <td>375</td>\n      <td>321</td>\n      <td>200</td>\n      <td>479</td>\n      <td>913</td>\n      <td>437</td>\n      <td>672</td>\n      <td>228</td>\n      <td>548</td>\n      <td>481</td>\n      <td>83</td>\n      <td>84</td>\n      <td>87</td>\n      <td>354</td>\n      <td>543</td>\n      <td>371</td>\n      <td>568</td>\n      <td>386</td>\n      <td>196</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>5326</td>\n      <td>1.430797219276428</td>\n    </tr>\n  </tbody>\n</table>\n</div>"},"metadata":{}}]},{"metadata":{"trusted":true,"_uuid":"ae3de367d7834583fa6c6957788dc86d7b77d4d2"},"cell_type":"code","source":"path =\"../tmp\"\ntry:\n    os.makedirs(path)\nexcept:\n    pass","execution_count":6,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Test Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"tpath = \"../input/test\"\nfiles = os.listdir(tpath)\ni = 0\ntest_id = []\ntest_df = pd.DataFrame(dtype=np.float64, columns=df.columns.values[:-1])\nfor f in tqdm_notebook(files):\n    seg = pd.read_csv(f'{tpath}/{f}')\n    converted = get_counts(seg.acoustic_data.values)\n    test_df.loc[i] = converted\n    test_id.append(f.replace(\".csv\", \"\"))\n    i+=1","execution_count":7,"outputs":[{"output_type":"display_data","data":{"text/plain":"HBox(children=(IntProgress(value=0, max=2624), HTML(value='')))","application/vnd.jupyter.widget-view+json":{"version_major":2,"version_minor":0,"model_id":"09597cf7c05a40fda24811d49bcac6f3"}},"metadata":{}},{"output_type":"stream","text":"\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"num = len(df)\ninterval = int(num/100)\nvalues = int(num/(5*100))\nvalid_idx = []\nfor i in range(0,len(df)-values,interval):\n    for j in range(0,values-1):\n        valid_idx.append(i+j)","execution_count":8,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_ttfs = np.array([df.iloc[i].expected for i in valid_idx])","execution_count":9,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = TabularDataBunch.from_df(path, df, \"expected\", valid_idx=valid_idx, test_df=test_df, procs=[Normalize])\n# data = TabularDataBunch.from_df(path, df, \"expected\", valid_idx=valid_idx, procs=[Normalize])","execution_count":10,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"* spread 200 - 2.02\n* spread 300 - "},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\nbest_learn = None\nbest_mae = 9999\n\nfor i in range(0, 99):\n    learn = tabular_learner(data=data, layers=[200,100], metrics=mae, ps=0.5, y_range=(-1,15))\n    learn.callbacks = [SaveModelCallback(learn, every='improvement', mode='min', name='best')]\n    learn.fit_one_cycle(20, 1e-2)\n    gc.collect()\n\n    preds = learn.get_preds(DatasetType.Valid)[0].numpy().flatten()\n    new_mae = np.abs(valid_ttfs-preds).mean()\n    if new_mae < best_mae or not best_learn:\n        best_learn = learn\n        best_mae = new_mae\n    print(f'Run {i} - Best MAE: {best_mae}')","execution_count":11,"outputs":[{"output_type":"stream","text":"Run 19 - Best MAE: 2.0077382553915184\nCPU times: user 5min 6s, sys: 2min 33s, total: 7min 39s\nWall time: 8min 30s\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"# Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = best_learn.get_preds(DatasetType.Test)[0].numpy().flatten()","execution_count":12,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tpath = \"../input/test\"\nfiles = os.listdir(tpath)\nfiles = [f.replace(\".csv\",\"\") for f in files]\nfiles[:3]","execution_count":13,"outputs":[{"output_type":"execute_result","execution_count":13,"data":{"text/plain":"['seg_0b082e', 'seg_9e7dff', 'seg_b6c10d']"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = pd.DataFrame({\"seg_id\":files, \"time_to_failure\":preds})\nresults.head()","execution_count":14,"outputs":[{"output_type":"execute_result","execution_count":14,"data":{"text/plain":"       seg_id    time_to_failure\n0  seg_0b082e  9.671259880065918\n1  seg_9e7dff  3.582855701446533\n2  seg_b6c10d  7.680974960327148\n3  seg_4435bd  4.013928413391113\n4  seg_c09a41  3.563020706176758","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>seg_id</th>\n      <th>time_to_failure</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>seg_0b082e</td>\n      <td>9.671259880065918</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>seg_9e7dff</td>\n      <td>3.582855701446533</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>seg_b6c10d</td>\n      <td>7.680974960327148</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>seg_4435bd</td>\n      <td>4.013928413391113</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>seg_c09a41</td>\n      <td>3.563020706176758</td>\n    </tr>\n  </tbody>\n</table>\n</div>"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"results.to_csv('submission.csv',index=False)","execution_count":15,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}