0% found this document useful (0 votes)
27 views

Muskan Project Report

Uploaded by

kochharmuskan2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Muskan Project Report

Uploaded by

kochharmuskan2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Project Report

on
Medicine Recommendation System
in Python
CSE IV-Sem
(Mini project)

DEPARTMENT OF COMPUTER SCIENCE


AND ENGINEERING

Submitted By : Submitted To :
Name :MUSKAN KOCHHAR Mr. Rahul
University Roll No. : 2219122 Chauhan
Class Roll No. : 39 Graphic Era Hill University
CSE-A2 (IV-Sem) DDN
Session : 2023-2024
CANDIDATE’S DECLARATION

I hereby certify that the work which is being presented in the project report entitled
“Medicine Recommendation System” in partial fulfillment of the requirements for the
award of the Degree of Bachelor of Technology in Computer Science and Engineering of the
Graphic Era Hill University, Dehradun has been carried out by me under my own guidance.

Name: Muskan Kochhar University Roll no.: 2219122


Introduction

Hospitals have access to vast amount of data about patients and their health parameters. Thus,
there is a need for convenient way for medical professionals to utilize this information
effectively. An example would be the access to aggregated information from existing database
on a specific problem at the point of care when it is necessary. Moreover, there are more
drugs, tests, and treatment recommendations (e.g. evidence-based medicine or clinical
pathways) available for medical staff every day. Thus, it becomes increasingly difficult for
them to decide which treatment to provide to a patient based on her symptoms, test results or
previous medical history.

On the other hand, all these data can be used to strive personalized healthcare which is
currently on the rise and predicted to get a major disruptive trend in healthcare in the
upcoming years. Therefore, a recommendation engine for medical use could be employed to
fill this gap and support decision making during therapy. Based on a patient’s current health
status, prehistory, current medications, symptoms and past treatments, the engine can look for
individuals with similar parameters in the database. At the end, the recommender system
would suggest the drugs that were most successful for similar patients. With the help of such a
system, the doctor will be able to make a better-informed decision on how to treat a patient.
Abstract
Nowadays people are progressively started caring about the health and medical diagnosis problems.
However, according to the administration’s report, more than 1 crore people every year die due to
medication error done by novices (New doctors). More than 42% medication errors are caused by
doctors because they provide prescriptions according to their experience which are quite limited. And
sometimes they have left many parts of the book they have read Technologies as data mining and
recommender technologies provide possibilities to explore potential knowledge from diagnosis history
and help the doctors to prescribe medication correctly to decrease the medication error. In this
recommendation we will design and implement a universal medicine recommender system framework
that applies data mining technologies to the recommendation system. The medicine recommender
system consists of database system module, recommendation model module, model evaluation, and
data visualization module
AIM of this project
The aim of a medicine recommendation system is to improve the accuracy, efficiency, and
personalization of medication prescriptions. Key objectives include:

1. Personalized Treatment: Tailor medication suggestions based on individual patient data to


enhance treatment outcomes.

2. Decision Support: Assist healthcare providers in making informed prescription decisions,


reducing their cognitive load.

3. Safety and Accuracy: Minimize prescription errors and monitor potential drug interactions to
ensure patient safety.

4. Efficiency and Cost-Effectiveness: Optimize healthcare resources and reduce costs by


improving prescription accuracy and reducing adverse drug reactions.

5. Data Utilization: Leverage large datasets from electronic health records and clinical studies to
provide data-driven recommendations.
PROBLEM DEFINITION

Medicine recommendation is one of the most important and challenging tasks in the modern
world. As there are many new diseases which are discovered by the doctors sometime a
medicine for one disease can lead to the side- effects which can further lead to the discovery
of new diseases. Our goal is to build such a recommendation model which will help the
doctors to prescribe a medicine to the patient t even if they have not studied about that before
the doctor has to open the framework and has to search about the diseases of the patient it will
also help to the inexperienced doctors and patients for using the right drugs high accuracy and
efficiency is very critical for such a recommender system.
SYSTEM ARCHITECTURE

1. Interfaces
There is a single type of interface as such supported by our system namely

2. User Interfaces:
The product will exist on a real-life system. The Interface will be a simple and easy to use interface.
The user needs to give input of the diseases which they are looking for after that the medicine will be
predicted according to the symptoms entered the result box will display the result of the fired query.

3. Hardware Interfaces:
The system has minimal Hardware interfaces. A normal personal desktop or a laptop will be a good
choice to run the system. It is recommended for the system to have higher ram and processing power in
order to compute and predict quickly

4.Software Interface:
To apply machine learning libraries such as are Pandas, NumPy, Sklearn etc. are used to load and train
the dataset. VS Code or Jupyter Notebook is used to run the algorithms.

5. System Analysis and Design:


The data for the medicine is very huge and consist various parameters the data has been segregated
according to the diseases the data indicates medicine along with the reviews of the patient who used it
this data was used to train the model and predict the medicine using machine learning algorithms.
• Graphical User Interface: The medicine recommender System takes the input from the user about
the diseases user is feeling after that it will give different medicines that can be used to cure the
diseases.
• Reliability & Availability: Our system will be highly available as it does not use any internet or
cloud technology. Our system relies on the data that is pre- stored and doesn’t require to be connected
to third party for resources.
• Performance: The performance of our system is high as compared to other models. We have an
accuracy of around 70-75 % which is more than any other algorithm that is used.
Benefits of Medicine Recommendation System

A medicine recommendation system offers numerous benefits, including:

1. Personalized Treatment:
- Tailors medication suggestions to individual patient profiles, improving the effectiveness
of treatments.

2. Improved Accuracy:
- Reduces prescription errors by considering comprehensive patient data and potential drug
interactions.

3. Time Efficiency:
- Saves time for healthcare providers by quickly providing relevant medication options.

4. Enhanced Patient Outcomes:


- Increases the likelihood of successful treatments and patient satisfaction through accurate
medication matching.

5. Cost Savings:
- Lowers healthcare costs by reducing adverse drug reactions and unnecessary treatments.

6. Decision Support:
- Assists doctors with data-driven insights, enhancing their decision-making process.

7. Comprehensive Data Utilization:


- Leverages large datasets from electronic health records, clinical studies, and patient
reviews to inform recommendations.

8. Consistency in Care:
- Ensures consistent and standardized medication prescribing practices across different
healthcare providers.

9. Reduced Cognitive Load:


- Lessens the mental burden on healthcare providers, allowing them to focus more on patient
care.

10. Proactive Health Management:


- Identifies potential health issues early by monitoring patient data and medication
responses.
Future Look
The future of medicine recommendation systems holds exciting possibilities, driven by advancements
in technology and healthcare integration. Here's what we can expect:

1. Artificial Intelligence and Machine Learning


- **Enhanced Algorithms**: More sophisticated AI and machine learning models capable of
processing vast amounts of data to provide highly accurate recommendations.
- **Predictive Analytics**: Advanced models predicting patient outcomes and proactively suggesting
preventive measures.

2. Integration with Genomic Data


- **Personalized Medicine**: Incorporation of genetic information to recommend medications tailored
to an individual's genetic makeup, improving efficacy and reducing adverse reactions.
- **Pharmacogenomics**: Utilization of genomic data to understand how different patients respond to
medications.

3. Real-Time Data Processing


- **Continuous Monitoring**: Real-time integration with wearable devices and IoT to monitor patient
vitals and adjust recommendations dynamically.
- **Instant Feedback**: Immediate updates and recommendations based on the latest patient data and
health status.

4. Advanced Natural Language Processing (NLP)


- **Understanding Unstructured Data**: Improved NLP capabilities to better interpret and utilize
doctors' notes, patient reviews, and other unstructured data sources.
- **Conversational Interfaces**: AI-driven chatbots and virtual assistants capable of interacting with
patients and providers in natural language.

5. Enhanced Interoperability
- **Unified Health Records**: Seamless integration with various health information systems, ensuring
all relevant patient data is available for analysis.
- **Standardized Protocols**: Adoption of global standards for data exchange and system
interoperability.

6. Telemedicine Integration
- **Remote Recommendations**: Integration with telemedicine platforms to provide medication
recommendations during virtual consultations.
- **Global Reach**: Expanding access to expert recommendations for patients in remote or
underserved areas.

7. Ethical and Secure Systems


- **Data Privacy and Security**: Advanced encryption and security measures to protect patient data.
- **Ethical AI**: Development of transparent, fair, and unbiased algorithms.

8. Comprehensive Health Management


- **Holistic View**: Systems offering comprehensive health management, including lifestyle
recommendations, diet plans, and mental health support.
- **Integrated Health Services**: Coordination with pharmacies, labs, and other health services for
streamlined patient care.
Source Code

import pandas as pd
dataset = pd.read_csv('Training.csv')
print("Shape of the dataset = ", dataset.shape) from sklearn.model_selection import
train_test_split
from sklearn.preprocessing import LabelEncoder
import numpy as np

# Dividing dataset into X = symptoms and y = Disease Prediction


X = dataset.drop('prognosis', axis=1)
y = dataset['prognosis']
print("Dataset = ", dataset)

# ecoding
le = LabelEncoder()
le.fit(y)
Y = le.transform(y)
print ("Encoded Y =", np.unique(Y))

#splitting in training(70%) and testing(30%)


X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3,
random_state=20)

print("Number of Training Samples = ", np.shape(X_train))


print("Number of Testing Samples = ", np.shape(X_test))

from sklearn.datasets import make_classification


from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, confusion_matrix
import numpy as np

# Create a dictionary to store models


models = {
'SVC': SVC(kernel='linear'),
'KNeighbors': KNeighborsClassifier(n_neighbors=5)
}
# Loop through the models, train, test, and print results

for model_name, model in models.items():

# Train the model


model.fit(X_train, y_train)

# Test the model


predictions = model.predict(X_test)

# Calculate confusion matrix


cm = confusion_matrix(y_test, predictions)
print("Shape of Confusion Matrix = ", cm.shape)
print(f"{model_name} Confusion Matrix:")
print(np.array2string(cm, separator=', '))

# Calculate accuracy = (TP + TN) / (TP + FP + TN + FN)


accuracy = accuracy_score(y_test, predictions)
print(f"{model_name} Accuracy: {accuracy}")

print("\n" + "="*40 + "\n")

# selecting svc
svc = SVC(kernel='linear')
svc.fit(X_train,y_train)
ypred = svc.predict(X_test)
accuracy_score(y_test,ypred)

# save svc
import pickle
pickle.dump(svc,open('svc.pkl','wb'))

# load model
# Open the pickle file in read-binary mode ('rb')
with open('svc.pkl', 'rb') as f:
data = pickle.load(f)

# test 1:
print("predicted disease :",svc.predict(X_test.iloc[0].values.reshape(1,-1)))
print("Actual Disease :", y_test[0])
# test 2:
print("predicted disease :",svc.predict(X_test.iloc[15].values.reshape(1,-1)))
print("Actual Disease :", y_test[15])
# sym_des (contains information about symptoms loaded from symtoms_df.csv)
sym_des = pd.read_csv("symtoms_df.csv")

# precautions (contains information about precautions to take and is loaded from


precautions_df.csv)
precautions = pd.read_csv("precautions_df.csv")

# workout (contains information about recommended workout and is loaded from


workout_df.csv)
workout = pd.read_csv("workout_df.csv")

# description (contains information about description of the predicted disease and is


loaded from description.csv)
description = pd.read_csv("description.csv")

# medications (contains information about prescribed medicines and is loaded from


medications.csv)
medications = pd.read_csv('medications.csv')

# diets (contains information about prescribed diet and is loaded from diets.csv)
diets = pd.read_csv("diets.csv")
def helper(dis):
desc = description[description['Disease'] == predicted_disease]['Description']
desc = " ".join([w for w in desc])

pre = precautions[precautions['Disease'] == dis][['Precaution_1', 'Precaution_2',


'Precaution_3', 'Precaution_4']]
pre = [col for col in pre.values]

med = medications[medications['Disease'] == dis]['Medication']


med = [med for med in med.values]

die = diets[diets['Disease'] == dis]['Diet']


die = [die for die in die.values]

wrkout = workout[workout['disease'] == dis] ['workout']

return desc,pre,med,die,wrkout

symptoms_dict = {'itching': 0, 'skin_rash': 1, 'nodal_skin_eruptions': 2,


'continuous_sneezing': 3, 'shivering': 4, 'chills': 5, 'joint_pain': 6,
'stomach_pain': 7, 'acidity': 8, 'ulcers_on_tongue': 9, 'muscle_wasting': 10,
'vomiting': 11, 'burning_micturition': 12, 'spotting_ urination': 13, 'fatigue': 14,
'weight_gain': 15, 'anxiety': 16, 'cold_hands_and_feets': 17, 'mood_swings': 18,
'weight_loss': 19, 'restlessness': 20, 'lethargy': 21, 'patches_in_throat': 22,
'irregular_sugar_level': 23, 'cough': 24, 'high_fever': 25, 'sunken_eyes': 26,
'breathlessness': 27, 'sweating': 28, 'dehydration': 29, 'indigestion': 30,
'headache': 31, 'yellowish_skin': 32, 'dark_urine': 33, 'nausea': 34,
'loss_of_appetite': 35, 'pain_behind_the_eyes': 36, 'back_pain': 37, 'constipation':
38, 'abdominal_pain': 39, 'diarrhoea': 40, 'mild_fever': 41, 'yellow_urine': 42,
'yellowing_of_eyes': 43, 'acute_liver_failure': 44, 'fluid_overload': 45,
'swelling_of_stomach': 46, 'swelled_lymph_nodes': 47, 'malaise': 48,
'blurred_and_distorted_vision': 49, 'phlegm': 50, 'throat_irritation': 51,
'redness_of_eyes': 52, 'sinus_pressure': 53, 'runny_nose': 54, 'congestion': 55,
'chest_pain': 56, 'weakness_in_limbs': 57, 'fast_heart_rate': 58,
'pain_during_bowel_movements': 59, 'pain_in_anal_region': 60, 'bloody_stool': 61,
'irritation_in_anus': 62, 'neck_pain': 63, 'dizziness': 64, 'cramps': 65, 'bruising':
66, 'obesity': 67, 'swollen_legs': 68, 'swollen_blood_vessels': 69,
'puffy_face_and_eyes': 70, 'enlarged_thyroid': 71, 'brittle_nails': 72,
'swollen_extremeties': 73, 'excessive_hunger': 74, 'extra_marital_contacts': 75,
'drying_and_tingling_lips': 76, 'slurred_speech': 77, 'knee_pain': 78,
'hip_joint_pain': 79, 'muscle_weakness': 80, 'stiff_neck': 81, 'swelling_joints': 82,
'movement_stiffness': 83, 'spinning_movements': 84, 'loss_of_balance': 85,
'unsteadiness': 86, 'weakness_of_one_body_side': 87, 'loss_of_smell': 88,
'bladder_discomfort': 89, 'foul_smell_of urine': 90, 'continuous_feel_of_urine': 91,
'passage_of_gases': 92, 'internal_itching': 93, 'toxic_look_(typhos)': 94,
'depression': 95, 'irritability': 96, 'muscle_pain': 97, 'altered_sensorium': 98,
'red_spots_over_body': 99, 'belly_pain': 100, 'abnormal_menstruation': 101,
'dischromic _patches': 102, 'watering_from_eyes': 103, 'increased_appetite': 104,
'polyuria': 105, 'family_history': 106, 'mucoid_sputum': 107, 'rusty_sputum': 108,
'lack_of_concentration': 109, 'visual_disturbances': 110,
'receiving_blood_transfusion': 111, 'receiving_unsterile_injections': 112, 'coma':
113, 'stomach_bleeding': 114, 'distention_of_abdomen': 115,
'history_of_alcohol_consumption': 116, 'fluid_overload.1': 117, 'blood_in_sputum':
118, 'prominent_veins_on_calf': 119, 'palpitations': 120, 'painful_walking': 121,
'pus_filled_pimples': 122, 'blackheads': 123, 'scurring': 124, 'skin_peeling': 125,
'silver_like_dusting': 126, 'small_dents_in_nails': 127, 'inflammatory_nails': 128,
'blister': 129, 'red_sore_around_nose': 130, 'yellow_crust_ooze': 131}
diseases_list = {15: 'Fungal infection', 4: 'Allergy', 16: 'GERD', 9: 'Chronic
cholestasis', 14: 'Drug Reaction', 33: 'Peptic ulcer diseae', 1: 'AIDS', 12: 'Diabetes
', 17: 'Gastroenteritis', 6: 'Bronchial Asthma', 23: 'Hypertension ', 30: 'Migraine',
7: 'Cervical spondylosis', 32: 'Paralysis (brain hemorrhage)', 28: 'Jaundice', 29:
'Malaria', 8: 'Chicken pox', 11: 'Dengue', 37: 'Typhoid', 40: 'hepatitis A', 19:
'Hepatitis B', 20: 'Hepatitis C', 21: 'Hepatitis D', 22: 'Hepatitis E', 3: 'Alcoholic
hepatitis', 36: 'Tuberculosis', 10: 'Common Cold', 34: 'Pneumonia', 13: 'Dimorphic
hemmorhoids(piles)', 18: 'Heart attack', 39: 'Varicose veins', 26: 'Hypothyroidism',
24: 'Hyperthyroidism', 25: 'Hypoglycemia', 31: 'Osteoarthristis', 5: 'Arthritis', 0:
'(vertigo) Paroymsal Positional Vertigo', 2: 'Acne', 38: 'Urinary tract infection',
35: 'Psoriasis', 27: 'Impetigo'}
def get_predicted_value(patient_symptoms):
input_vector = np.zeros(len(symptoms_dict))
for item in patient_symptoms:
input_vector[symptoms_dict[item]] = 1
p = diseases_list[svc.predict([input_vector])[0]]
return p

# Demo Symptoms 1 = itching,skin_rash,nodal_skin_eruptions


# Demo Symptoms 2 = yellow_crust_ooze, red_sore_around_nose, small_dents_in_nails,
blister, inflammatory_nails

symptoms = input("Enter your symptoms.......")

# making list
user_symptoms = [s.strip() for s in symptoms.split(',')]

# Remove any extra characters, if any


user_symptoms = [symptom.strip("[]' ") for symptom in user_symptoms]

# use get_predicted_value function


predicted_disease = get_predicted_value(user_symptoms)

desc, pre, med, die, wrkout = helper(predicted_disease)

print("=================predicted disease============")
print(predicted_disease)
print("=================description==================")
print(desc)
print("=================precautions==================")
i = 1
for p_i in pre[0]:
print(i, ": ", p_i)
i += 1

print("=================medications==================")
for m_i in med:
print(i, ": ", m_i)
i += 1

print("=================workout==================")
for w_i in wrkout:
print(i, ": ", w_i)
i += 1

print("=================diets==================")
for d_i in die:
print(i, ": ", d_i)
i += 1
Conclusion
We devise a universal medicine recommender system framework that applies data
mining technologies to the medical diagnosis, which consists of database system
module, data preparation module, recommendation model module, model evaluation
model, and data visualization module. And we give a concrete implementation of each
module based on an open dataset. Experiments are done to evaluate the models, finally,
SVM is selected for the medicine recommendation model for its high accuracy, good
efficiency and scalability in this open dataset. In consideration of the safety of the
patient, we also proposed a mistaken-check mechanism that ensures the safety and the
quality of service. In future work, we plan to build our own recommendation model to
improve the accuracy and efficiency of model further. We also plan to apply Map
Reduce parallel technologies to our medicine recommender System to enlarge the
ability of processing big diagnosis data

You might also like