Chapter No Title Page No: 1.1 Project Overview 1.2 Objective 1.3 Importance of The Project
Chapter No Title Page No: 1.1 Project Overview 1.2 Objective 1.3 Importance of The Project
ABSTRACT VII
01
1 INTRODUCTION
1.2 OBJECTIVE
2 LITERATURE REVIEW 05
3 SYSTEM ANALYSIS 07
3.2 DRAWBACKS
3.4 ADVANTAGES
4 SYSTEM IMPLEMENTATION 19
IV
4.2.1 USER QUERY ANALYSIS
7 CONCLUSION 25
8 REFERENCES 27
9 APPENDIX 28
V
ABSTRACT
A deep learning approach for health analysis leverages algorithms like CNN, logistic regression, random forest etc. to
extract valuable insights from medical data. By employing deep neural networks, this methodology can effectively
analyze complex medical datasets, including patient records, imaging scans, and more. Through sophisticated pattern
recognition and feature extraction, deep learning models can detect and predict outcomes, and even assist in diagnosis
and treatment planning. This technology holds immense potential for revolutionizing healthcare by enabling
personalized medicine, early disease detection, and optimized treatment strategies. Overall, deep learning in health
analysis offers a powerful toolset for healthcare professionals, researchers, and policymakers to improve patient care,
advance medical research, and enhance public health initiatives
VI
CHAPTER 1
INTRODUCTION
In recent years, deep learning has emerged as a transformative force in various fields, including healthcare. Its
ability to analyze complex datasets and extract meaningful insights has opened up new avenues for revolutionizing
traditional healthcare practices. Deep learning methods, built upon deep neural networks, offer powerful tools for
processing and understanding vast amounts of medical data, ranging from electronic health records to genomic
sequences and medical imaging scans. By harnessing the computational power of deep learning, healthcare
professionals can uncover hidden patterns, predict patient outcomes, and personalize treatment strategies with
unprecedented accuracy. This project explores the application of deep learning in health analysis, highlighting its
potential to enhance diagnostic accuracy, optimize treatment planning, and improve overall patient care. Through a
deeper understanding of the capabilities and limitations of deep learning in healthcare, we can pave the way for
innovative solutions to address complex medical challenges and ultimately improve public health outcomes..
1.1PROJECT OVERVIEW
The scope of a health analysis project using deep learning encompasses multiple stages, beginning with
defining the project's objectives, such as disease prediction or medical imaging analysis. Data collection is
crucial, involving the identification and preprocessing of relevant datasets while ensuring compliance with
healthcare regulations like HIPAA for data privacy. Model development follows, where appropriate deep
learning architectures are selected, features are engineered, and models are trained, validated, and optimized
using the prepared data. Evaluation metrics like accuracy, precision, and recall are employed to assess model
performance, with clinical validation involving healthcare professionals to confirm the models' clinical
relevance. Upon successful validation, the trained models are deployed into production environments,
integrated with existing healthcare systems, 2 and monitored for performance and maintenance. Ethical
considerations, including addressing biases, ensuring transparency, and adhering to regulatory compliance,
are integral throughout the project. The project aims to leverage deep learning's potential to advance
healthcare, providing valuable insights, enhancing diagnostic accuracy, and ultimately improving patient
care outcomes.
1
1.2 OBJECTIVE
The healthcare industry faces numerous challenges, including accurate disease prediction, timely diagnosis,
and effective treatment planning. Traditional methods often rely on manual interpretation of medical data,
which can be time-consuming, subjective, and prone to human error. Additionally, the increasing volume
and complexity of healthcare data present significant obstacles to extracting actionable insights using
conventional approaches. The problem in this project aims to address the development and implementation
of advanced deep learning models to enhance health analysis capabilities. Specifically, the project focuses
on: Disease Prediction: Utilizing deep learning algorithms to predict the onset, progression, or recurrence of
various diseases based on patient data, including medical records, genetic information, and lifestyle factors.
Medical Imaging Analysis: Leveraging deep learning techniques to analyze medical imaging data, such as X-
rays, MRI scans, and CT scans, for accurate and early detection of abnormalities, tumors, or other
pathological conditions. By addressing these key areas, the project seeks to improve diagnostic accuracy,
optimize treatment strategies, and ultimately enhance patient outcomes in the healthcare domain. The
integration of advanced deep learning technologies has the potential to revolutionize healthcare practices,
providing clinicians with powerful tools to make informed decisions, prioritize resources effectively, and
deliver personalized patient care.
2
CHAPTER 2
LITERATURE REVIEW
1. Rajkomar, A., Dean, J., & Kohane, I. (2018). Machine Learning in Medicine. The New England
Journal of Medicine. This seminal paper highlights the potential of machine learning, including
deep learning, in predicting disease onset and progression using electronic health records (EHRs)
and genomic data. 2. Miotto, R., Wang, F., Wang, S., Jiang, X., & Dudley, J. T. (2017). Deep
learning for healthcare: review, opportunities, and challenges. Briefings in Bioinformatics. This
review article provides an overview of deep learning applications in healthcare, emphasizing its
role in disease prediction, risk stratification, and patient management. 3. Shen, D., Wu, G., & Suk,
H. I. (2017). Deep Learning in Medical Image Analysis. Annual Review of Biomedical
Engineering. This comprehensive review discusses the advancements and challenges of using deep
learning techniques, particularly convolutional neural networks (CNNs), in medical image analysis
for tasks like tumor detection, organ segmentation, and disease classification. 4. Litjens, G., Kooi,
T., Bejnordi, B. E., et al. (2017). A survey on deep learning in medical image analysis. Medical
Image Analysis. This survey paper provides an in-depth analysis of various deep learning
architectures and their applications in analyzing different types of medical images, highlighting the
performance improvements achieved compared to traditional methods. 5. Price, W. N., & Cohen,
I. G. (2019). Privacy in the Age of Medical Big Data. Nature Medicine. This paper addresses the
ethical and privacy concerns associated with the use of largescale medical datasets in deep learning
models, emphasizing the importance of data anonymization, consent, and regulatory compliance.
4 6. Zhang, X., Zhang, L., & Cheng, L. (2020). Bias in Artificial Intelligence: A Review. Journal
of Biomedical Informatics. This review article discusses the potential biases in AI algorithms,
including deep learning models, and their implications in healthcare, highlighting the importance
of fairness, transparency, and interpretability in model development and deployment
3
CHAPTER 3
SYSTEM ANALYSIS
3.1 EXISTING SYSTEM:
Before the advent of deep learning in health analysis, traditional healthcare systems relied heavily on manual
interpretation of medical data by clinicians and researchers. This process often involved laborious and time-consuming
tasks, such as manually reviewing patient records, analyzing medical images, and correlating diverse data points to make
diagnostic and treatment decisions. While some automated tools existed, they often lacked the sophistication to handle
the complexity and variability inherent in medical data. Moreover, existing healthcare systems faced challenges such as
limited scalability, lack of standardization in data formats, and difficulties in integrating heterogeneous data sources.
These limitations hindered the efficient analysis of large datasets and impeded the development of robust predictive
models for disease diagnosis, prognosis, and treatment response prediction. Although statistical methods and machine
learning algorithms were applied to healthcare data, they often struggled to capture complex patterns and relationships
within the data, leading to suboptimal performance in real-world clinical settings. Overall, the existing healthcare system
before the integration of deep learning was characterized by manual-intensive processes, limited automation, and
challenges in effectively leveraging the vast amounts of available medical data to improve patient care and health
outcomes.
3.2 DRAWBACKS:
The major drawbacks in the current existing systems are: System Compatibility 6 Legacy Systems: Many healthcare
institutions use old computer systems. These may not work well with new deep learning tools, needing updates or even
replacements. Interoperability Issues: Deep learning tools might not easily share data with existing patient record systems
due to different data formats and standards. Data Management and Security Data Silos: Patient data is often stored in
separate databases, making it hard to gather all the needed data for training deep learning models. Data Security: Using
deep learning requires strong security to protect patient information from hacks or unauthorized access, following strict
rules like HIPAA
The proposed system integrates various machine learning and deep learning algorithms, each tailored to specific
tasks within health analysis. Here's how these algorithms, including Convolutional Neural Networks (CNN), Random
Forest, Decision Tree, and Logistic Regression, contribute to the system: In the context of medical imaging analysis,
Convolutional Neural Networks (CNNs) are particularly effective. CNNs excel in learning hierarchical representations
4
of image data, making them well-suited for processing medical imaging data like MRI scans and X-rays. By
automatically detecting patterns and features within medical images, CNNs aid in the diagnosis of diseases such as
cancer or neurological disorders. For tasks involving predictive modeling and risk assessment based on structured data
such as electronic health records, Random Forest and Decision Tree algorithms are employed. Random Forest, as an
ensemble learning method, combines multiple decision trees to improve predictive accuracy and generalization. Decision
Trees, on the other hand, provide interpretable rules that guide clinical decision-making, making them valuable tools for
healthcare professionals. 7 Additionally, Logistic Regression is utilized for binary classification tasks, such as predicting
patient outcomes or assessing the likelihood of disease occurrence. Logistic Regression's interpretable coefficients offer
insights into the underlying relationships between variables, facilitating actionable insights for healthcare practitioners.
By incorporating these algorithms into the proposed system, healthcare practitioners can leverage the strengths of each
method to analyze diverse types of medical data and derive actionable insights for improving patient care and outcomes.
3.4 ADVANTAGES:
High Accuracy: Deep learning algorithms, particularly Convolutional Neural Networks (CNNs) for image
analysis, often achieve high accuracy rates in tasks such as medical image classification and segmentation.
This high accuracy leads to more reliable diagnoses and treatment recommendations. Feature Learning: Deep
learning models are capable of automatically learning relevant features from raw data, eliminating the need
for manual feature engineering. This ability is especially advantageous in healthcare, where complex and
heterogeneous data types are common. Complex Pattern Recognition: Deep learning excels at recognizing
complex patterns and relationships within data, including subtle variations that may be indicative of disease.
This capability enables the detection of early disease markers and predictive modeling of patient outcomes.
Scalability: Deep learning models can scale effectively with large datasets, accommodating the vast amounts
of medical data generated daily in healthcare systems worldwide. This scalability ensures that the models
remain effective even as data volumes increase. Transfer Learning: Deep learning models trained on large,
diverse datasets can be fine-tuned for specific healthcare applications with relatively small amounts of 8
domain-specific data. This transfer learning approach accelerates model development and deployment in
healthcare settings. Continuous Learning: Deep learning models can be updated with new data over time,
allowing them to adapt to evolving healthcare practices and patient populations. This continuous learning
capability ensures that the models remain relevant and effective in dynamic healthcare environments.
Automation of Repetitive Tasks: Deep learning algorithms can automate repetitive tasks in healthcare, such as
medical image analysis and patient risk stratification. This automation reduces the burden on healthcare
professionals, allowing them to focus on more complex decision-making tasks. Potential for Novel
Discoveries: Deep learning's ability to uncover hidden patterns in data opens up possibilities for novel
discoveries in healthcare, including new disease biomarkers, drug targets, and treatment strategies. These
discoveries have the potential to transform medical research and clinical practice.
Development Environment
• Programming Language: Python
5
• Integrated Development Environment (IDE): Visual Studio Code (VS Code)
• Package Management: Anaconda Hardware Requirements
• Operating System: Windows/Linux
• Processor: Intel Core i5 (or higher) or Ryzen
• RAM: Minimum 8GB (16GB recommended)
• Storage: Minimum 512 SSD
• Graphics: 2GB or 4GB Functional Requirements
Data Collection and Preprocessing: Implement data collection modules to fetch and preprocess healthcare
datasets.
Model Development: Develop and train deep learning models for disease prediction and medical imaging
analysis
.Web Application Development: Design and develop a web-based user interface for the application.
Data Visualization: Create interactive dashboards and graphical representations for data visualization.
Security and Compliance: 15 Implement user authentication and data encryption to ensure security.
Non-Functional Requirements Performance: The application should be able to handle multiple user requests
simultaneously without significant latency.
Scalability: The architecture should support scaling to accommodate increasing data volumes and user loads.
Usability: The user interface should be intuitive, user-friendly, and accessible on various devices.
Security: The application must comply with healthcare data privacy regulations , ensuring data protection and
confidentiality.
The health analysis system leveraging deep learning is developed using Python programming language and utilizes
Visual Studio Code (VS Code) as the Integrated Development Environment (IDE) and Anaconda for package
management and environment configuration. This software solution aims to enhance diagnostic accuracy, improve
patient care, and optimize healthcare systems through advanced deep learning techniques tailored for healthcare
applications.
1. User Authentication Module Description: This module handles user registration, login, and authentication
processes to ensure secure access to the application. Technology: Flask-Login, Flask-Security
2. Data Collection and Preprocessing Module Description: Responsible for collecting, cleaning, and preprocessing
healthcare datasets for model training and analysis. Technology: Pandas, NumPy
3. Model Development and Training Module Description: Develops and trains deep learning models tailored for
healthcare applications such as disease prediction and medical imaging analysis. Technology: Keras, CNN,
random forest, decision trees, logistic regression
4. Medical Imaging Analysis Module Description: Analyzes medical images (e.g., X-rays, MRI scans) to detect
abnormalities and assist in diagnosis. 23 Technology: OpenCV
5. Personalized Treatment Recommendation Module Description: Generates personalized treatment
recommendations based on individual patient health profiles and medical history. Technology: Custom
algorithms developed using Python libraries
6
6. Data Visualization and Dashboard Module Description: Creates interactive dashboards and visualizations to
present health analysis results in an intuitive manner.
7. 7.Security and Compliance Module Description: Ensures robust data security, encryption.
CHAPTER 4
SYSTEM IMPLEMENTATION
8
The project aims to develop a comprehensive health analysis web application
powered by deep learning technologies to enhance disease prediction, medical
imaging analysis, and personalized treatment recommendations. By focusing on
user-friendly design, data visualization, security, scalability, and user support, the
web application aims to empower healthcare professionals with advanced tools
and insights for improved patient care and clinical decision-making.
4.2 OUTLINE
Introduction:
Background: Overview of healthcare challenges and the potential of deep
learning in addressing them.
Project Objectives: Description of the project's goals, focusing on disease
prediction, medical imaging analysis, and personalized treatment
recommendations.
Literature Review:
Deep Learning in Healthcare: Survey of existing research and applications in
disease prediction, medical imaging analysis, and personalized medicine.
Challenges and Drawbacks: Exploration of the limitations and challenges
associated with integrating deep learning into healthcare systems.
Data Collection and Preprocessing
Data Sources: Identification and selection of relevant datasets, considering data
privacy regulations like HIPAA.
Data Preprocessing: Cleaning, normalization, and transformation of data to
prepare it for deep learning model training.
Model Development
Model Selection: Choosing appropriate deep learning architectures, such as
Convolutional Neural Networks (CNNs) for medical imaging and Recurrent
Neural Networks (RNNs) for sequential data.
Feature Engineering: Extracting and selecting relevant features from the data to
input into the deep learning models.
Model Training and Validation: Training and optimizing the models using the
preprocessed data, employing cross-validation techniques and performance
metrics to evaluate model efficacy.
Web Application Development
Frontend Development: Designing and developing a user-friendly interface for
healthcare professionals to interact with the deep learning-powered analysis tools.
Backend Development: Building the server-side infrastructure to support data
processing, model inference, and user authentication.
9
Integration: Integrating the trained deep learning models with the web application
to enable real-time prediction and analysis capabilities.
Data Visualization and Insights
Interactive Dashboards: Creating interactive data visualization tools to present
model predictions and insights intuitively.
Graphical Representations: Designing graphical representations, charts, and plots
to facilitate data exploration and interpretation by users.
Security and Compliance
User Authentication: Implementing secure authentication mechanisms to control
access to the web application.
Data Security: Ensuring data protection through encryption, anonymization, and
adherence to regulatory standards like HIPAA.
Testing and Validation
Functional Testing: Conducting rigorous testing of the web application's
functionality, performance, and usability.
Clinical Validation: Collaborating with healthcare professionals to validate the
clinical relevance and accuracy of the deep learning models and web application
outputs.
Deployment and Maintenance
Deployment: Deploying the web application on scalable cloud platforms or on-
premises infrastructure.
Maintenance and Updates: Monitoring the application's performance, conducting
regular updates, and providing ongoing support to ensure its reliability and
effectiveness.
Conclusion
Summary: Recapitulating the project's objectives, methodologies, findings, and
contributions to healthcare through deep learning.
Future Work: Identifying potential areas for further research, improvement, and
expansion of the web application and deep learning models.
Key features of the project include data collection and preprocessing, where
10
relevant datasets are identified. In the model development phase, specialized deep
learning models tailored for healthcare applications will be selected and trained to
handle complex medical data effectively.
The web application itself will be built with a user-centric approach, featuring an
intuitive and interactive interface that facilitates seamless interaction and data
visualization. This will enable healthcare professionals to explore and interpret
predictive analytics and diagnostic results with ease, empowering them to make
informed clinical decisions.
11
CHAPTER 5
12
5.5 FUTURE SCOPE
The Health Analysis Web Application, while already a robust and innovative
platform, has a promising future with opportunities for expansion, enhancement,
and integration of emerging technologies. Here's a look at some potential avenues
for future development and growth:
Telemedicine Integration
IoT Integration
Interface:
14
Admin Dashboard:
CHAPTER 6
CONCLUSION
The system architecture for the Health Analysis Web Application will
follow a three-tier architecture consisting of:
Presentation Layer: User Interface (UI) accessible via web browsers.
Application Layer: Backend server handling business logic and deep
learning model operations.
Data Layer: Database storage for user data, configurations, and model
parameters.
Components:
Presentation Layer
User Interface: Developed using HTML, CSS, for a responsive and
interactive UI.
15
Dashboard: Interactive dashboards for displaying health analysis results
using libraries.
Application Layer
Web Server: Utilizing Flask or Django to handle HTTP requests and
responses.
Deep Learning Models: Convolutional Neural Networks (CNN), logistic
regression, and decision trees etc. are integrated for disease prediction and
medical imaging analysis.
Data Processing: Pandas and NumPy for data manipulation and
preprocessing.
Data Layer
Database: SQL-based database to store user data, configurations, and
model parameters securely.
Data Storage: File storage systems for storing medical images and large
datasets.
Workflow:
User Authentication: Secure login and registration functionalities using
Flask-Login and Flask-Security.
Data Input: Upload or input patient data, medical records, and images via
the UI.
Data Processing: Preprocess input data using Pandas and NumPy to
prepare it for model ingestion.
Model Inference: Run deep learning models on the preprocessed data to
16
generate predictions and insights.
Result Presentation: Display analysis results on interactive dashboards and
visualizations.
Data Storage: Store user data, analysis results, and model parameters in
the database.
Security Measures:
Data Encryption: Encrypt sensitive data at rest and in transit using
cryptography libraries.
Authentication: Implement secure authentication mechanisms to control
user access.
Authorization: Role-based access control to manage user permissions and
data access.
Scalability and Performance:
Load Balancing: Distribute incoming application traffic across multiple
servers to ensure high availability and reliability.
Caching: Utilize caching mechanism to improve response times for
frequently accessed data.
17
CHAPTER 7
REFERENCES
1. Deep Learning Applications in Healthcare
• Kruse, C., Krowski, N., Rodriguez, B., Tran, L., Vela, J., & Brooks, M.
(2017). Telehealth and patient satisfaction: a systematic review and
narrative analysis. BMJ Open, 7(8), e016242.
CHAPTER 8
APPENDIX
CODE:
# Flask utils
from flask import Flask, redirect, url_for, request,
render_template
from werkzeug.utils import secure_filename
from gevent.pywsgi import WSGIServer
# root directory
webroot = 'src'
static_dir = os.path.join(webroot,'static')
template_dir = os.path.join(webroot,'templates')
# defining the flask app
app =
Flask(__name__,static_folder=static_dir,template_fol
der=template_dir)
# route for home page
@app.route('/',methods=['GET','POST'])
def index():
return render_template('index.html')
breast_file = "breast_model.sav"
loaded_breast_model = joblib.load(breast_file)
breast_pred =
loaded_breast_model.predict([[Radius_Mean,
Area_Mean, Compactness_Mean, Concavity_Mean,
Concave_Points_Mean, Area_Worst,
Compactness_Worst,Concavity_Worst,
Area_Se, Fractal_Dimension_Se,
Symmetry_Worst, Fractal_Dimension_Worst]])
breast_pred = round(100*breast_pred[0])
if(breast_pred == 0):
res = "Congratulations! you are safe from
Breast Cancer"
else:
res = "Sorry :( you have encountered with
21
Breast Cancer"
return
render_template('breastcancer.html',prediction=res)
except Exception as e:
print(e)
error=("Please fill all the fields for prediction")
error={"error":error}
return render_template("404.html",error=error)
else:
return render_template('breastcancer.html')
# Diabetes section
@app.route('/diabetes',methods=['GET','POST'])
def diabetes():
if request.method == "POST":
try:
Pregnancies =
float(request.form["Pregnancies"])
Glucose = float(request.form["Glucose"])
Bloodpressure =
float(request.form["Bloodpressure"])
SkinThickness =
float(request.form["SkinThickness"])
Insulin = float(request.form["Insulin"])
BMIn = float(request.form["BMI"])
DiabetesPedigreeFunction =
float(request.form["DiabetesPedigreeFunction"])
Age = float(request.form["Age"])
filename = "diabetes.sav"
loaded_model = joblib.load(filename)
dia_pred =
loaded_model.predict([[Pregnancies,Glucose,Bloodpr
essure,SkinThickness,Insulin,BMIn,DiabetesPedigree
Function,Age]])
22
dia_pred = round(100*dia_pred[0])
if(dia_pred == 0):
res = "Congratulations! you are safe from
Diabetes"
else:
res = "Sorry :( you have encountered with
Diabetes"
return
render_template('diabetes.html',prediction=res)
except Exception as e:
print(e)
error=("Please fill all the fields for diabetes
prediction")
error={"error":error}
return render_template("404.html",error=error)
else:
return render_template('diabetes.html')
@app.route('/heart',methods=['GET','POST'])
def heart():
if request.method == 'POST':
try:
Age = float(request.form["age"])
sex = (request.form["sex"])
if(sex == "male"):
sex = 1
else:
sex = 0
#chest pain
chestpain = (request.form["chestpain"])
if(chestpain == "ATA"):
chestpain = 1
elif (chestpain == "NAP"):
chestpain = 2
23
elif (chestpain == "ASY"):
chestpain = 0
else:
chestpain = 3
# resting bp
restingbp = float(request.form["restingbp"])
cholestrol = float(request.form["cholestrol"])
fastingbs = float(request.form["fastingbs"])
restingecg = (request.form["restingecg"])
if(restingecg == "Normal"):
restingecg = 1
elif (restingecg == "ST"):
restingecg = 2
else:
restingecg = 0
maxhr = float(request.form["maxhr"])
exercise = (request.form["exercise"])
if(exercise == "N"):
exercise = 0
else:
exercise = 1
oldpeak = float(request.form["oldpeak"])
stslope = (request.form["stslope"])
if(stslope == "up"):
stslope = 2
elif(stslope == "flat"):
stslope = 1
else:
stslope = 0
file_heart = "heart_model.sav"
loaded_model = joblib.load(file_heart)
heart_pred = loaded_model.predict([[Age, sex,
chestpain, restingbp, cholestrol, fastingbs, restingecg,
24
maxhr,
exercise, oldpeak, stslope]])
heart_pred = round(100*heart_pred[0])
if(heart_pred == 0):
res = "Congratulations! you are safe from
Heart Disease"
else:
res = "Sorry :( you have encountered with
Heart Failure"
return render_template('heart.html',predict =
res)
except Exception as e:
print(e)
error=("Please fill all the fields for heart disease
prediction")
error={"error":error}
return render_template("404.html",error=error)
else:
return render_template('heart.html')
@app.route('/pneumonia',methods=['GET','POST'])
def pneumonia():
if request.method == 'POST':
# try:
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, '', secure_filename(f.filename))
f.save(file_path)
# Make prediction
preds = pneumonia_predict(file_path, model)
os.remove(file_path)#removes file from the
server after prediction has been returned
if preds == 1:
res = "Sorry :( you have got the chances of
Pneumonia"
else:
res = "Congratulations! you are safe from
Pneumonia"
return
render_template('pneumonia.html',prediction=res)
# except Exception as e:
# print(e)
# error=("Have you uploaded the image??")
# error={"error":error}
# return
26
render_template("404.html",error=error)
return render_template('pneumonia.html')
if __name__=="__main__":
app.run(debug=True,port=port,host="0.0.0.0")
Setup:
from setuptools import setup,find_packages
setup(
name='main',
version='0.1.0',
description='Main package for this repository',
install_requires=['flask','flask_cors','joblib','numpy',],
packages=find_packages(),license="MIT"
)
CSS:
body {
font-family: 'Open Sans', sans-serif;
line-height: 20px;
color: #999999;
font-size: 300;
27
font-size: 16px;
}
li, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
h1, h2, h3, h4, h5, h6
{
font-family: 'Raleway', sans-serif;
font-weight: 600;
color: #222222;
}
a, a:hover, a:focus, a:active{
outline: none;
}
.section-padding{
padding: 60px 0px;
}
h2 {
line-height: 20px;
margin: 0;
font-size: 28px;
font-weight: 700;
28
text-transform: uppercase;
}
hr.botm-line {
height: 3px;
width: 60px;
background: #ffb737;
position: relative;
border: 0;
margin: 20px 0 20px 0;
}
/***************************************
top-section
***************************************/
.navbar {
margin-bottom: 0px;
border: 0px;
}
.navbar {
border-radius: 0px;
}
.navbar-default {
background-color: rgb(253, 253, 253);
padding: 20px 0;
transition: all 0.3s;
}
.navbar-default {
background-color:rgba(6, 58, 82, 0.78);
border: 0px;
}
.navbar {
border-radius: 0px;
}
.navbar-brand
{
29
font-family: 'Nunito Sans', sans-serif;
font-size: 31px;
}
.navbar-brand img {
padding-top: 2px;
width: 120px !important;
}
}
@media (max-width: 768px) {
.navbar-collapse {
background: rgba(28,74,90, 0.9);
}
}
.top-nav-collapse {
padding: 0;
background:rgba(28,74,90, 0.9);
}
33
plt.xlabel('Epoch')
plt.legend(['Test', 'Validation'], loc='upper right')
plt.show()
def names(number):
if number==0:
return 'Its a Tumor'
else:
return 'No, Its not a tumor'
from matplotlib.pyplot import imshow
img = Image.open(r"C:\Users\U\Downloads\brain tumour
detection\datasets\yes\y1.jpg")
x = np.array(img.resize((128,128)))
x = x.reshape(1,128,128,3)
res = model.predict_on_batch(x)
34
classification = np.where(res == np.amax(res))[1][0]
imshow(img)
print(str(res[0][classification]*100) + '% Confidence This Is ' +
names(classification))
50.09170174598694% Confidence This Is Its a Tumor
#import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import preprocessing
from sklearn import metrics
36
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import plot_confusion_matrix, accuracy_score,
classification_report
import joblib
# standard scaler
scaler = StandardScaler()
data_temp = scaler.fit_transform(data_temp)
'''Logistic Regression'''
log = LogisticRegression()
log.fit(X_train, y_train)
# save the model
filename = 'breast_model.sav'
joblib.dump(log, filename)
Pneumonia detection:
Count number of infected and normal:
count_me = []
for i in train:
if(i[1] == 0):
count_me.append("Pneumonia")
else:
count_me.append("Normal")
sns.set_style('darkgrid')
sns.countplot(count_me)
Incorrect prediction:
i=0
for c in incorrect[:6]:
plt.subplot(4,2,i+1)
plt.xticks([])
40
plt.yticks([])
plt.imshow(x_test[c].reshape(150,150), cmap="gray",
interpolation='none')
plt.title("Predicted Class {},Actual Class {}".format(y_pred[c], y_test[c]))
plt.tight_layout()
i += 1
Malaria detection:
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import keras
from keras.models import Sequential
from keras.layers import Dense, Conv2D , MaxPool2D , Flatten , Dropout ,
BatchNormalization
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report,confusion_matrix
from keras.callbacks import ReduceLROnPlateau
import cv2
from keras.models import load_model
Visualize the image:
plt.figure(figsize = (20,10))
41
for i in range(9):
plt.subplot(3, 3, i+1)
img = plt.imread(os.path.join(malaria_dir, malaria_infected[i]))
plt.imshow(img, cmap='gray')
plt.title('Malaria infection image')
plt.show()
Normal image:
plt.figure(figsize = (20,10))
for i in range(9):
plt.subplot(3, 3, i+1)
img = plt.imread(os.path.join(normal_dir, normal[i]))
plt.imshow(img, cmap='gray')
plt.title('Normal Image')
plt.show()
42
Malaria infected:
plt.figure(figsize = (6,6))
plt.imshow(train[0][0],cmap='gray')
plt.title(labels[train[0][1]])
Text(0.5, 1.0, 'parasite')
plt.figure(figsize = (6,6))
plt.imshow(train[-1][0], cmap='gray')
plt.title(labels[train[-1][1]])
Text(0.5, 1.0, 'normal')
43
Thyroid prediction:
data.describe(include="all")
<class 'pandas.core.frame.DataFrame'> RangeIndex: 3772 entries, 0 to 3771
Data columns (total 28 columns): # Column Non-Null Count Dtype --- ------
-------------- ----- 0 age 3771 non-null object
1 sex 3622 non-null object
2 on thyroxine 3772 non-null int64
3 query on thyroxine 3772 non-null int64
4 on antithyroid medication 3772 non-null int64 ]
5 sick 3772 non-null int64
6 pregnant 3772 non-null int64
7 thyroid surgery 3772 non-null int64
8 I131 treatment 3772 non-null int64
9 query hypothyroid 3772 non-null int64
10 query hyperthyroid 3772 non-null int64
11 lithium 3772 non-null int64
12 goitre 3772 non-null int64
44
13 tumor 3772 non-null int64
14 hypopituitary 3772 non-null int64
15 psych 3772 non-null int64
16 TSH measured 3772 non-null int64
17 TSH 3403 non-null object
18 T3 measured 3772 non-null int64
19 T3 3003 non-null object...
26 TBG measured 3772 non-null int64 27 binaryClass 3772 non-null int32
dtypes: int32(1), int64(20), object(7)
Diabetes prediction:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
45
import seaborn as sns
import missingno as msno
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import mean_squared_error
from sklearn import metrics
from sklearn.metrics import plot_confusion_matrix, accuracy_score,
classification_report
import joblib
46
index = 0
ax = ax.flatten()
rf = RandomForestClassifier().fit(X_train,y_train)
rp = rf.predict(X_test)
47
print(classification_report(y_test, rp))
plot_confusion_matrix(rf,X_test,y_test)
48