montebello-642 commited on
Commit
6b4216c
·
verified ·
1 Parent(s): 29b2d73

Upload Logistic Regression.ipynb

Browse files
Files changed (1) hide show
  1. Logistic Regression.ipynb +264 -0
Logistic Regression.ipynb ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {
7
+ "collapsed": true
8
+ },
9
+ "outputs": [
10
+ {
11
+ "name": "stdout",
12
+ "output_type": "stream",
13
+ "text": [
14
+ "Index(['duration_mo', 'mos_ethnicity', 'complainant_ethnicity', 'is_force',\n",
15
+ " 'is_abuse_of_authority', 'is_discourtesy', 'is_offensive_language',\n",
16
+ " 'outcome_description'],\n",
17
+ " dtype='object')\n",
18
+ " duration_mo mos_ethnicity complainant_ethnicity is_force \\\n",
19
+ "0 10 0 2 0 \n",
20
+ "1 9 1 2 0 \n",
21
+ "2 9 1 2 1 \n",
22
+ "3 14 1 2 0 \n",
23
+ "4 6 0 7 0 \n",
24
+ "\n",
25
+ " is_abuse_of_authority is_discourtesy is_offensive_language \\\n",
26
+ "0 1 0 0 \n",
27
+ "1 0 1 0 \n",
28
+ "2 0 0 0 \n",
29
+ "3 1 0 0 \n",
30
+ "4 0 0 1 \n",
31
+ "\n",
32
+ " outcome_description \n",
33
+ "0 0 \n",
34
+ "1 0 \n",
35
+ "2 0 \n",
36
+ "3 0 \n",
37
+ "4 1 \n",
38
+ " duration_mo mos_ethnicity complainant_ethnicity is_force \\\n",
39
+ "count 33358.000000 33358.000000 33358.000000 33358.000000 \n",
40
+ "mean 9.733767 0.946819 2.468283 0.022573 \n",
41
+ "std 5.017703 0.754311 2.256281 0.148541 \n",
42
+ "min 0.000000 0.000000 0.000000 0.000000 \n",
43
+ "25% 6.000000 0.000000 1.000000 0.000000 \n",
44
+ "50% 10.000000 1.000000 2.000000 0.000000 \n",
45
+ "75% 13.000000 1.000000 2.000000 0.000000 \n",
46
+ "max 110.000000 4.000000 7.000000 1.000000 \n",
47
+ "\n",
48
+ " is_abuse_of_authority is_discourtesy is_offensive_language \\\n",
49
+ "count 33358.000000 33358.000000 33358.000000 \n",
50
+ "mean 0.608310 0.140206 0.228911 \n",
51
+ "std 0.488135 0.347206 0.420138 \n",
52
+ "min 0.000000 0.000000 0.000000 \n",
53
+ "25% 0.000000 0.000000 0.000000 \n",
54
+ "50% 1.000000 0.000000 0.000000 \n",
55
+ "75% 1.000000 0.000000 0.000000 \n",
56
+ "max 1.000000 1.000000 1.000000 \n",
57
+ "\n",
58
+ " outcome_description \n",
59
+ "count 33358.000000 \n",
60
+ "mean 0.438066 \n",
61
+ "std 0.496157 \n",
62
+ "min 0.000000 \n",
63
+ "25% 0.000000 \n",
64
+ "50% 0.000000 \n",
65
+ "75% 1.000000 \n",
66
+ "max 1.000000 \n",
67
+ "duration_mo 0\n",
68
+ "mos_ethnicity 0\n",
69
+ "complainant_ethnicity 0\n",
70
+ "is_force 0\n",
71
+ "is_abuse_of_authority 0\n",
72
+ "is_discourtesy 0\n",
73
+ "is_offensive_language 0\n",
74
+ "outcome_description 0\n",
75
+ "dtype: int64\n",
76
+ "Accuracy: 0.65\n",
77
+ " precision recall f1-score support\n",
78
+ "\n",
79
+ " 0 0.65 0.82 0.72 3778\n",
80
+ " 1 0.64 0.42 0.51 2894\n",
81
+ "\n",
82
+ " accuracy 0.65 6672\n",
83
+ " macro avg 0.64 0.62 0.62 6672\n",
84
+ "weighted avg 0.64 0.65 0.63 6672\n",
85
+ "\n",
86
+ "Running on local URL: http://127.0.0.1:7860\n",
87
+ "Running on public URL: https://d8846d114093b0894a.gradio.live\n",
88
+ "\n",
89
+ "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n"
90
+ ]
91
+ },
92
+ {
93
+ "data": {
94
+ "text/plain": "<IPython.core.display.HTML object>",
95
+ "text/html": "<div><iframe src=\"https://d8846d114093b0894a.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
96
+ },
97
+ "metadata": {},
98
+ "output_type": "display_data"
99
+ },
100
+ {
101
+ "data": {
102
+ "text/plain": ""
103
+ },
104
+ "execution_count": 1,
105
+ "metadata": {},
106
+ "output_type": "execute_result"
107
+ }
108
+ ],
109
+ "source": [
110
+ "import pandas as pd\n",
111
+ "from sklearn.model_selection import train_test_split, cross_val_score\n",
112
+ "from sklearn.preprocessing import StandardScaler\n",
113
+ "from sklearn.linear_model import LogisticRegression\n",
114
+ "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
115
+ "import seaborn as sns\n",
116
+ "import matplotlib.pyplot as plt\n",
117
+ "import gradio as gr\n",
118
+ "import numpy as np\n",
119
+ "\n",
120
+ "#loading the dataset and select only the columns needed\n",
121
+ "selected_columns = ['duration_mo', 'mos_ethnicity', 'complainant_ethnicity', 'is_force', 'is_abuse_of_authority', 'is_discourtesy', 'is_offensive_language', 'outcome_description']\n",
122
+ "df = pd.read_csv('my_dataset_logistic.csv', usecols=selected_columns)\n",
123
+ "\n",
124
+ "print(df.columns)\n",
125
+ "print(df.head())\n",
126
+ "print(df.describe())\n",
127
+ "print(df.isnull().sum())\n",
128
+ "\n",
129
+ "#set the name of the column to calculate accuracy\n",
130
+ "X = df.drop('outcome_description', axis=1)\n",
131
+ "y = df['outcome_description']\n",
132
+ "X.fillna(0, inplace=True)\n",
133
+ "\n",
134
+ "#split into training and test set\n",
135
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
136
+ "\n",
137
+ "#standardize the features\n",
138
+ "scaler = StandardScaler()\n",
139
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
140
+ "X_test_scaled = scaler.transform(X_test)\n",
141
+ "\n",
142
+ "#train the model\n",
143
+ "model = LogisticRegression(random_state=42)\n",
144
+ "model.fit(X_train_scaled, y_train)\n",
145
+ "\n",
146
+ "#make predictions and evaluate the model\n",
147
+ "y_pred = model.predict(X_test_scaled)\n",
148
+ "accuracy = accuracy_score(y_test, y_pred)\n",
149
+ "print(f'Accuracy: {accuracy:.2f}')\n",
150
+ "\n",
151
+ "#classification report with confusion matrix, correlation graph and standard deviation of all the variables\n",
152
+ "print(classification_report(y_test, y_pred))\n",
153
+ "\n",
154
+ "# Confusion Matrix\n",
155
+ "conf_matrix = confusion_matrix(y_test, y_pred)\n",
156
+ "plt.figure(figsize=(8, 6))\n",
157
+ "sns.heatmap(conf_matrix, annot=True, fmt=\"d\", cmap=\"Blues\", cbar=False,xticklabels=df['outcome_description'].unique(), yticklabels=df['outcome_description'].unique())\n",
158
+ "plt.title(\"Confusion Matrix\")\n",
159
+ "plt.xlabel(\"Predicted\")\n",
160
+ "plt.ylabel(\"Actual\")\n",
161
+ "plt.show()\n",
162
+ "\n",
163
+ "#Correlation Matrix\n",
164
+ "correlation_matrix = df.corr()\n",
165
+ "plt.figure(figsize=(10, 8))\n",
166
+ "sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt=\".2f\", linewidths=.5)\n",
167
+ "plt.title('Correlation Matrix')\n",
168
+ "plt.show()\n",
169
+ "\n",
170
+ "#plotting a bar chart to visualize better the correlation\n",
171
+ "target_correlations = correlation_matrix['outcome_description'].sort_values(ascending=False)\n",
172
+ "plt.figure(figsize=(10, 6))\n",
173
+ "target_correlations.drop('outcome_description').plot(kind='bar', color='blue')\n",
174
+ "plt.title('Correlations with Target Variable')\n",
175
+ "plt.xlabel('Features')\n",
176
+ "plt.ylabel('Correlation')\n",
177
+ "plt.show()\n",
178
+ "\n",
179
+ "#Standard Deviation\n",
180
+ "std_dev = df.std()\n",
181
+ "print('\\nStandard deviation')\n",
182
+ "print(std_dev)\n",
183
+ "\n",
184
+ "#gradio implementation\n",
185
+ "#create the available options for the ethnicities\n",
186
+ "mos_ethnicity_options = [\"Hispanic\", \"White\", \"Black\", \"Asian\", \"American Indian\", \"Other Race\", \"Refused\", \"Unknown\"]\n",
187
+ "complainant_ethnicity_options = [\"Hispanic\", \"White\", \"Black\", \"Asian\", \"American Indian\", \"Other Race\", \"Refused\", \"Unknown\"]\n",
188
+ "\n",
189
+ "#defining the function to make predictions using the model\n",
190
+ "def predict_outcome_duration(mos_ethnicity, complainant_ethnicity, is_force, is_abuse_of_authority, is_discourtesy, is_offensive_language, duration_mo):\n",
191
+ " try:\n",
192
+ " #converting values from string to int\n",
193
+ " mos_ethnicity_encoded = mos_ethnicity_options.index(mos_ethnicity)\n",
194
+ " complainant_ethnicity_encoded = complainant_ethnicity_options.index(complainant_ethnicity)\n",
195
+ "\n",
196
+ " #converting checkbox value to int\n",
197
+ " is_force = int(is_force)\n",
198
+ " is_abuse_of_authority = int(is_abuse_of_authority)\n",
199
+ " is_discourtesy = int(is_discourtesy)\n",
200
+ " is_offensive_language = int(is_offensive_language)\n",
201
+ "\n",
202
+ " input_data = [[duration_mo, mos_ethnicity_encoded, complainant_ethnicity_encoded, is_force, is_abuse_of_authority, is_discourtesy, is_offensive_language]]\n",
203
+ " input_scaled = scaler.transform(input_data)\n",
204
+ " prediction = model.predict(input_scaled)[0]\n",
205
+ "\n",
206
+ " #outputting the result\n",
207
+ " return \"Arrest\" if prediction == 1 else \"No Arrest\"\n",
208
+ "\n",
209
+ " except Exception as e:\n",
210
+ " return f\"Error: {str(e)}\"\n",
211
+ "\n",
212
+ "#creating the gradio interface, using dropdowns to show the different ethnicities, checkbox to identify which type of allegation it was and a slider with the duration in months\n",
213
+ "mos_ethnicity_dropdown = gr.Dropdown(choices=mos_ethnicity_options,label=\"Defendant Ethnicity\")\n",
214
+ "complainant_ethnicity_dropdown = gr.Dropdown(choices=complainant_ethnicity_options, label=\"Complainant Ethnicity\")\n",
215
+ "is_force_checkbox = gr.Checkbox()\n",
216
+ "is_abuse_of_authority_checkbox = gr.Checkbox()\n",
217
+ "is_discourtesy_checkbox = gr.Checkbox()\n",
218
+ "is_offensive_language_checkbox = gr.Checkbox()\n",
219
+ "duration_mo_slider = gr.Slider(minimum=0, maximum=20, label=\"Duration in months\")\n",
220
+ "\n",
221
+ "iface = gr.Interface(\n",
222
+ " fn=predict_outcome_duration,\n",
223
+ " inputs=[complainant_ethnicity_dropdown, mos_ethnicity_dropdown, is_force_checkbox, is_abuse_of_authority_checkbox, is_discourtesy_checkbox, is_offensive_language_checkbox, duration_mo_slider],\n",
224
+ " outputs=\"text\",\n",
225
+ " live=True,\n",
226
+ " title=\"Complaint Outcome Prediction\"\n",
227
+ ")\n",
228
+ "\n",
229
+ "# Launch the Gradio Interface\n",
230
+ "iface.launch(share=True)"
231
+ ]
232
+ },
233
+ {
234
+ "cell_type": "code",
235
+ "execution_count": null,
236
+ "outputs": [],
237
+ "source": [],
238
+ "metadata": {
239
+ "collapsed": false
240
+ }
241
+ }
242
+ ],
243
+ "metadata": {
244
+ "kernelspec": {
245
+ "display_name": "Python 3",
246
+ "language": "python",
247
+ "name": "python3"
248
+ },
249
+ "language_info": {
250
+ "codemirror_mode": {
251
+ "name": "ipython",
252
+ "version": 2
253
+ },
254
+ "file_extension": ".py",
255
+ "mimetype": "text/x-python",
256
+ "name": "python",
257
+ "nbconvert_exporter": "python",
258
+ "pygments_lexer": "ipython2",
259
+ "version": "2.7.6"
260
+ }
261
+ },
262
+ "nbformat": 4,
263
+ "nbformat_minor": 0
264
+ }