Shakirul360 commited on
Commit
37d9988
·
verified ·
1 Parent(s): 8fde1ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -175
app.py CHANGED
@@ -1,23 +1,21 @@
 
1
  #!pip install gradio pandas scikit-learn joblib
2
 
3
-
4
  import pandas as pd
5
- import numpy as np
6
- from sklearn.model_selection import train_test_split
7
- from sklearn.preprocessing import StandardScaler
8
- from sklearn.linear_model import LogisticRegression
9
- from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
10
- import gradio as gr
11
  import joblib
 
12
 
13
- # Load your dataset (assuming 'AIDA-PHQ-Updated.csv' is in the same directory as your script)
14
- df = pd.read_csv("AIDA-PHQ-Updated.csv")
 
15
 
16
- df.head()
 
17
 
18
- # Ordinal mappings (if not already applied)
 
19
  ordinal_mappings = {
20
- 'Not Applicable' : 0,
21
  'Strongly disagree': 1,
22
  'Disagree': 2,
23
  'Neutral': 3,
@@ -38,62 +36,22 @@ ordinal_columns = [
38
  'EmotionalViolenceExperience'
39
  ]
40
 
41
- for col in ordinal_columns:
42
- df[col] = df[col].map(ordinal_mappings)
43
-
44
- # Encode the Gender column
45
- from sklearn.preprocessing import LabelEncoder
46
- encoder = LabelEncoder()
47
- df['Gender'] = encoder.fit_transform(df['Gender'])
48
-
49
- df.head()
50
-
51
- # Split into X and y
52
- X = df.drop('DepressionLevel', axis=1)
53
- y = df['DepressionLevel']
54
-
55
- X.columns
56
-
57
- X.head()
58
 
59
- # Split into train and test sets
60
- random_state = 2024
61
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=random_state)
62
-
63
- # Standardize features
64
- scaler = StandardScaler()
65
- X_train_scaled = scaler.fit_transform(X_train)
66
- X_test_scaled = scaler.transform(X_test)
67
-
68
-
69
-
70
- # Train Logistic Regression model
71
- logreg = LogisticRegression(C=10.0, solver='newton-cg')
72
- logreg.fit(X_train_scaled, y_train)
73
-
74
-
75
- # Save the model as a .bin file
76
- with open('model.bin', 'wb') as file:
77
- joblib.dump(logreg, file)
78
-
79
- # Save the scaler as a .bin file
80
- with open('scaler.bin', 'wb') as file:
81
- joblib.dump(scaler, file)
82
-
83
- def predict_depression_level_logreg(age, gender, cgpa, poor_academic_performance,
84
- academic_criticism, unsatisfied_workload,
85
- non_interest_subject, unhappy_subject,
86
- non_interest_institution, unhappy_institution,
87
- parental_strictness, parental_academic_pressure,
88
- parental_marriage_pressure, parental_career_pressure,
89
- parental_study_abroad, parental_understanding,
90
- sibling_bonding, parental_relationship_stability,
91
- peer_relationship, teacher_support,
92
- partner_relationship_impact, physical_violence,
93
- sexual_violence, verbal_violence, emotional_violence,
94
- little_interest, feeling_down, sleeping_issue,
95
- feeling_tired, poor_appetite, feeling_bad,
96
- trouble_concentrating, slowness, self_harm):
97
 
98
  # Convert gender to numeric
99
  gender = 1 if gender == 'Female' else 0
@@ -127,18 +85,19 @@ def predict_depression_level_logreg(age, gender, cgpa, poor_academic_performance
127
  columns=feature_names)
128
 
129
  input_data_scaled = scaler.transform(input_data)
130
- prediction = logreg.predict(input_data_scaled)[0]
131
- return str(prediction)
132
 
133
 
134
- # Define Gradio interface with proper input labels and output type
135
  inputs = [
136
- gr.Slider(minimum=int(df['Age'].min()), maximum=int(df['Age'].max()), label="Age"),
137
  gr.Dropdown(choices=["Male", "Female"], label="Gender"),
138
- gr.Slider(minimum=float(df['CGPA'].min()), maximum=float(df['CGPA'].max()), label="CGPA")
139
  ]
140
 
141
 
 
142
  # Updated labels for ordinal columns
143
  ordinal_labels = {
144
  'PoorAcademicPerformanceSelfPerception': 'Your Academic Performance is poor.',
@@ -167,6 +126,7 @@ ordinal_labels = {
167
  'EmotionalViolenceExperience': 'You have experienced emotional violence.',
168
  }
169
 
 
170
  # Add radio buttons for ordinal columns with updated labels
171
  for col in ordinal_columns:
172
  inputs.append(gr.Radio(choices=list(ordinal_mappings.keys()), label=ordinal_labels[col]))
@@ -187,112 +147,12 @@ additional_inputs = [
187
 
188
  inputs.extend(additional_inputs)
189
 
190
- # # Sample input values (these should match the features and their order in your function)
191
- # sample_input = {
192
- # "Age": 25,
193
- # "Gender": "Female", # Assuming string value for Gender
194
- # "CGPA": 3.5,
195
- # "PoorAcademicPerformanceSelfPerception": "Disagree", # String value, needs mapping
196
- # "AcademicCriticismSelfPerception": "Neutral", # String value, needs mapping
197
- # "UnsatisfiedAcademicWorkloadSelfPerception": "Strongly disagree", # String value, needs mapping
198
- # "NonInterestSubjectOpinion": "Disagree", # String value, needs mapping
199
- # "UnhappySubjectOpinion": "Neutral", # String value, needs mapping
200
- # "NonInterestInstitutionOpinion": "Strongly disagree", # String value, needs mapping
201
- # "UnhappyInstitutionOpinion": "Disagree", # String value, needs mapping
202
- # "ParentalStrictness": "Strongly agree", # String value, needs mapping
203
- # "ParentalAcademicPressure": "Agree", # String value, needs mapping
204
- # "ParentalMarriagePressure": "Neutral", # String value, needs mapping
205
- # "ParentalCareerPressure": "Strongly disagree", # String value, needs mapping
206
- # "ParentalStudyAbroadPressure": "Neutral", # String value, needs mapping
207
- # "ParentalUnderstanding": "Strongly agree", # String value, needs mapping
208
- # "SiblingBonding": "Strongly agree", # String value, needs mapping
209
- # "ParentalRelationshipStability": "Neutral", # String value, needs mapping
210
- # "PeerRelationship": "Agree", # String value, needs mapping
211
- # "TeacherSupport": "Strongly agree", # String value, needs mapping
212
- # "PartnerRelationshipImpact": "Neutral", # String value, needs mapping
213
- # "PhysicalViolenceExperience": 0,
214
- # "SexualViolenceExperience": 1,
215
- # "VerbalViolenceExperience": 0,
216
- # "EmotionalViolenceExperience": 2,
217
- # "little interest": 1,
218
- # "feeling down": 3,
219
- # "Sleeping issue": 2,
220
- # "feeling tired": 4,
221
- # "poor appetite": 2,
222
- # "feeling bad": 3,
223
- # "trouble concertrating": 1,
224
- # "slowness": 2,
225
- # "self harm": 0
226
- # }
227
-
228
- # # Convert the sample input dictionary to a DataFrame
229
- # sample_df = pd.DataFrame([sample_input])
230
-
231
- # # Map ordinal columns to numerical values using ordinal_mappings
232
- # for col in ordinal_columns:
233
- # sample_df[col] = sample_df[col].map(ordinal_mappings)
234
-
235
- # # Convert gender to numeric
236
- # sample_df['Gender'] = 1 if sample_df['Gender'].iloc[0] == 'Female' else 0
237
-
238
- # # Scale the input data using the scaler from your model
239
- # sample_df_scaled = scaler.transform(sample_df)
240
-
241
- # # Predict using your function
242
- # prediction = predict_depression_level_logreg(*sample_df_scaled[0])
243
-
244
- # # Print or use the prediction as needed
245
- # print("Predicted Depression Level:", prediction)
246
-
247
 
248
  output = gr.Textbox(label="Predicted Depression Level")
249
 
 
250
  # Create Gradio interface
251
- iface = gr.Interface(fn=predict_depression_level_logreg, inputs=inputs, outputs=output, title="Understand your Depression Levels",
252
  description="A questionnaire to determine potential depression severity using the questions below - ")
253
 
254
- iface.launch(debug=True, share=True)
255
-
256
- # #importing libraries
257
- # import numpy as np
258
- # import lime
259
- # # import lime.lime_tabular
260
- # from lime import lime_tabular
261
-
262
- # # Training Logistic Regression classifier
263
- # model = LogisticRegression()
264
- # model.fit(X_train, y_train)
265
-
266
- # # Defining the lime explainer
267
- # explainer = lime_tabular.LimeTabularExplainer(
268
- # training_data=np.array(X_train),
269
- # feature_names=X_train.columns,
270
- # class_names=['MINIMAL','MILD','Moderate','ModeratelySevere','Severe'],
271
- # mode='classification'
272
- # )
273
-
274
- # #importing libraries
275
- # import numpy as np
276
- # import lime
277
- # # import lime.lime_tabular
278
- # from lime import lime_tabular
279
-
280
- # # Training Logistic Regression classifier
281
- # model = LogisticRegression()
282
- # model.fit(X_train, y_train)
283
-
284
- # # Defining the lime explainer
285
- # explainer = lime_tabular.LimeTabularExplainer(
286
- # training_data=np.array(X_train),
287
- # feature_names=X_train.columns,
288
- # class_names=['MINIMAL','MILD','Moderate','ModeratelySevere','Severe'],
289
- # mode='classification'
290
- # )
291
-
292
- # exp = explainer.explain_instance(
293
- # data_row=X_test.iloc[5],
294
- # predict_fn=model.predict_proba, num_features = 12
295
- # )
296
-
297
- # exp.show_in_notebook(show_table=True)
298
-
 
1
+ # Install necessary libraries
2
  #!pip install gradio pandas scikit-learn joblib
3
 
 
4
  import pandas as pd
 
 
 
 
 
 
5
  import joblib
6
+ import gradio as gr
7
 
8
+ # Load the model and scaler from the binary files
9
+ with open('model.bin', 'rb') as file:
10
+ model = joblib.load(file)
11
 
12
+ with open('scaler.bin', 'rb') as file:
13
+ scaler = joblib.load(file)
14
 
15
+
16
+ # Define ordinal mappings and columns
17
  ordinal_mappings = {
18
+ 'Not Applicable': 0,
19
  'Strongly disagree': 1,
20
  'Disagree': 2,
21
  'Neutral': 3,
 
36
  'EmotionalViolenceExperience'
37
  ]
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ # Define the prediction function
41
+ def predict_depression_level(age, gender, cgpa, poor_academic_performance,
42
+ academic_criticism, unsatisfied_workload,
43
+ non_interest_subject, unhappy_subject,
44
+ non_interest_institution, unhappy_institution,
45
+ parental_strictness, parental_academic_pressure,
46
+ parental_marriage_pressure, parental_career_pressure,
47
+ parental_study_abroad, parental_understanding,
48
+ sibling_bonding, parental_relationship_stability,
49
+ peer_relationship, teacher_support,
50
+ partner_relationship_impact, physical_violence,
51
+ sexual_violence, verbal_violence, emotional_violence,
52
+ little_interest, feeling_down, sleeping_issue,
53
+ feeling_tired, poor_appetite, feeling_bad,
54
+ trouble_concentrating, slowness, self_harm):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  # Convert gender to numeric
57
  gender = 1 if gender == 'Female' else 0
 
85
  columns=feature_names)
86
 
87
  input_data_scaled = scaler.transform(input_data)
88
+ prediction = model.predict(input_data_scaled)[0]
89
+ return "Your depression severity may be " + str(prediction)
90
 
91
 
92
+ # Define Gradio interface inputs
93
  inputs = [
94
+ gr.Slider(minimum=0, maximum=100, label="Age"),
95
  gr.Dropdown(choices=["Male", "Female"], label="Gender"),
96
+ gr.Slider(minimum=0.0, maximum=4.0, label="CGPA")
97
  ]
98
 
99
 
100
+
101
  # Updated labels for ordinal columns
102
  ordinal_labels = {
103
  'PoorAcademicPerformanceSelfPerception': 'Your Academic Performance is poor.',
 
126
  'EmotionalViolenceExperience': 'You have experienced emotional violence.',
127
  }
128
 
129
+
130
  # Add radio buttons for ordinal columns with updated labels
131
  for col in ordinal_columns:
132
  inputs.append(gr.Radio(choices=list(ordinal_mappings.keys()), label=ordinal_labels[col]))
 
147
 
148
  inputs.extend(additional_inputs)
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
  output = gr.Textbox(label="Predicted Depression Level")
152
 
153
+
154
  # Create Gradio interface
155
+ iface = gr.Interface(fn=predict_depression_level, inputs=inputs, outputs=output, title="Understand your Depression Levels",
156
  description="A questionnaire to determine potential depression severity using the questions below - ")
157
 
158
+ iface.launch(debug=True, share=True)