-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
1918 lines (1478 loc) · 70 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Required Dependencies
from flask import Flask, render_template, request, redirect, url_for, jsonify, send_file
import pandas as pd
import numpy as np
import matplotlib
import seaborn as sns
import io
import warnings
warnings.filterwarnings("ignore")
# Extreme Gradient booost
import xgboost as xbs
# Classification Models
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
# Regression Models
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.neighbors import KNeighborsRegressor
matplotlib.use('Agg')
plt=matplotlib.pyplot
# This is our main python file that will run the flask app
app = Flask(__name__)
# To scale down training data
def scale_down(X_train, X_test):
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
X_train=scaler.fit_transform(X_train)
X_test=scaler.transform(X_test)
return X_train, X_test
# To check accuracy of the regression models
def check_r2_score(y_test, y_pred):
from sklearn.metrics import r2_score
score = r2_score(y_test, y_pred)
return score
# To check accuracy of classification models
def check_accuracy(y_test, y_pred):
from sklearn.metrics import accuracy_score
score = accuracy_score(y_test, y_pred)
return score
# Linear Regression
def linear_regression(X_train,y_train):
from sklearn.linear_model import LinearRegression
linear_regressor=LinearRegression()
linear_regressor.fit(X_train,y_train)
return linear_regressor
# Ridge Regression (L2 Regularization)
def ridge_regression(X_train,y_train):
from sklearn.linear_model import Ridge
ridge_regressor=Ridge()
ridge_regressor.fit(X_train,y_train)
return ridge_regressor
# Lasso Regression (L1 Regularization)
def lasso_regression(X_train,y_train):
from sklearn.linear_model import Lasso
lasso_regressor=Lasso()
lasso_regressor.fit(X_train,y_train)
return lasso_regressor
# Elastic NET Regression (L1 + L2 Regularization)
def elastic_net_regression(X_train,y_train):
from sklearn.linear_model import ElasticNet
elastic_net_regressor=ElasticNet()
elastic_net_regressor.fit(X_train,y_train)
return elastic_net_regressor
# Decision Tree Regression
def decision_tree_regression(X_train,y_train):
from sklearn.tree import DecisionTreeRegressor
tree=DecisionTreeRegressor(random_state=42)
tree.fit(X_train,y_train)
return tree
# Decision Tree Classification
def decision_tree_classification(X_train,y_train):
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(random_state=42)
tree.fit(X_train,y_train)
return tree
# Extra Tree Regression
def extra_tree_regression(X_train,y_train):
from sklearn.tree import ExtraTreeRegressor
trees=ExtraTreeRegressor(random_state=42)
trees.fit(X_train,y_train)
return trees
# Extra Tree Classification
def extra_tree_classification(X_train,y_train):
from sklearn.tree import ExtraTreeClassifier
trees=ExtraTreeClassifier(random_state=42)
trees.fit(X_train,y_train)
return trees
# Logistic Regression
def logistic_regression(X_train,y_train,types, random_state, max_iter, multiclass, bias, solver):
if bias == "None":
bias = None
if types=="Binary":
from sklearn.linear_model import LogisticRegression
log_reg=LogisticRegression(random_state=random_state, max_iter=max_iter, penalty=bias, solver=solver)
log_reg.fit(X_train,y_train)
return log_reg
if types=="MultiClass":
from sklearn.linear_model import LogisticRegression
log_reg=LogisticRegression(random_state=random_state, max_iter=max_iter, multi_class=multiclass, penalty=bias, solver=solver)
log_reg.fit(X_train,y_train)
return log_reg
#Naive Bias Classifier
def naive_bayes_classifier(X_train,y_train,types):
if types=="Gaussian":
from sklearn.naive_bayes import GaussianNB
naive=GaussianNB()
naive.fit(X_train,y_train)
return naive
if types=="Multinomial":
from sklearn.naive_bayes import MultinomialNB
naive=MultinomialNB()
naive.fit(X_train,y_train)
return naive
if types=="Bernoulli":
from sklearn.naive_bayes import BernoulliNB
naive=BernoulliNB()
naive.fit(X_train,y_train)
return naive
if types=="Complement":
from sklearn.naive_bayes import ComplementNB
naive=ComplementNB()
naive.fit(X_train,y_train)
return naive
if types=="Categorical":
from sklearn.naive_bayes import CategoricalNB
naive=CategoricalNB()
naive.fit(X_train,y_train)
return naive
#Support Vector Classification
def support_vector_classification(X_train,y_train,random_state,max_iter,kernel,parameter,gamma):
from sklearn.svm import SVC
svc = SVC(kernel=kernel, C=parameter, gamma=gamma, random_state=random_state, max_iter=max_iter)
svc.fit(X_train,y_train)
return svc
#Support Vector Regression
def support_vector_regression(X_train,y_train,epsilon,max_iter,kernel,parameter,gamma):
from sklearn.svm import SVR
svr = SVR(kernel=kernel,epsilon=epsilon, C=parameter, gamma=gamma, max_iter=max_iter)
svr.fit(X_train,y_train)
return svr
# Random Forest Classification
def random_forest_classification(X_train,y_train,n_estimators,max_depth,max_features,criterion,bootstrap,oob_score):
if max_depth == "None":
max_depth = None
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth, max_features=max_features, criterion=criterion, bootstrap=bootstrap, oob_score=oob_score)
forest.fit(X_train,y_train)
return forest
# Random Forest Regression
def random_forest_regression(X_train,y_train,n_estimators,max_depth,max_features,criterion,bootstrap,oob_score):
if max_depth == "None":
max_depth = None
from sklearn.ensemble import RandomForestRegressor
forest = RandomForestRegressor(n_estimators=n_estimators, max_depth=max_depth, max_features=max_features, criterion=criterion, bootstrap=bootstrap, oob_score=oob_score)
forest.fit(X_train,y_train)
return forest
# Adaboost Classification
def adaboost_classification(X_train,y_train,n_estimators,learning_rate,algorithm):
from sklearn.ensemble import AdaBoostClassifier
adaboost = AdaBoostClassifier(n_estimators=n_estimators, learning_rate=learning_rate, algorithm=algorithm)
adaboost.fit(X_train,y_train)
return adaboost
# Gradient Boost Classification
def gradientboost_classification(X_train,y_train,n_estimators,learning_rate,max_depth,criterion):
from sklearn.ensemble import GradientBoostingClassifier
gradient_boost = GradientBoostingClassifier(n_estimators=n_estimators, learning_rate=learning_rate, max_depth=max_depth,criterion=criterion)
gradient_boost.fit(X_train,y_train)
return gradient_boost
# Adaboost Regression
def adaboost_regression(X_train,y_train,n_estimators,learning_rate,loss):
from sklearn.ensemble import AdaBoostRegressor
adaboost = AdaBoostRegressor(n_estimators=n_estimators, learning_rate=learning_rate, loss=loss)
adaboost.fit(X_train,y_train)
return adaboost
# Gradient Boost Regressor
def gradient_boost_regression(X_train,y_train,n_estimators, learning_rate, loss, criterion, max_depth, max_features):
from sklearn.ensemble import GradientBoostingRegressor
gradient_boost = GradientBoostingRegressor(n_estimators=n_estimators, learning_rate=learning_rate, loss=loss, criterion=criterion, max_depth=max_depth, max_features=max_features)
gradient_boost.fit(X_train,y_train)
return gradient_boost
# XGBoost Regressor
def xgboost_regression(X_train,y_train):
xgb_reg=xbs.XGBRegressor()
xgb_reg.fit(X_train,y_train)
return xgb_reg
# KNN Classifier
def knn_classification(X_train,y_train,n_neighbors,weights,algorithm,leaf_size,p):
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=n_neighbors, weights=weights, algorithm=algorithm, leaf_size=leaf_size, p=p)
knn.fit(X_train,y_train)
return knn
# KNN Regressor
def knn_regression(X_train,y_train,n_neighbors,weights,algorithm,leaf_size,p):
from sklearn.neighbors import KNeighborsRegressor
knn = KNeighborsRegressor(n_neighbors=n_neighbors, weights=weights, algorithm=algorithm, leaf_size=leaf_size, p=p)
knn.fit(X_train,y_train)
return knn
#Home Page
@app.route("/")
def home():
return render_template("index.html")
#Introduction Page
@app.route("/introduction")
def introduction():
return render_template("intro.html")
#Upload Page
@app.route("/upload")
def upload():
return render_template("upload copy.html")
#Receiving the dataset here
@app.route("/upload2", methods=['POST'])
def upload_dataset():
global df
if request.method == "POST":
file = request.files["file"]
if file:
df = pd.read_csv(file)
return redirect(url_for("main_page"))
#Start
@app.route("/main_page", methods=["GET","POST"])
def main_page():
return render_template("slot2intro.html")
#Show Dataset
@app.route("/show")
def show():
return render_template("dataset.html", dataset = df.to_html())
#Insights1
@app.route("/insights1")
def insights1():
#column names
cols = list(df.columns)
# Row 1:- no. of missing values
misses = df.isnull().sum()
# Row 2:- no. of present values
present = list(df.count())
# Row 3:- type of data
dtypes = list(df.dtypes.astype("str"))
# Row 4:- no. of unique values
unique = list(df.nunique())
row1 = pd.DataFrame([present], columns=cols)
row2 = pd.DataFrame([misses], columns=cols)
row3 = pd.DataFrame([dtypes], columns=cols)
row4 = pd.DataFrame([unique], columns=cols)
df_req = pd.concat([row1, row2, row3,row4], keys = ["No. of Values","Missing Values","Data Type","Unique Values"])
df_req = df_req.droplevel(1)
return render_template("insights1.html", dataset = df_req.to_html())
#insights2
@app.route("/insights2")
def insights2():
global df_req
cols = list(df.columns)
num = df.select_dtypes(include=["int64","float64"])
if num.empty:
return render_template("insights1.html", dataset = "No Numerical Features Found");
# Row 1:- minimum values
rep = "NC"
min_val = list(df.min())
min_val = [rep if type(x) == str else x for x in min_val]
# Row 2:- maximum values
max_val = list(df.max())
max_val = [rep if type(x) == str else x for x in max_val]
# Calculation for further steps
df_copy = df.copy()
array = []
a = list(df.dtypes.astype("str"))
c = list(df.columns)
for i in range(len(a)):
if a[i] == "object":
change = c[i]
array.append(i)
df_copy[change] = -1
# Row 3:- Difference in min and max values
diff = df_copy.max() - df_copy.min()
# Row 4:- Mean of the values
mean = df_copy.mean()
# Row 5:- Median of the values
median = df_copy.median()
# Row 6:- Mean/Median difference
diff2 = list(np.array(mean) - np.array(median))
# Row 7:- Standard Deviation of the values
std = df_copy.std()
row1 = pd.DataFrame([min_val], columns=cols)
row2 = pd.DataFrame([max_val], columns=cols)
row3 = pd.DataFrame([diff], columns=cols)
row4 = pd.DataFrame([mean], columns=cols)
row5 = pd.DataFrame([median], columns=cols)
row6 = pd.DataFrame([diff2], columns=cols)
row7 = pd.DataFrame([std], columns=cols)
df_req = pd.concat([row1, row2, row3,row4, row5, row6, row7], keys = ["Minimum","Maximum","Difference","Mean","Median","Mean-Median Difference","Standard Deviation"])
df_req = df_req.droplevel(1)
for i in range(len(array)):
index = array[i]
change = c[index]
df_req[change] = "NC"
# this code will fail if all are categorical
return render_template("insights2.html", dataset = df_req.to_html())
#round to 2 decimal
@app.route("/round2")
def round2():
return render_template("insights2.html", dataset = df_req.round(2).to_html())
#round to 3 decimal
@app.route("/round3")
def round3():
return render_template("insights2.html", dataset = df_req.round(3).to_html())
#Categorical Analysis
@app.route("/category")
def category():
categorical_features = df.select_dtypes(include=["object"])
if categorical_features.empty:
return render_template("category.html", dataset = "No Categorical Features")
arr = categorical_features.columns.tolist()
return render_template("category.html", dataset = categorical_features.describe().to_html(), columns = arr)
#Visualization-I
@app.route("/visual1", methods = ["GET", "POST"])
def visual1():
num = df.select_dtypes(include=["int64","float64"])
if num.empty:
return render_template("visualization1.html", message1 = "No Numerical Features Found")
plt.figure(figsize=(12,12))
sns.heatmap(num.corr().round(2), annot=True, cmap="rainbow")
plt.savefig("static/images/visual1/heatmap.png", bbox_inches = 'tight')
plt.clf()
sns.histplot(data=df,x=df.columns[-1], bins = 60, color = "r")
plt.savefig("static/images/visual1/hist.png", bbox_inches = 'tight')
# for histograms
columns = list(num.columns)
return render_template("visualization1.html", graph1_url = "static/images/visual1/heatmap.png", message1 = "Correlation Heatmap", graph2_url = "static/images/visual1/hist.png", message2 = "Histogram of the Target Variable",columns=columns)
# Histogram Generator
@app.route("/histograms", methods = ["GET", "POST"])
def histograms():
arr = request.form.getlist('columns')
arr = [i.replace(","," ") for i in arr]
if(len(arr) > 9):
return render_template("visualization2.html", message = "Select maximum 9 features")
if len(arr) != 0:
sns.set_style("darkgrid")
if(len(arr) == 1):
plt.figure(figsize=(12,12))
sns.histplot(x = df[arr[0]], bins = 30, kde = True, color = "r")
elif(len(arr) == 2):
fig, axes = plt.subplots(nrows = 1, ncols = 2, figsize = (15,10))
for i in range(len(arr)):
if (i == 0):
sns.histplot(x = df[arr[0]], ax = axes[0], bins = 30, kde = True, color = "r")
if (i == 1):
sns.histplot(x = df[arr[1]], ax = axes[1], bins = 30, kde = True, color = "b")
elif(len(arr) > 2 and len(arr) < 5):
fig, axes = plt.subplots(nrows = 2, ncols = 2, figsize = (15,15))
for i in range(len(arr)):
if (i == 0):
sns.histplot(x = df[arr[0]], ax = axes[0, 0], bins = 30, kde = True, color = "r")
if (i == 1):
sns.histplot(x = df[arr[1]], ax = axes[0, 1], bins = 30, kde = True, color = "b")
if (i == 2):
sns.histplot(x = df[arr[2]], ax = axes[1, 0], bins = 30, kde = True, color = "b")
if (i == 3):
sns.histplot(x = df[arr[3]], ax = axes[1, 1], bins = 30, kde = True, color = "black")
elif(len(arr) == 6):
fig, axes = plt.subplots(nrows = 2, ncols = 3, figsize = (15,10))
for i in range(len(arr)):
if (i == 0):
sns.histplot(x = df[arr[0]], ax = axes[0, 0], bins = 30, kde = True, color = "r")
if (i == 1):
sns.histplot(x = df[arr[1]], ax = axes[0, 1], bins = 30, kde = True, color = "b")
if (i == 2):
sns.histplot(x = df[arr[2]], ax = axes[0, 2], bins = 30, kde = True, color = "black")
if (i == 3):
sns.histplot(x = df[arr[3]], ax = axes[1, 0], bins = 30, kde = True, color = "b")
if (i == 4):
sns.histplot(x = df[arr[4]], ax = axes[1, 1], bins = 30, kde = True, color = "r")
if (i == 5):
sns.histplot(x = df[arr[5]], ax = axes[1, 2], bins = 30, kde = True, color = "g")
else:
fig, axes = plt.subplots(nrows = 3, ncols = 3, figsize = (15,15))
for i in range(len(arr)):
if (i == 0):
sns.histplot(x = df[arr[0]], ax = axes[0, 0], bins = 30, kde = True, color = "r")
if (i == 1):
sns.histplot(x = df[arr[1]], ax = axes[0, 1], bins = 30, kde = True, color = "b")
if (i == 2):
sns.histplot(x = df[arr[2]], ax = axes[0, 2], bins = 30, kde = True, color = "black")
if (i == 3):
sns.histplot(x = df[arr[3]], ax = axes[1, 0], bins = 30, kde = True, color = "b")
if (i == 4):
sns.histplot(x = df[arr[4]], ax = axes[1, 1], bins = 30, kde = True, color = "r")
if (i == 5):
sns.histplot(x = df[arr[5]], ax = axes[1, 2], bins = 30, kde = True, color = "g")
if (i == 6):
sns.histplot(x = df[arr[6]], ax = axes[2, 0], bins = 30, kde = True, color = "black")
if (i == 7):
sns.histplot(x = df[arr[7]], ax = axes[2, 1], bins = 30, kde = True, color = "g")
if (i == 8):
sns.histplot(x = df[arr[8]], ax = axes[2, 2], bins = 30, kde = True, color = "r")
plt.savefig("static/images/visual1.1/histograms.png", bbox_inches = 'tight')
return render_template("visualization2.html", graph3_url = "static/images/visual1.1/histograms.png", message = "Histograms of the Selected Features")
else:
return render_template("visualization2.html", message = "Please select atleast one feature")
# Missing Value Analysis
@app.route("/phase2")
def phase2():
global null_df_copy,y
null_df = pd.DataFrame(df.isnull().sum().astype(int), columns = ["Null Count"])
if (null_df["Null Count"].sum() == 0):
return render_template("missvalue.html", dataset = "No Missing Values Found")
null_df=null_df[null_df["Null Count"] != 0]
null_df["Null Percentage"] = (null_df["Null Count"] / len(df)) * 100
null_df["Null Percentage"] = null_df["Null Percentage"].round(2)
plt.clf()
null_df["Null Count"].plot(kind="bar", title = "Bar Plot",
ylabel="Miss Value Count", color = "b")
plt.savefig("static/images/miss/miss_bar.png", bbox_inches ="tight")
plt.clf()
null_df_copy = null_df.copy()
null_df = null_df.sort_values("Null Count", ascending = False)
message = "Your dataset has " + str(len(null_df)) + " features with missing values out of " + str(len(df.columns)) + " features."
null_df.loc["Total"] = null_df.sum()
# Imputation Technique through median of feature having no missing values and only few unique values
feat_list = df.nunique().to_list()
feat_list_idx = []
for i in range(len(feat_list)):
if(feat_list[i] > 1 and feat_list[i] < 15):
feat_list_idx.append(i)
feat_list = [df.columns.to_list()[i] for i in feat_list_idx] # Feature list having less unique values
flag = False
feat = []
for i in range(len(feat_list)):
if df[null_df.T.columns.to_list()[i]].dtype == "object":
flag = True
feat.append(null_df.T.columns.to_list()[i])
for i in feat:
feat_list.remove(i)
temp=null_df_copy.T.columns.to_list()
y=[]
for i in df.select_dtypes(include=["object"]).columns.to_list():
if i in temp:
y.append(i)
return render_template("missvalue.html", dataset = null_df.to_html(), message = message, bar_url = "static/images/miss/miss_bar.png", features = feat_list)
# Detecting Outliers Through Boxplots
@app.route("/boxplots", methods = ["POST"])
def boxplots():
global select_list,x
select_list = request.form.getlist("columns") # Feature list selected by user
select_list = [i.replace(","," ") for i in select_list]
if(len(select_list) != 1):
return render_template("missvalue2.html", message="Please select exactly one feature")
x=df.isnull().sum().to_list()
count=0
for i in range(len(x)):
if(x[i]==0):
count += 1
x=null_df_copy.index.to_list()
for i in range(len(x)):
plt.figure(figsize=(15,10))
sns.boxplot(x=df[select_list[0]], y=df[x[i]], data=df, palette = "winter")
plt.savefig(f"static/images/miss/boxplot{i}.png", bbox_inches ="tight")
plt.clf()
images = [f"static/images/miss/boxplot{i}.png" for i in range(len(x))]
for i in y:
if i in x:
x.remove(i)
return render_template("missvalue2.html", length = len(x), images=images, message = "BoxPlots to see the outliers!", columns_numerical = x)
# Dataset Containing rows with missing values only
@app.route("/show_miss")
def show_miss():
return render_template("miss_dataset.html", dataset = df[df.isnull().any(axis=1)].replace(np.nan, '', regex=True).to_html())
# Missing Value Imputation
@app.route("/fill_misses_numerical", methods = ["POST"])
def miss_fill():
features=request.form.getlist("columns_num")
features = [i.replace(","," ") for i in features]
array=list(np.unique(df[select_list[0]]))
for i in range(len(features)):
for j in range(len(array)):
feature = features[i]
target=array[j]
median=df[df[select_list[0]]==target][feature].median()
df[feature].fillna(median,inplace=True)
plt.clf()
return redirect(url_for("phase2"))
@app.route("/fill_misses_categorical", methods = ["GET","POST"])
def fill_misses_categorical():
features = y
for i in features:
mode_value = df[i].mode().iloc[0]
df[i] = df[i].fillna(mode_value)
return redirect(url_for("phase2"))
#Encoding Categorical Features
@app.route("/phase3")
def phase3():
global send
x=df.dtypes.astype(str).to_list()
count = 0
idx=[] #idx of categorical features
unique_features=[]
for i in range(len(x)):
if x[i]=="object":
count+=1;
idx.append(i)
unique_features.append(list(df[df.columns.to_list()[i]].unique()))
if count==0:
return render_template("Encoding1.html", message1="No Categorical Features Found",message2="Your can proceed to next step")
feature_names=[df.columns.to_list()[i] for i in idx] #categorical feature names
send={} # dictionary of categorical features and their unique values
for i in range(len(feature_names)):
send[feature_names[i]]=unique_features[i]
return render_template("Encoding.html", message1="Your dataset has "+str(count)+" categorical features",message2="Encoding them to Numeric Values here"
,send=send)
@app.route("/encoding",methods=["GET","POST"])
def encode():
global encodings,feature
encoded_values=[] #list of encoded values
array=[] #list of categorical features
feature=[] #list of categorical features
for features,values in send.items():
array.append(send[features])
encoded_values.append([request.form.get(f"{value}") for value in values])
encoded_values=[[int(x) if x is not None else None for x in sub_list] for sub_list in encoded_values]
child_list=[] #list of index and encoded values
x=[sublist for sublist in encoded_values if None not in sublist]
child_list.append([encoded_values.index(x[0]),x[0]])
encodings={} #dictionary of encoded values
for i in range(len(child_list[0][1])):
encodings[array[child_list[0][0]][i]]=child_list[0][1][i]
for features in send.keys():
feature.append(features)
feature=feature[child_list[0][0]]
return render_template("Encoding2.html",encodings=encodings)
@app.route("/encode_it",methods=["GET","POST"])
def encode_1():
global df1
df[feature]=[encodings[x] for x in df[feature]]
df1= df.copy()
return redirect(url_for("phase3"))
@app.route("/download")
def download():
csv_file=io.StringIO()
df.to_csv(csv_file,index=False)
return send_file(
io.BytesIO(csv_file.getvalue().encode()),
as_attachment=True,
download_name="Dataset.csv",
mimetype='text/csv'
)
@app.route("/phase4")
def phase4():
return render_template("EDA.html")
@app.route("/phase5")
def phase5():
return render_template("ML_intro.html")
@app.route("/show_tts")
def tts():
# global df
# df=pd.read_csv("Real estate.csv")
return render_template("tts.html",columns=df.columns.to_list())
@app.route("/start_machine", methods = ["GET","POST"])
def start_machine():
global X_train,X_test,y_train,y_test,training,target
test=request.form.get("test_size")
problem=request.form.get("problem")
target = request.form.getlist('columns')
target = [i.replace(","," ") for i in target]
target=target[0]
training = request.form.getlist('columns1')
training = [i.replace(","," ") for i in training]
# Separating Independent and Dependent Features
X = df[training]
y=df[target]
#splitting
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=float(test),random_state=42)
if problem=="Regression":
return render_template("regression.html", test_size=test,
training=X_train.shape, testing=X_test.shape)
else:
return render_template("classification.html", test_size=test,
training=X_train.shape, testing=X_test.shape)
@app.route("/train_reg_models", methods = ["GET","POST"])
def train_reg_models():
global regression_models
regression_models=request.form.getlist("regression_models")
if len(regression_models) > 1:
return render_template("regression2.html",training=X_train.shape, testing=X_test.shape)
for i in regression_models:
if i == "linear_reg":
return render_template("models/LinearRegression/LinearRegression.html",
target=target, trains=training)
if i == "decision_tree_reg":
return render_template("models/DecisionTree/DecisionTreeRegressor.html",
target=target, trains=training)
if i == "svr":
return render_template("models/SupportVectorMachines/SupportVectorRegressor.html",
target=target, trains=training)
if i == "random_forest_reg":
return render_template("models/RandomForest/RandomForestRegressor.html",
target=target, trains=training)
if i == "adaboost_reg":
return render_template("models/Boosting/Regressors/AdaboostRegressor.html",
target=target, trains=training)
if i == "gradientboost_reg":
return render_template("models/Boosting/Regressors/GradientBoostRegressor.html",
target=target, trains=training)
if i == "xgboost_reg":
return render_template("models/Boosting/Regressors/XgboostRegressor.html",
target=target, trains=training)
if i == "knn_reg":
return render_template("models/KNearestNeighbours/KNNRegressor.html",
target=target, trains=training)
@app.route("/train_linear_reg", methods = ["GET","POST"])
def train_linear_reg():
global linear_regressor
bias=request.form.get("bias")
# is_scale=request.form.get("scaler")
# if is_scale=="yes":
# X_train,X_test=scale_down(X_train,X_test)
# Above piece of Code is not Working and i do not know why
if bias == "L1 Regularization":
linear_regressor=lasso_regression(X_train,y_train)
return render_template("models/LinearRegression/LinearRegression.html",
target=target, trains=training,train_status="Model is trained Successfully",
message="Click Here",columns = training,model = "linear_reg")
elif bias == "L2 Regularization":
linear_regressor=ridge_regression(X_train,y_train)
return render_template("models/LinearRegression/LinearRegression.html",
target=target, trains=training,train_status="Model is trained Successfully",
message="Click Here",columns = training,model = "linear_reg")
elif bias == "Both":
linear_regressor=ridge_regression(X_train,y_train)
return render_template("models/LinearRegression/LinearRegression.html",
target=target, trains=training,train_status="Model is trained Successfully",
message="Click Here",columns = training,model = "linear_reg")
else:
linear_regressor=linear_regression(X_train,y_train)
return render_template("models/LinearRegression/LinearRegression.html",
target=target, trains=training,train_status="Model is trained Successfully",
columns = training,model = "linear_reg")
@app.route("/test_linear_reg", methods = ["GET","POST"])
def test_linear_reg():
score=check_r2_score(y_test,linear_regressor.predict(X_test))
score=score*100
return jsonify({"score":score})
@app.route("/visualize_linear_reg", methods = ["GET","POST"])
def visualize_linear_reg():
plt.clf()
plt.figure(figsize=(15,15))
plt.scatter(X_train,y_train,color="red",s=2)
plt.plot(X_train,linear_regressor.predict(X_train),color="blue")
plt.title("Linear Regression")
plt.xlabel("Independent Variable")
plt.ylabel("Dependent Variable")
plt.savefig("static/images/models/LinearRegression/linear_reg.png", bbox_inches = 'tight')
return render_template("models/LinearRegression/LinearRegression2.html",
graph1="static/images/models/LinearRegression/linear_reg.png")
@app.route("/train_decision_tree_reg", methods = ["GET","POST"])
def train_decision_tree_reg():
global decision_tree_regressor
tree=request.form.get("tree")
if tree == "ExtraTreeRegressor":
decision_tree_regressor=extra_tree_regression(X_train,y_train)
return render_template("models/DecisionTree/DecisionTreeRegressor.html",
target=target, trains=training,train_status="ExtraTree is trained Successfully")
else:
decision_tree_regressor=decision_tree_regression(X_train,y_train)
return render_template("models/DecisionTree/DecisionTreeRegressor.html",
target=target, trains=training,train_status="Model is trained Successfully",
columns=training,model="decision_tree_reg")
@app.route("/test_decision_tree_reg", methods = ["GET","POST"])
def test_decision_tree_reg():
score=check_r2_score(y_test,decision_tree_regressor.predict(X_test))
score=score*100
return jsonify({"score":score})
@app.route("/train_support_vector_regressor", methods = ["GET","POST"])
def train_support_vector_regressor():
global support_vector_regressor
epsilon = request.form.get("epsilon")
max_iter = request.form.get("max_iter")
kernel = request.form.get("kernel")
parameter = request.form.get("parameter")
gamma = request.form.get("gamma")
if not epsilon:
epsilon=0.1
else:
epsilon = float(epsilon)
if not max_iter:
max_iter=-1
else:
max_iter = int(max_iter)
if not kernel:
kernel = "rbf"
if not parameter:
parameter = 1.0
else:
parameter = float(parameter)
if not gamma:
gamma = "scale"
elif gamma == "auto":
gamma = "auto"
else:
gamma = float(gamma)
support_vector_regressor = support_vector_regression(X_train,y_train,epsilon=epsilon, max_iter=max_iter, kernel=kernel, parameter=parameter, gamma=gamma)
return render_template("models/SupportVectorMachines/SupportVectorRegressor.html",
target=target, trains=training,train_status="Model is trained Successfully",
columns=training,model="support_vector_reg")
@app.route("/test_support_vector_regressor", methods = ["GET","POST"])
def test_support_vector_regressor():
score=check_r2_score(y_test,support_vector_regressor.predict(X_test))
score=score*100
return jsonify({"score":score})
@app.route("/train_random_forest_regressor", methods = ["GET","POST"])
def train_random_forest_regressor():
global random_forest_regressor
n_estimators = request.form.get("n_estimators")
max_depth = request.form.get("max_depth")
max_features = request.form.get("max_features")
criterion = request.form.get("criterion")
bootstrap = request.form.get("bootstrap")
oob_score = request.form.get("oob")
if not n_estimators:
n_estimators=100
else:
n_estimators = int(n_estimators)
if not max_depth:
max_depth=None
else:
max_depth = int(max_depth)
if not max_features:
max_features=1
elif max_features == "log2":
max_features = "log2"
elif max_features == "None":
max_features = None
elif max_features == "sqrt":
max_features = "sqrt"
else:
max_features = float(max_features)
if not criterion:
criterion="squared_error"
if not bootstrap:
bootstrap=True
else:
bootstrap=False
if not oob_score:
oob_score=False
else:
oob_score=True
random_forest_regressor = random_forest_regression(X_train,y_train,n_estimators=n_estimators, max_depth=max_depth, max_features=max_features, criterion=criterion, bootstrap=bootstrap, oob_score=oob_score)
return render_template("models/RandomForest/RandomForestRegressor.html",
training=X_train.shape, target=X_test.shape,train_status="Model is trained Successfully",
columns=training,model="random_forest_reg")
@app.route("/test_random_forest_regressor", methods = ["GET","POST"])
def test_random_forest_regressor():
score=check_r2_score(y_test,random_forest_regressor.predict(X_test))
score=score*100
return jsonify({"score":score})
@app.route("/train_adaboost_regressor", methods = ["GET","POST"])
def train_adaboost_regressor():
global adaboost_regressor
n_estimators = request.form.get("n_estimators")
learning_rate = request.form.get("learning_rate")
loss = request.form.get("loss")
if not n_estimators:
n_estimators=50
else:
n_estimators = int(n_estimators)
if not learning_rate:
learning_rate=1.0
else:
learning_rate = float(learning_rate)
if not loss:
loss="linear"