<jupyter_start><jupyter_text>**CNN Model For Early Detection of Sepsis** **Mounting Drive to the Content Folder**<jupyter_code>from google.colab import drive
drive.mount('/content/drive')<jupyter_output>Mounted at /content/drive<jupyter_text>**Import Required Libraries**<jupyter_code>#Importing Libraries
import numpy as np
import pandas as pd<jupyter_output><empty_output><jupyter_text>**Load the dataset "Patient.csv" from drive**<jupyter_code>dataset=pd.read_csv('/content/drive/My Drive/EPS DATA/patient.csv')<jupyter_output><empty_output><jupyter_text>The dataset consists of clinical data of 40336 patients.For each patient hourly clinical data is given.The dataset is made each and patient Clinical data separated by Patient IDIt consists of 42 ColoumnsWe need to predict whther the patient is diagnosed with sepsis i.e 'Sepsis Label'Sepsis Label is given as 0 for not diagnosed with 1.   0 for not diagnosed with Sepsis2.   1 for diagnosed with Sepsis<jupyter_code>#View The dataset
dataset.head(5)
dataset.shape
dataset.size<jupyter_output><empty_output><jupyter_text>**Preparing Patient wise data**<jupyter_code>#Separating Patient ID,Sepsis Label form all the data 
features=dataset.drop(['SepsisLabel','Patient_Id'],axis=1)
features.head(5)
features.shape
features.size
#Finding the percentage of missing data from each Column
missing=features.isnull().sum()*100/1552210
missing
cols=list(missing[missing<90].index)
#Dropping all the columns from features data which are 90% missing
features=dataset[cols]
features.head(5)
features.shape
features.size
#Dropping HospAdmTime and ICULOS
features=features.drop(['HospAdmTime','ICULOS'],axis=1)
#Filling the data with mean
features=features.fillna(features.mean())
features.head(5)
#Converting the DataFrame to array
featurearr=features.iloc[:,:].values
label=dataset[['SepsisLabel',"Patient_Id"]]
label.shape
featurearr.shape
yarr=label.iloc[:].values
patientid=dataset['Patient_Id'].values.tolist()
#Appending Hourly data of each patient to single row
c=0
ip=[]
yp=[]
seq=[]
index=0
for i in range(len(patientid)):
  if i==0:
    seq+=featurearr[index].tolist()
    index+=1
    continue
  if patientid[i]!=patientid[i-1]:
    ip.append(seq)
    yp+=[yarr[i-1,0]]
    seq=[]
  if yarr[i,0]==0:
    seq+=featurearr[index].tolist()
  elif yarr[i,0]==1 and patientid[i-1]!=patientid[i]:
    seq+=featurearr[index].tolist()
  index+=1
ip.append(seq)
yp+=[yarr[i-1,0]]
m=0
for i in yp:
    if i==1:
        m+=1
print('Number of Patients Diagnosed With Sepsis is ',m)
max=0
for i in ip:
    if max<len(i):
        max=len(i)
