NOTE: This Use Case is not purposed for resource constrained devices.
We all are aware of the pandemic situation created by the outbreak of novel corona virus and the large of number of deaths it has caused worldwide.So, it is the need of the hour to develop a deep learning model which can help us identify covid patients.
Importing the Dataset¶
The dataset contains the spectogram of cough sounds of normal and covid patients
In [1]:
# This will load the dataset.You will see a folder called ALL in your workspace.
!wget -N "https://cainvas-static.s3.amazonaws.com/media/user_data/cainvas-admin/CovidDetec.zip"
!unzip -qo CovidDetec.zip
!rm CovidDetec.zip
The following code has been used to convert the audio files to spectograms.But you don't have to worry about this step as it has been already done for you.
import librosa
import librosa.display
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from glob import glob
data_dir = 'CovidDetec/Covid'
audio_files = glob(data_dir + '/*.wav')
print(len(audio_files))
samples, sample_rate = librosa.load(audio_files[1],sr=44100)
sample = np.array(samples)
sample = sample.reshape(1,sample.shape[0])
for i in range (2,8):
samples, sample_rate = librosa.load(audio_files[1],sr=44100)
temp = np.array(samples)
temp = temp.reshape(1,temp.shape[0])
sample = np.append(sample, temp, axis=0)
print(type(sample))
print(sample.shape)
for i in range (1,8):
fig = plt.figure(figsize=[4,4])
ax = fig.add_subplot(111)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
S = librosa.feature.melspectrogram(y=sample[1], sr=sample_rate)
#librosa.display.specshow(librosa.power_to_db(S, ref=np.max))
direc = 'CovidDetec/MS/CovidMS/Covid10'+str(i)
plt.savefig(direc)
Importing important libraries¶
In [2]:
# import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
from keras.layers import Dense, Flatten, AveragePooling2D, Dropout
from keras.models import Model
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
Data Visualization¶
In [3]:
data_path = "CovidDetec/MS/"
In [4]:
# Check images
img = cv2.imread("CovidDetec/MS/Train/Covid/Covid10.png")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.title("Covid Cough Spectogram")
plt.imshow(img)
Out[4]:
In [5]:
# Check images
img = cv2.imread("CovidDetec/MS/Train/Normal/Normal11.png")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.title("Normal Cough Spectogram")
plt.imshow(img)
Out[5]:
Creating TrainSet and TestSet¶
In [6]:
# Data agumentation on train and test
train_datagen = ImageDataGenerator(rescale = 1./255,
zoom_range = 0.2,
rotation_range=15,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
In [7]:
# create dataset train
training_set = train_datagen.flow_from_directory(data_path + 'Train',
target_size = (224, 224),
batch_size = 16,
class_mode = 'categorical',
shuffle=True)
In [8]:
# Create test data set
test_set = test_datagen.flow_from_directory(data_path + 'Test',
target_size = (224, 224),
batch_size = 16,
class_mode = 'categorical',
shuffle = False)
Model Architecture¶
In [9]:
# Model creation with changes
model = VGG16(input_shape=(224,224,3),include_top=False)
for layer in model.layers:
layer.trainable = False
newModel = model.output
newModel = AveragePooling2D()(newModel)
newModel = Flatten()(newModel)
newModel = Dense(128, activation="relu")(newModel)
newModel = Dropout(0.5)(newModel)
newModel = Dense(2, activation='softmax')(newModel)
model = Model(inputs=model.input, outputs=newModel)
model.summary()
Model Training¶
In [10]:
opt=Adam(learning_rate=0.0001)
model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])
In [11]:
history = model.fit(training_set,
validation_data=test_set,
epochs=8)
Accessing the performance of the model¶
In [12]:
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs=range(len(acc))
plt.plot(epochs,acc,label='Trainin_acc',color='blue')
plt.plot(epochs,val_acc,label='Validation_acc',color='red')
plt.legend()
plt.title("Training and Validation Accuracy")
Out[12]:
In [13]:
plt.plot(epochs,loss,label='Training_loss',color='blue')
plt.plot(epochs,val_loss,label='Validation_loss',color='red')
plt.legend()
plt.title("Training and Validation loss")
Out[13]:
In [14]:
print("Accuracy of our model on test data : " , model.evaluate(test_set)[1]*100 , "%")
Saving the model¶
In [15]:
model.save("CovidTest.h5")
Compiling the DeepC Compiler¶
In [ ]:
!deepCC CovidTest.h5