{"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 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\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nSTEPSIZE=150000\n#print(os.listdir(\"../input\"))\n# due to huge volume of data, only select 33%\nacoustic=pd.read_csv(\"../input/train.csv\",nrows =210000000)\n# select partial of the data to plot\nfilter1=range(0,len(acoustic),100)\nplt.plot(acoustic.iloc[filter1,0])\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":false},"cell_type":"markdown","source":"As we can see from this image, most of acoustic value is betwen (-100,100), while maximun is over 3000 or below -3000. No matter analysis by human being or machine code, we tend to focus on the extreme value, and overlook data which vary in a smaller range. This will impact final performance significantly. The longer 'time_to_failure', the bigger impact it will have, because at every cycle beginning, the acoustic value is in a small range.\n"},{"metadata":{"_uuid":"0e055697849146700d86b7a1410e214cf743a3c1"},"cell_type":"markdown","source":"By applying function log (np.log10), it help us to evenly analysis acoustice in every stage. Below is the python code to smoothen acoustic data"},{"metadata":{"trusted":true,"_uuid":"04fdb97d7ee19cf12a11ae7acc71004ae5881a80"},"cell_type":"code","source":"def logX(data):\n    # Handle positive value\n    positive = np.where(data.iloc[:,0]>0,data.iloc[:,0],0)+1\n    logp=np.log10(positive)\n    # Handle negative value, convert to ABS\n    absneg = np.where(data.iloc[:,0]<0,data.iloc[:,0]*-1,0)+1\n    logn=np.log10(absneg)*-1\n    logall = logn+logp\n    data.iloc[:,0]=logall\n    return data\nacoustic=logX(acoustic)\nplt.plot(acoustic.iloc[filter1,0])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2c806f5a6045eb2b980584f9c7efcbdeb5575555"},"cell_type":"markdown","source":"From above result we can see the value fluctuating much less.\n\n\nRemaining code continue to build a sklearn MLPRegressor model and validate the result.\nThe function dataReFeaturing() is referenced from [Earthquakes FE. More features and samples](http://www.kaggle.com/artgor/earthquakes-fe-more-features-and-samples) by Andrew Lukyanenko"},{"metadata":{"trusted":true,"_uuid":"ebd1e7e28b7ec3f003cf91d5e7d09ced6d831db5"},"cell_type":"code","source":"def dataReFeaturing(dataSource,shiftStep=STEPSIZE,includeY=True):\n    # shiftStep will enable overlap of test data.\n    # when dataSource is test data, includeY will be False\n    \n    rows = STEPSIZE\n    segments = int(np.ceil(dataSource.shape[0] / shiftStep))\n    \n    X_tr = pd.DataFrame(index=range(segments), dtype=np.float64,\n                           columns=['ave', 'std', 'max', 'min',\n                                   'av_change_abs', 'av_change_rate', 'abs_max', 'abs_min',\n                                   'std_first_50000', 'std_last_50000', 'std_first_10000', 'std_last_10000',\n                                   'avg_first_50000', 'avg_last_50000', 'avg_first_10000', 'avg_last_10000',\n                                   'min_first_50000', 'min_last_50000', 'min_first_10000', 'min_last_10000',\n                                   'max_first_50000', 'max_last_50000', 'max_first_10000', 'max_last_10000'])\n    y_tr = pd.DataFrame(index=range(segments), dtype=np.float64,\n                           columns=['time_to_failure'])\n    \n    for segment in range(segments):\n        if (segment*rows+rows > len(dataSource)):\n            segTo=len(dataSource)\n            segFrom=segTo-rows\n        else:\n            segFrom=segment*rows\n            segTo=segment*rows+rows\n        \n        seg = dataSource.iloc[segFrom:segTo]\n        x = seg['acoustic_data'].values\n        if(includeY):\n            y = seg['time_to_failure'].values[-1]\n            y_tr.loc[segment, 'time_to_failure'] = y\n        else:\n            y_tr.loc[segment, 'time_to_failure'] = 0  # for test data\n        X_tr.loc[segment, 'ave'] = x.mean()\n        X_tr.loc[segment, 'std'] = x.std()\n        X_tr.loc[segment, 'max'] = x.max()\n        X_tr.loc[segment, 'min'] = x.min()\n        \n        \n        X_tr.loc[segment, 'av_change_abs'] = np.mean(np.diff(x))\n        X_tr.loc[segment, 'av_change_rate'] = np.mean(np.nonzero((np.diff(x) / x[:-1]))[0])\n        X_tr.loc[segment, 'abs_max'] = np.abs(x).max()\n        X_tr.loc[segment, 'abs_min'] = np.abs(x).min()\n        \n        X_tr.loc[segment, 'std_first_50000'] = x[:50000].std()\n        X_tr.loc[segment, 'std_last_50000'] = x[-50000:].std()\n        X_tr.loc[segment, 'std_first_10000'] = x[:10000].std()\n        X_tr.loc[segment, 'std_last_10000'] = x[-10000:].std()\n        \n        X_tr.loc[segment, 'avg_first_50000'] = x[:50000].mean()\n        X_tr.loc[segment, 'avg_last_50000'] = x[-50000:].mean()\n        X_tr.loc[segment, 'avg_first_10000'] = x[:10000].mean()\n        X_tr.loc[segment, 'avg_last_10000'] = x[-10000:].mean()\n        \n        X_tr.loc[segment, 'min_first_50000'] = x[:50000].min()\n        X_tr.loc[segment, 'min_last_50000'] = x[-50000:].min()\n        X_tr.loc[segment, 'min_first_10000'] = x[:10000].min()\n        X_tr.loc[segment, 'min_last_10000'] = x[-10000:].min()\n        \n        X_tr.loc[segment, 'max_first_50000'] = x[:50000].max()\n        X_tr.loc[segment, 'max_last_50000'] = x[-50000:].max()\n        X_tr.loc[segment, 'max_first_10000'] = x[:10000].max()\n        X_tr.loc[segment, 'max_last_10000'] = x[-10000:].max()\n    \n    return pd.concat([X_tr, y_tr], axis=1, sort=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b582c048f7db78432aa0a8a921b846dc5c8321dd"},"cell_type":"code","source":"from sklearn.preprocessing import MinMaxScaler\nTRAINRATIO=0.7\ntrainSet1=acoustic.iloc[0:int(len(acoustic)*TRAINRATIO),:]\nvalSet1=acoustic.iloc[int(len(acoustic)*TRAINRATIO):-1,:]\ntrainSet2=dataReFeaturing(trainSet1,int(STEPSIZE/3))\nscaler = MinMaxScaler()\ntrainSetNorm=scaler.fit_transform(trainSet2)\nnp.random.shuffle(trainSetNorm)\n\n# build MLPRegressor model\nfrom sklearn.neural_network import MLPRegressor\nx_train=trainSetNorm[:,0:-1]\ny_train=trainSetNorm[:,-1]\nmodel = MLPRegressor(solver='lbfgs', \n                    alpha=0.0001,\n                    hidden_layer_sizes=(800,400,200), \n                    random_state=1,\n                    activation='relu',\n                    verbose=False)\nmodel.fit(x_train, y_train)\n\n# validate model\nvalSet2=dataReFeaturing(valSet1,STEPSIZE)\nvalSetNorm=scaler.transform(valSet2)\nx_val=valSetNorm[:,0:-1]\ny_val=valSetNorm[:,-1]\ny_pred_val=model.predict(x_val)\n#------------------------------------------------------\n# plotting result\n#------------------------------------------------------\nplt.plot(y_val, \"b.\")\nplt.plot(y_pred_val,\"r-\")\nplt.xlabel(\"Time\")\nplt.ylabel(\"Value\")","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"39cb9d471dc6972cb9b698788080632d2eb51293"},"cell_type":"markdown","source":"Above is model validate result\nBy comparison, if not call function logX(), the result will be much worse"},{"metadata":{"_uuid":"be7d995e218acc3e6f28c6f31bfe8309e3bc128c","trusted":true},"cell_type":"code","source":"acoustic=pd.read_csv(\"../input/train.csv\",nrows =210000000)\ntrainSet1=acoustic.iloc[0:int(len(acoustic)*TRAINRATIO),:]\nvalSet1=acoustic.iloc[int(len(acoustic)*TRAINRATIO):-1,:]\ntrainSet2=dataReFeaturing(trainSet1,int(STEPSIZE/3))\nscaler = MinMaxScaler()\ntrainSetNorm=scaler.fit_transform(trainSet2)\nnp.random.shuffle(trainSetNorm)\n\n# build MLPRegressor model\nfrom sklearn.neural_network import MLPRegressor\nx_train=trainSetNorm[:,0:-1]\ny_train=trainSetNorm[:,-1]\nmodel = MLPRegressor(solver='lbfgs', \n                    alpha=0.0001,\n                    hidden_layer_sizes=(800,400,200), \n                    random_state=1,\n                    activation='relu',\n                    verbose=False)\nmodel.fit(x_train, y_train)\n\n# validate model\nvalSet2=dataReFeaturing(valSet1,STEPSIZE)\nvalSetNorm=scaler.transform(valSet2)\nx_val=valSetNorm[:,0:-1]\ny_val=valSetNorm[:,-1]\ny_pred_val=model.predict(x_val)\n#------------------------------------------------------\n# plotting result\n#------------------------------------------------------\nplt.plot(y_val, \"b.\")\nplt.plot(y_pred_val,\"r-\")\nplt.xlabel(\"Time\")\nplt.ylabel(\"Value\")","execution_count":null,"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}