print('Max length of row',max) #No Of Hours for each patient are not same
#Feature Data
x=np.array(ip)
#Labels
y=np.array(yp)
#Making the data Categorical data
from keras.utils.np_utils import to_categorical
y=to_categorical(y)
from keras.preprocessing import sequence
#No Of Hours for each patient are not same.So we pad zeros in the beginning
x = sequence.pad_sequences(x, maxlen=4032)
x.shape<jupyter_output><empty_output><jupyter_text>**Splitting Data Using for training and testing**<jupyter_code>#Spliiting data set in ratio 6:4 for training and testing
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.4,random_state=0)
print('Training Set:')
print('Features',x_train.shape,'\nLabel',y_train.shape)
print('Testing Set:')
print('Features',x_test.shape,'\nLabel',y_test.shape)<jupyter_output>Training Set:
Features (24201, 4032) 
Label (24201, 2)
Testing Set:
Features (16135, 4032) 
Label (16135, 2)<jupyter_text>**Preparing the model**<jupyter_code>from keras.models import Sequential
from keras.layers import Dense, Conv1D, MaxPooling1D, Flatten
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
embedding_vecor_length = 32
model1 = Sequential()
model1.add(Embedding(1000, embedding_vecor_length, input_length=4032))
model1.add(Conv1D(filters=64, kernel_size=3, padding='same', activation='relu'))
model1.add(MaxPooling1D(pool_size=2))
model1.add(Conv1D(filters=64, kernel_size=3, padding='same', activation='relu'))
model1.add(MaxPooling1D(pool_size=2))
model1.add(Conv1D(filters=64, kernel_size=3, padding='same', activation='relu'))
model1.add(MaxPooling1D(pool_size=2))
model1.add(Flatten())
model1.add(Dense(128, activation='relu'))
model1.add(Dense(2, activation='softmax'))
model1.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model1.summary())<jupyter_output>Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
embedding (Embedding)        (None, 4032, 32)          32000     
_________________________________________________________________
conv1d (Conv1D)              (None, 4032, 64)          6208      
_________________________________________________________________
max_pooling1d (MaxPooling1D) (None, 2016, 64)          0         
_________________________________________________________________
conv1d_1 (Conv1D)            (None, 2016, 64)          12352     
_________________________________________________________________
max_pooling1d_1 (MaxPooling1 (None, 1008, 64)          0         
_________________________________________________________________
conv1d_2 (Conv1D)            (None, 1008, 64)          12352     
________________________________________________________[...]<jupyter_text>**Training the model with train data**<jupyter_code>#training the model
model1.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=10, batch_size=128)<jupyter_output>Epoch 1/10
190/190 [==============================] - 341s 2s/step - loss: 0.2138 - accuracy: 0.9212 - val_loss: 0.1360 - val_accuracy: 0.9641
Epoch 2/10
190/190 [==============================] - 338s 2s/step - loss: 0.1319 - accuracy: 0.9650 - val_loss: 0.1322 - val_accuracy: 0.9639
Epoch 3/10
190/190 [==============================] - 337s 2s/step - loss: 0.1346 - accuracy: 0.9628 - val_loss: 0.1492 - val_accuracy: 0.9634
Epoch 4/10
190/190 [==============================] - 337s 2s/step - loss: 0.1256 - accuracy: 0.9636 - val_loss: 0.1782 - val_accuracy: 0.9505
Epoch 5/10
190/190 [==============================] - 338s 2s/step - loss: 0.1199 - accuracy: 0.9656 - val_loss: 0.1364 - val_accuracy: 0.9642
Epoch 6/10
190/190 [==============================] - 338s 2s/step - loss: 0.1065 - accuracy: 0.9682 - val_loss: 0.1440 - val_accuracy: 0.9642
Epoch 7/10
190/190 [==============================] - 339s 2s/step - loss: 0.0981 - accuracy: 0.9701 - val_loss: 0.1508 - val_accuracy: 0.9623[...]<jupyter_text>**Predict the test data using trained model**<jupyter_code>y_pred=model1.predict(x_test)
y_pred
y_pred.shape
y_pred1=np.round(y_pred)
ypred=[]
for i in y_pred1:
  if i[0]==0:
    ypred.append(1)
  else:
    ypred.append(0)
ytest=[]
for i in y_test:
  if i[0]==0:
    ytest.append(1)
  else:
    ytest.append(0)<jupyter_output><empty_output><jupyter_text>**Accuracy Score**<jupyter_code>from sklearn.metrics import accuracy_score
accuracy_score(ytest,ypred)<jupyter_output><empty_output><jupyter_text>**Confusion Matrix**<jupyter_code>from sklearn.metrics import confusion_matrix
cm=confusion_matrix(ytest,ypred)
cm<jupyter_output><empty_output><jupyter_text>**HeatMap**<jupyter_code>import seaborn as sns
sns.heatmap(cm,annot=True)<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup