Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pandas as pd
- import numpy as np
- import h5py
- import matplotlib
- #matplotlib.use('agg')
- import matplotlib.pyplot as plt
- from keras.models import Model, Sequential
- from keras.layers import Dense, Input, concatenate,Conv1D, Conv2D, MaxPooling2D, Conv2DTranspose,MaxPooling1D, Cropping2D, Multiply, subtract, Flatten, Reshape, Permute, LSTM, TimeDistributed,Dropout,BatchNormalization,UpSampling1D
- from keras.optimizers import SGD
- from keras.callbacks import ModelCheckpoint,EarlyStopping
- import tensorflow as tf
- from keras.models import load_model
- from keras import optimizers
- from keras import regularizers
- from math import sqrt
- from sklearn.metrics import mean_squared_error
- from sklearn.metrics import mean_absolute_error
- import pickle
- from sklearn.preprocessing import StandardScaler
- import time
- from sklearn import preprocessing
- from numpy import argmax
- from keras.utils import to_categorical
- from tabulate import tabulate
- from numpy import array
- from imblearn.over_sampling import SMOTE
- from imblearn.combine import SMOTEENN
- from collections import Counter
- #import the data
- #path="D:\\NCSU Research\\GEARS_Jul9\GEARS\\540\\x_train_540_final.pkl"
- #data=np.load(path, allow_pickle=True) #1. path中\改为\\; 2. 加allow_pinckle=True
- file_540=open("D:\\NCSU Research\\GEARS_Jul9\GEARS\\540\\x_train_540_final.pkl","rb")
- data = pickle.load(file_540)
- #print(data.isnull().any()) all false
- #print(data)
- #print(type(data))=<class 'pandas.core.frame.DataFrame'>
- #same as using pd.load
- #prepare data: (Emaily)prepare_data*: load in data with selected features, forward filling the missing value, and prepare the train, valid, test series for model usage
- #feature selection(why: can check it later)
- #pick_index=['glucose level','fingerstick','basis_gsr','basis_skintem','acceleration','basal','bolus','meal']
- #make the data balenced
- #add label to data
- data["label"]=pd.cut(data["glucose level"], bins=[0,70,130,10000], labels=[-1,0,1])
- #print(data)
- #do balance by the label
- #from imblearn.over_sampling import BorderlineSMOT
- #切片:分开特征x和目标y
- #X,y=data.["time" "fingerstick" "basis_gsr" "basis_skintem" "acceleration" "bolus" "basal" "meal" "basis_sleep"]
- #ros=BorderlineSMOTE(sampling_strategy={-1:3000,0:6000,1:})
- #First I hope to use the pakage directly for resampleing
- #However, I realize that there's a time series, which makes the order of data also important
- #Therefore, I attempt to first rearange the data to run away from time series
- #Or there's another way to deal with the imbalanced data which is to modify the loss function
- #rearrange the data
- #to delet the first, second, third...and combine them together
- data_without=data.drop(labels=["time","glucose level"],axis=1,inplace=False)
- data_0=data_without
- data_0=data_0.reset_index(drop=True)
- data_1=data_without.drop(data.index[0])
- data_1.columns=["fingerstick_1", "basis_gsr_1", "basis_skintem_1", "acceleration_1", "bolus_1", "basal_1", "meal_1", "basis_sleep_1", "label_1"]
- data_1=data_1.reset_index(drop=True) #after reseting will give a new dataframe
- #print(data_1)
- data_2=data_1.drop(data_1.index[0])
- data_2.columns=["fingerstick_2", "basis_gsr_2", "basis_skintem_2", "acceleration_2", "bolus_2", "basal_2", "meal_2", "basis_sleep_2", "label_2"]
- data_2=data_2.reset_index(drop=True)
- data_3=data_2.drop(data_2.index[0])
- data_3.columns=["fingerstick_3", "basis_gsr_3", "basis_skintem_3", "acceleration_3", "bolus_3", "basal_3", "meal_3", "basis_sleep_3", "label_3"]
- data_3=data_3.reset_index(drop=True)
- data_4=data_3.drop(data_3.index[0])
- data_4.columns=["fingerstick_4", "basis_gsr_4", "basis_skintem_4", "acceleration_4", "bolus_4", "basal_4", "meal_4", "basis_sleep_4", "label_4"]
- data_4=data_4.reset_index(drop=True)
- data_5=data_4.drop(data_4.index[0])
- data_5.columns=["fingerstick_5", "basis_gsr_5", "basis_skintem_5", "acceleration_5", "bolus_5", "basal_5", "meal_5", "basis_sleep_5", "label_5"]
- data_5=data_5.reset_index(drop=True)
- data_6=data_5.drop(data_5.index[0])#though index is always 0, the output for data_6 is began at 6
- data_6.columns=["fingerstick_6", "basis_gsr_6", "basis_skintem_6", "acceleration_6", "bolus_6", "basal_6", "meal_6", "basis_sleep_6", "label_6"]
- data_6=data_6.reset_index(drop=True)
- data_new=pd.concat([data_0,data_1,data_2,data_3,data_4,data_5,data_6],axis=1)
- #print(data_new.dropna())
- data_new=data_new.dropna()#cut the line that include "NAN"
- #print(data_6)
- #print(data_new)
- #print(data["label"])
- new_label=data_6["label_6"]
- new_label=new_label.tolist()
- #print(len(new_label))
- #print(type(new_label))
- label_new=new_label[7:]
- #change the lbael list into dataframe and combine with the data_new
- from pandas.core.frame import DataFrame
- n={"label_new": label_new}
- data_label=DataFrame(n)
- data_complete=pd.concat([data_new,data_label],axis=1)
- data_complete=data_complete.dropna()#cut the line that include "NAN"
- #balanced the data
- x_columns = [x for x in data_complete.columns if x not in ["label_new"]]
- X=data_complete[x_columns]
- y=data_complete["label_new"]
- smote_enn = SMOTEENN(random_state=0)
- #why do following redundant thing because SMOTEENN create NaN if I don't do this
- X.to_csv("D:\\NCSU Research\\GEARS_Jul9\\GEARS\\540\\avoid_NaN.csv")
- filename="D:\\NCSU Research\\GEARS_Jul9\\GEARS\\540\\avoid_NaN.csv"
- X_read=pd.read_csv(filename)
- X_df=pd.DataFrame(X_read)
- X_resampled, y_resampled =smote_enn.fit_resample(X_df,y)
- #print(sorted(Counter(y_resampled).items())) #[(-1.0, 5659), (0.0, 3117), (1.0, 3380)]
- #check whether the NaN exist again
- #nan_list = X_resampled.isnull().sum().tolist()#把每一列的空值个数加起来
- #print(nan_list)
- #print(sum(nan_list))
- #print(X_resampled) #a column with old order exist
- X_resampled.drop(labels=["Unnamed: 0"],axis=1,inplace=True)
- #print(type(X_resampled)) #dataframe
- #standadization
- X_scaled=X_resampled.apply(lambda x: (x-np.min(x))/(np.max(x)-np.min(x)))
- #can't standadize the label
- #Try 2
- #X_scale=preprocessing.scale(X_resampled)
- #print(X_scale)
- #X_scaled=pd.DataFrame(X_scale,columns=x_columns)
- #Try3
- #colu = [x for x in X_resampled.columns if x not in ["label_new","label","label_1","label_2","label_3","label_4","labe_5","label_6"]]
- #print(colu)
- #max_min_scaler=lambda x: (x-np.min(x))/(np.max(x)-np.min(x))
- #for i in colu:
- # X_resampled[i] = X_resampled[[i]].apply(max_min_scaler)
- #print(X_resampled.mean())
- data_f=pd.concat([X_scaled,y_resampled],axis=1)
- #print(data_f)
- data_f.to_csv("D:\\NCSU Research\\GEARS_Jul9\\GEARS\\540\\data.complete.csv",index=0)
- #PermissionError: [Errno 13] Permission denied: 'D:\\NCSU Research\\GEARS_Jul9\\GEARS\\540\\data.complete.csv'
- #when building RF, mistake like this: Input contains NaN, infinity or a value too large for dtype('float32')
- #nan_list = data_f.isnull().sum().tolist()#把每一列的空值个数加起来
- #print(nan_list)
- #print(sum(nan_list))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement