Obotu commited on
Commit
10442fc
1 Parent(s): dd20df3

Upload medicine_recommendation_system.py

Browse files
Files changed (1) hide show
  1. medicine_recommendation_system.py +223 -0
medicine_recommendation_system.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Medicine Recommendation System.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/14_xuicBiGfCSaq81L12iVQ2rMCUTxXHC
8
+
9
+ # Title: Personalized Medical Recommendation System with Machine Learning
10
+
11
+ # Description:
12
+
13
+ Welcome to our cutting-edge Personalized Medical Recommendation System, a powerful platform designed to assist users in understanding and managing their health. Leveraging the capabilities of machine learning, our system analyzes user-input symptoms to predict potential diseases accurately.
14
+
15
+ # load dataset & tools
16
+ """
17
+
18
+ import pandas as pd
19
+
20
+ dataset = pd.read_csv('Training.csv')
21
+
22
+ dataset
23
+
24
+ # vals = dataset.values.flatten()
25
+
26
+ dataset.shape
27
+
28
+ """# train test split"""
29
+
30
+ from sklearn.model_selection import train_test_split
31
+ from sklearn.preprocessing import LabelEncoder
32
+
33
+ X = dataset.drop('prognosis', axis=1)
34
+ y = dataset['prognosis']
35
+
36
+ # ecoding prognonsis
37
+ le = LabelEncoder()
38
+ le.fit(y)
39
+ Y = le.transform(y)
40
+
41
+ X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=20)
42
+
43
+ """# Training top models"""
44
+
45
+ from sklearn.datasets import make_classification
46
+ from sklearn.model_selection import train_test_split
47
+ from sklearn.svm import SVC
48
+ from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
49
+ from sklearn.neighbors import KNeighborsClassifier
50
+ from sklearn.naive_bayes import MultinomialNB
51
+ from sklearn.metrics import accuracy_score, confusion_matrix
52
+ import numpy as np
53
+
54
+
55
+ # Create a dictionary to store models
56
+ models = {
57
+ 'SVC': SVC(kernel='linear'),
58
+ 'RandomForest': RandomForestClassifier(n_estimators=100, random_state=42),
59
+ 'GradientBoosting': GradientBoostingClassifier(n_estimators=100, random_state=42),
60
+ 'KNeighbors': KNeighborsClassifier(n_neighbors=5),
61
+ 'MultinomialNB': MultinomialNB()
62
+ }
63
+
64
+ # Loop through the models, train, test, and print results
65
+ for model_name, model in models.items():
66
+ # Train the model
67
+ model.fit(X_train, y_train)
68
+
69
+ # Test the model
70
+ predictions = model.predict(X_test)
71
+
72
+ # Calculate accuracy
73
+ accuracy = accuracy_score(y_test, predictions)
74
+ print(f"{model_name} Accuracy: {accuracy}")
75
+
76
+ # Calculate confusion matrix
77
+ cm = confusion_matrix(y_test, predictions)
78
+ print(f"{model_name} Confusion Matrix:")
79
+ print(np.array2string(cm, separator=', '))
80
+
81
+ print("\n" + "="*40 + "\n")
82
+
83
+ """# single prediction"""
84
+
85
+ # selecting svc
86
+ svc = SVC(kernel='linear')
87
+ svc.fit(X_train,y_train)
88
+ ypred = svc.predict(X_test)
89
+ accuracy_score(y_test,ypred)
90
+
91
+ # save svc
92
+ import pickle
93
+ pickle.dump(svc,open('svc.pkl','wb'))
94
+
95
+ # load model
96
+ svc = pickle.load(open('svc.pkl','rb'))
97
+
98
+ # test 1:
99
+ print("predicted disease :",svc.predict(X_test.iloc[0].values.reshape(1,-1)))
100
+ print("Actual Disease :", y_test[0])
101
+
102
+ # test 2:
103
+ print("predicted disease :",svc.predict(X_test.iloc[100].values.reshape(1,-1)))
104
+ print("Actual Disease :", y_test[100])
105
+
106
+ """# Recommendation System and Prediction
107
+
108
+ # load database and use logic for recommendations
109
+ """
110
+
111
+ sym_des = pd.read_csv("symtoms_df.csv")
112
+ precautions = pd.read_csv("precautions_df.csv")
113
+ workout = pd.read_csv("workout_df.csv")
114
+ description = pd.read_csv("description.csv")
115
+ medications = pd.read_csv('medications.csv')
116
+ diets = pd.read_csv("diets.csv")
117
+
118
+ #============================================================
119
+ # custome and helping functions
120
+ #==========================helper funtions================
121
+ def helper(dis):
122
+ desc = description[description['Disease'] == predicted_disease]['Description']
123
+ desc = " ".join([w for w in desc])
124
+
125
+ pre = precautions[precautions['Disease'] == dis][['Precaution_1', 'Precaution_2', 'Precaution_3', 'Precaution_4']]
126
+ pre = [col for col in pre.values]
127
+
128
+ med = medications[medications['Disease'] == dis]['Medication']
129
+ med = [med for med in med.values]
130
+
131
+ die = diets[diets['Disease'] == dis]['Diet']
132
+ die = [die for die in die.values]
133
+
134
+ wrkout = workout[workout['disease'] == dis] ['workout']
135
+
136
+
137
+ return desc,pre,med,die,wrkout
138
+
139
+ 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}
140
+ 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'}
141
+
142
+ # Model Prediction function
143
+ def get_predicted_value(patient_symptoms):
144
+ input_vector = np.zeros(len(symptoms_dict))
145
+ for item in patient_symptoms:
146
+ input_vector[symptoms_dict[item]] = 1
147
+ return diseases_list[svc.predict([input_vector])[0]]
148
+
149
+ # Test 1
150
+ # Split the user's input into a list of symptoms (assuming they are comma-separated) # itching,skin_rash,nodal_skin_eruptions
151
+ symptoms = input("Enter your symptoms.......")
152
+ user_symptoms = [s.strip() for s in symptoms.split(',')]
153
+ # Remove any extra characters, if any
154
+ user_symptoms = [symptom.strip("[]' ") for symptom in user_symptoms]
155
+ predicted_disease = get_predicted_value(user_symptoms)
156
+
157
+ desc, pre, med, die, wrkout = helper(predicted_disease)
158
+
159
+ print("=================predicted disease============")
160
+ print(predicted_disease)
161
+ print("=================description==================")
162
+ print(desc)
163
+ print("=================precautions==================")
164
+ i = 1
165
+ for p_i in pre[0]:
166
+ print(i, ": ", p_i)
167
+ i += 1
168
+
169
+ print("=================medications==================")
170
+ for m_i in med:
171
+ print(i, ": ", m_i)
172
+ i += 1
173
+
174
+ print("=================workout==================")
175
+ for w_i in wrkout:
176
+ print(i, ": ", w_i)
177
+ i += 1
178
+
179
+ print("=================diets==================")
180
+ for d_i in die:
181
+ print(i, ": ", d_i)
182
+ i += 1
183
+
184
+ # Test 1
185
+ # Split the user's input into a list of symptoms (assuming they are comma-separated) # yellow_crust_ooze,red_sore_around_nose,small_dents_in_nails,inflammatory_nails,blister
186
+ symptoms = input("Enter your symptoms.......")
187
+ user_symptoms = [s.strip() for s in symptoms.split(',')]
188
+ # Remove any extra characters, if any
189
+ user_symptoms = [symptom.strip("[]' ") for symptom in user_symptoms]
190
+ predicted_disease = get_predicted_value(user_symptoms)
191
+
192
+ desc, pre, med, die, wrkout = helper(predicted_disease)
193
+
194
+ print("=================predicted disease============")
195
+ print(predicted_disease)
196
+ print("=================description==================")
197
+ print(desc)
198
+ print("=================precautions==================")
199
+ i = 1
200
+ for p_i in pre[0]:
201
+ print(i, ": ", p_i)
202
+ i += 1
203
+
204
+ print("=================medications==================")
205
+ for m_i in med:
206
+ print(i, ": ", m_i)
207
+ i += 1
208
+
209
+ print("=================workout==================")
210
+ for w_i in wrkout:
211
+ print(i, ": ", w_i)
212
+ i += 1
213
+
214
+ print("=================diets==================")
215
+ for d_i in die:
216
+ print(i, ": ", d_i)
217
+ i += 1
218
+
219
+ # let's use pycharm flask app
220
+ # but install this version in pycharm
221
+ import sklearn
222
+ print(sklearn.__version__)
223
+