-
Notifications
You must be signed in to change notification settings - Fork 2
/
MLMD.py
3575 lines (2712 loc) · 192 KB
/
MLMD.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
'''
Runs the streamlit app
Call this file in the terminal via `streamlit run app.py`
'''
from streamlit_extras.badges import badge
import streamlit as st
from streamlit_extras.colored_header import colored_header
from streamlit_option_menu import option_menu
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split as TTS
from sklearn.model_selection import cross_val_score as CVS
from sklearn.model_selection import cross_validate as CV
from sklearn.metrics import make_scorer, r2_score
from sklearn.model_selection import LeaveOneOut
from sklearn import tree
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor as RFR
from sklearn.ensemble import RandomForestClassifier as RFC
from sklearn.linear_model import LinearRegression as LinearR
from sklearn.linear_model import LogisticRegression as LR
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge
from sklearn.neural_network import MLPRegressor
from sklearn.svm import SVR
from sklearn.svm import SVC
from sklearn.impute import SimpleImputer
from sklearn.feature_selection import mutual_info_regression as MIR
from sklearn.cluster import KMeans
from sklearn.metrics import confusion_matrix
from sklearn.metrics import r2_score
from sklearn.metrics import make_scorer
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import BaggingRegressor
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import GradientBoostingRegressor
import xgboost as xgb
from catboost import CatBoostClassifier
from catboost import CatBoostRegressor
from sklearn.gaussian_process import GaussianProcessRegressor
import Bgolearn.BGOsampling as BGOS
import graphviz
import shap
import matplotlib.pyplot as plt
import pickle
from utils import *
from streamlit_extras.badges import badge
from sklearn.gaussian_process.kernels import RBF
import warnings
from sko.GA import GA
from sko.PSO import PSO
from sko.DE import DE
from sko.AFSA import AFSA
from sko.SA import SAFast
# import sys
from prettytable import PrettyTable
import scienceplots
from algorithm.TrAdaboostR2 import TrAdaboostR2
from algorithm.mobo import Mobo4mat
warnings.filterwarnings('ignore')
st.set_page_config(
page_title="MLMD",
page_icon="🍁",
layout="centered",
initial_sidebar_state="auto",
menu_items={
})
sysmenu = '''
<style>
MainMenu {visibility:hidden;}
footer {visibility:hidden;}
'''
# https://icons.bootcss.com/
st.markdown(sysmenu,unsafe_allow_html=True)
# arrow-repeat
with st.sidebar:
select_option = option_menu("MLMD", ["平台主页", "基础功能", "特征工程", "回归预测", "主动学习","迁移学习", "代理优化", "其他"],
icons=['house', 'clipboard-data', 'menu-button-wide','bezier2', 'arrow-repeat','subtract', 'app', 'microsoft'],
menu_icon="boxes", default_index=0)
if select_option == "平台主页":
st.write('''![](https://user-images.githubusercontent.com/61132191/231174459-96d33cdf-9f6f-4296-ba9f-31d11056ef12.jpg?raw=true)''')
# st.markdown("<br>", unsafe_allow_html=True)
col1, col2, col3, col4 = st.columns([1,0.25,0.2,0.5])
with col1:
pass
# st.write('''
# Check out [help document](https://mlmd.netlify.app/) for more information
# ''')
with col2:
st.write('[![](https://img.shields.io/badge/MLMD-Github-yellowgreen)](https://github.com/Jiaxuan-Ma/Machine-Learning-for-Material-Design)')
with col3:
badge(type="github", name="Jiaxuan-Ma/MLMD")
with col4:
st.write("")
colored_header(label="材料设计的机器学习平台",description="Machine Learning for Material Design",color_name="violet-90")
# st.write("## Machine Learning for Material Design")
# st.write("## 材料的机器学习平台")
st.markdown(
'''
The **MLMD** platform (**M**achine **L**earning for **M**aterial **D**esign) for Material or Engineering aims at utilizing general and frontier machine learning algrithm to accelerate the material design with no-programming. \n
材料基因组工程理念的发展将会大幅度提高新材料的研发效率、缩短研发周期、降低研发成本、全面加速材料从设计到工程化应用的进程。
因此**MLMD**旨在为材料试验科研人员提供快速上手,无编程的机器学习算法平台,致力于材料试验到材料设计的一体化。
''')
colored_header(label="数据布局",description="only support `.csv` file",color_name="violet-90")
st.write('''![](https://user-images.githubusercontent.com/61132191/231178382-aa223924-f1cb-4e0e-afa1-08c536111f3a.jpg?raw=true)''')
# colored_header(label="致谢",description="",color_name="violet-90")
# st.markdown(
# '''
# 国家科技部重点研发计划(No. 2022YFB3707803)
# ''')
elif select_option == "基础功能":
colored_header(label="数据可视化",description=" ",color_name="violet-90")
file = st.file_uploader("Upload `.csv`file", type=['csv'], label_visibility="collapsed")
if file is None:
table = PrettyTable(['上传文件名称', '名称','数据说明'])
table.add_row(['file_1','dataset','数据集'])
st.write(table)
if file is not None:
df = pd.read_csv(file)
# check NaN
check_string_NaN(df)
colored_header(label="数据信息",description=" ",color_name="violet-70")
nrow = st.slider("rows", 1, len(df)-1, 5)
df_nrow = df.head(nrow)
st.write(df_nrow)
colored_header(label="数据初步统计",description=" ",color_name="violet-30")
st.write(df.describe())
tmp_download_link = download_button(df.describe(), f'数据统计.csv', button_text='download')
st.markdown(tmp_download_link, unsafe_allow_html=True)
colored_header(label="特征变量和目标变量", description=" ",color_name="violet-70")
target_num = st.number_input('目标变量数量', min_value=1, max_value=10, value=1)
col_feature, col_target = st.columns(2)
# features
features = df.iloc[:,:-target_num]
# targets
targets = df.iloc[:,-target_num:]
with col_feature:
st.write(features.head())
with col_target:
st.write(targets.head())
colored_header(label="特征变量统计分布", description=" ",color_name="violet-30")
feature_selected_name = st.selectbox('选择特征变量',list(features))
feature_selected_value = features[feature_selected_name]
plot = customPlot()
col1, col2 = st.columns([1,3])
with col1:
with st.expander("绘图参数"):
options_selected = [plot.set_title_fontsize(1),plot.set_label_fontsize(2),
plot.set_tick_fontsize(3),plot.set_legend_fontsize(4),plot.set_color('line color',6,5),plot.set_color('bin color',0,6)]
with col2:
plot.feature_hist_kde(options_selected,feature_selected_name,feature_selected_value)
#=========== Targets visulization ==================
colored_header(label="目标变量统计分布", description=" ",color_name="violet-30")
target_selected_name = st.selectbox('选择目标变量',list(targets))
target_selected_value = targets[target_selected_name]
plot = customPlot()
col1, col2 = st.columns([1,3])
with col1:
with st.expander("绘图参数"):
options_selected = [plot.set_title_fontsize(7),plot.set_label_fontsize(8),
plot.set_tick_fontsize(9),plot.set_legend_fontsize(10), plot.set_color('line color',6,11), plot.set_color('bin color',0,12)]
with col2:
plot.target_hist_kde(options_selected,target_selected_name,target_selected_value)
#=========== Features analysis ==================
colored_header(label="特征变量配方(合金成分)", description=" ",color_name="violet-30")
feature_range_selected_name = st.slider('选择特征变量个数',1,len(features.columns), (1,2))
min_feature_selected = feature_range_selected_name[0]-1
max_feature_selected = feature_range_selected_name[1]
feature_range_selected_value = features.iloc[:,min_feature_selected: max_feature_selected]
data_by_feature_type = df.groupby(list(feature_range_selected_value))
feature_type_data = create_data_with_group_and_counts(data_by_feature_type)
IDs = [str(id_) for id_ in feature_type_data['ID']]
Counts = feature_type_data['Count']
col1, col2 = st.columns([1,3])
with col1:
with st.expander("绘图参数"):
options_selected = [plot.set_title_fontsize(13),plot.set_label_fontsize(14),
plot.set_tick_fontsize(15),plot.set_legend_fontsize(16),plot.set_color('bin color',0, 17)]
with col2:
plot.featureSets_statistics_hist(options_selected,IDs, Counts)
colored_header(label="特征变量在数据集中的分布", description=" ",color_name="violet-30")
feature_selected_name = st.selectbox('选择特征变量', list(features),1)
feature_selected_value = features[feature_selected_name]
col1, col2 = st.columns([1,3])
with col1:
with st.expander("绘图参数"):
options_selected = [plot.set_title_fontsize(18),plot.set_label_fontsize(19),
plot.set_tick_fontsize(20),plot.set_legend_fontsize(21), plot.set_color('bin color', 0, 22)]
with col2:
plot.feature_distribution(options_selected,feature_selected_name,feature_selected_value)
colored_header(label="特征变量和目标变量关系", description=" ",color_name="violet-30")
col1, col2 = st.columns([1,3])
with col1:
with st.expander("绘图参数"):
options_selected = [plot.set_title_fontsize(23),plot.set_label_fontsize(24),
plot.set_tick_fontsize(25),plot.set_legend_fontsize(26),plot.set_color('scatter color',0, 27),plot.set_color('line color',6,28)]
with col2:
plot.features_and_targets(options_selected,df, list(features), list(targets))
# st.write("### Targets and Targets ")
if targets.shape[1] != 1:
colored_header(label="目标变量和目标变量关系", description=" ",color_name="violet-30")
col1, col2 = st.columns([1,3])
with col1:
with st.expander("绘图参数"):
options_selected = [plot.set_title_fontsize(29),plot.set_label_fontsize(30),
plot.set_tick_fontsize(31),plot.set_legend_fontsize(32),plot.set_color('scatter color',0, 33),plot.set_color('line color',6,34)]
with col2:
plot.targets_and_targets(options_selected,df, list(targets))
st.write('---')
elif select_option == "特征工程":
with st.sidebar:
sub_option = option_menu(None, ["空值处理", "特征唯一值处理", "特征和特征相关性", "特征和目标相关性", "One-hot编码", "特征重要性"])
if sub_option == "空值处理":
colored_header(label="空值处理",description=" ",color_name="violet-90")
file = st.file_uploader("Upload `.csv`file", type=['csv'], label_visibility="collapsed")
if file is None:
table = PrettyTable(['上传文件名称', '名称','数据说明'])
table.add_row(['file_1','dataset','数据集'])
st.write(table)
if file is not None:
# colored_header(label="数据信息",description=" ",color_name="violet-70")
# with st.expander('数据信息'):
df = pd.read_csv(file)
# check NuLL
null_columns = df.columns[df.isnull().any()]
if len(null_columns) == 0:
st.error('No missing features!')
st.stop()
colored_header(label="数据信息", description=" ",color_name="violet-70")
nrow = st.slider("rows", 1, len(df)-1, 5)
df_nrow = df.head(nrow)
st.write(df_nrow)
colored_header(label="目标变量和特征变量",description=" ",color_name="violet-70")
target_num = st.number_input('目标变量数量', min_value=1, max_value=10, value=1)
col_feature, col_target = st.columns(2)
# features
features = df.iloc[:,:-target_num]
# targets
targets = df.iloc[:,-target_num:]
with col_feature:
st.write(features.head())
with col_target:
st.write(targets.head())
# sub_sub_option = option_menu(None, ["丢弃空值", "填充空值"])
colored_header(label="选择方法",description=" ",color_name="violet-70")
sub_sub_option = option_menu(None, ["丢弃空值", "填充空值"],
icons=['house', "list-task"],
menu_icon="cast", default_index=0, orientation="horizontal")
if sub_sub_option == "丢弃空值":
fs = FeatureSelector(features, targets)
missing_threshold = st.slider("丢弃阈值(空值占比)",0.001, 1.0, 0.5)
fs.identify_missing(missing_threshold)
fs.features_dropped_missing = fs.features.drop(columns=fs.ops['missing'])
data = pd.concat([fs.features_dropped_missing, targets], axis=1)
st.write(data)
tmp_download_link = download_button(data, f'空值丢弃数据.csv', button_text='download')
st.markdown(tmp_download_link, unsafe_allow_html=True)
st.write('%d features with $\gt$ %0.2f missing threshold.\n' % (len(fs.ops['missing']), fs.missing_threshold))
plot = customPlot()
with st.expander('绘图'):
col1, col2 = st.columns([1,3])
with col1:
options_selected = [plot.set_title_fontsize(1),plot.set_label_fontsize(2),
plot.set_tick_fontsize(3),plot.set_legend_fontsize(4),plot.set_color('bin color',19,5)]
with col2:
plot.feature_missing(options_selected, fs.record_missing, fs.missing_stats)
st.write('---')
if sub_sub_option == "填充空值":
fs = FeatureSelector(features, targets)
missing_feature_list = fs.features.columns[fs.features.isnull().any()].tolist()
with st.container():
fill_method = st.selectbox('填充方法',('常值', '随机森林算法'))
if fill_method == '常值':
missing_feature = st.multiselect('丢失值特征',missing_feature_list,missing_feature_list[-1])
option_filled = st.selectbox('均值',('均值','常数','中位数','众数'))
if option_filled == '均值':
# fs.features[missing_feature] = fs.features[missing_feature].fillna(fs.features[missing_feature].mean())
imp = SimpleImputer(missing_values=np.nan,strategy= 'mean')
fs.features[missing_feature] = imp.fit_transform(fs.features[missing_feature])
elif option_filled == '常数':
# fs.features[missing_feature] = fs.features[missing_feature].fillna(0)
fill_value = st.number_input('输入数值')
imp = SimpleImputer(missing_values=np.nan, strategy= 'constant', fill_value = fill_value)
fs.features[missing_feature] = imp.fit_transform(fs.features[missing_feature])
elif option_filled == '中位数':
# fs.features[missing_feature] = fs.features[missing_feature].fillna(0)
imp = SimpleImputer(missing_values=np.nan, strategy= 'median')
fs.features[missing_feature] = imp.fit_transform(fs.features[missing_feature])
elif option_filled == '众数':
imp = SimpleImputer(missing_values=np.nan, strategy= 'most_frequent')
fs.features[missing_feature] = imp.fit_transform(fs.features[missing_feature])
data = pd.concat([fs.features, targets], axis=1)
else:
with st.expander('超参数'):
num_estimators = st.number_input('number estimators',1, 10000, 100)
criterion = st.selectbox('criterion',('squared_error','absolute_error','friedman_mse','poisson'))
max_depth = st.number_input('max depth',1, 1000, 5)
min_samples_leaf = st.number_input('min samples leaf', 1, 1000, 5)
min_samples_split = st.number_input('min samples split', 1, 1000, 5)
random_state = st.checkbox('random state 1024',True)
option_filled = st.selectbox('均值',('均值','常数','中位数','众数'))
if option_filled == '均值':
feature_missing_reg = fs.features.copy()
null_columns = feature_missing_reg.columns[feature_missing_reg.isnull().any()]
null_counts = feature_missing_reg.isnull().sum()[null_columns].sort_values()
null_columns_ordered = null_counts.index.tolist()
for i in null_columns_ordered:
df = feature_missing_reg
fillc = df[i]
df = pd.concat([df.iloc[:,df.columns != i], pd.DataFrame(targets)], axis=1)
df_temp_fill = SimpleImputer(missing_values=np.nan,strategy= 'mean').fit_transform(df)
YTrain = fillc[fillc.notnull()]
YTest = fillc[fillc.isnull()]
XTrain = df_temp_fill[YTrain.index,:]
XTest = df_temp_fill[YTest.index,:]
rfc = RFR(n_estimators=num_estimators,criterion=criterion,max_depth=max_depth,min_samples_leaf=min_samples_leaf,
min_samples_split=min_samples_split,random_state=random_state)
rfc = rfc.fit(XTrain, YTrain)
YPredict = rfc.predict(XTest)
feature_missing_reg.loc[feature_missing_reg[i].isnull(), i] = YPredict
elif option_filled == '常数':
fill_value = st.number_input('输入数值')
feature_missing_reg = fs.features.copy()
null_columns = feature_missing_reg.columns[feature_missing_reg.isnull().any()]
null_counts = feature_missing_reg.isnull().sum()[null_columns].sort_values()
null_columns_ordered = null_counts.index.tolist()
for i in null_columns_ordered:
df = feature_missing_reg
fillc = df[i]
df = pd.concat([df.iloc[:,df.columns != i], pd.DataFrame(targets)], axis=1)
df_temp_fill = SimpleImputer(missing_values=np.nan, strategy= 'constant', fill_value = fill_value).fit_transform(df)
YTrain = fillc[fillc.notnull()]
YTest = fillc[fillc.isnull()]
XTrain = df_temp_fill[YTrain.index,:]
XTest = df_temp_fill[YTest.index,:]
rfc = RFR(n_estimators=num_estimators,criterion=criterion,max_depth=max_depth,min_samples_leaf=min_samples_leaf,
min_samples_split=min_samples_split,random_state=random_state)
rfc = rfc.fit(XTrain, YTrain)
YPredict = rfc.predict(XTest)
feature_missing_reg.loc[feature_missing_reg[i].isnull(), i] = YPredict
elif option_filled == '中位数':
feature_missing_reg = fs.features.copy()
null_columns = feature_missing_reg.columns[feature_missing_reg.isnull().any()]
null_counts = feature_missing_reg.isnull().sum()[null_columns].sort_values()
null_columns_ordered = null_counts.index.tolist()
for i in null_columns_ordered:
df = feature_missing_reg
fillc = df[i]
df = pd.concat([df.iloc[:,df.columns != i], pd.DataFrame(targets)], axis=1)
df_temp_fill = SimpleImputer(missing_values=np.nan,strategy= 'median').fit_transform(df)
YTrain = fillc[fillc.notnull()]
YTest = fillc[fillc.isnull()]
XTrain = df_temp_fill[YTrain.index,:]
XTest = df_temp_fill[YTest.index,:]
rfc = RFR(n_estimators=num_estimators,criterion=criterion,max_depth=max_depth,min_samples_leaf=min_samples_leaf,
min_samples_split=min_samples_split,random_state=random_state)
rfc = rfc.fit(XTrain, YTrain)
YPredict = rfc.predict(XTest)
feature_missing_reg.loc[feature_missing_reg[i].isnull(), i] = YPredict
elif option_filled == '众数':
feature_missing_reg = fs.features.copy()
null_columns = feature_missing_reg.columns[feature_missing_reg.isnull().any()]
null_counts = feature_missing_reg.isnull().sum()[null_columns].sort_values()
null_columns_ordered = null_counts.index.tolist()
for i in null_columns_ordered:
df = feature_missing_reg
fillc = df[i]
df = pd.concat([df.iloc[:,df.columns != i], pd.DataFrame(targets)], axis=1)
df_temp_fill = SimpleImputer(missing_values=np.nan,strategy= 'most_frequent').fit_transform(df)
YTrain = fillc[fillc.notnull()]
YTest = fillc[fillc.isnull()]
XTrain = df_temp_fill[YTrain.index,:]
XTest = df_temp_fill[YTest.index,:]
rfc = RFR(n_estimators=num_estimators,criterion=criterion,max_depth=max_depth,min_samples_leaf=min_samples_leaf,
min_samples_split=min_samples_split,random_state=random_state)
rfc = rfc.fit(XTrain, YTrain)
YPredict = rfc.predict(XTest)
feature_missing_reg.loc[feature_missing_reg[i].isnull(), i] = YPredict
data = pd.concat([feature_missing_reg, targets], axis=1)
st.write(data)
tmp_download_link = download_button(data, f'空值填充数据.csv', button_text='download')
st.markdown(tmp_download_link, unsafe_allow_html=True)
st.write('---')
elif sub_option == "特征唯一值处理":
colored_header(label="特征唯一值处理",description=" ",color_name="violet-90")
file = st.file_uploader("Upload `.csv`file", type=['csv'], label_visibility="collapsed")
if file is None:
table = PrettyTable(['上传文件名称', '名称','数据说明'])
table.add_row(['file_1','dataset','数据集'])
st.write(table)
if file is not None:
colored_header(label="数据信息",description=" ",color_name="violet-70")
df = pd.read_csv(file)
# 检测缺失值
check_string_NaN(df)
nrow = st.slider("rows", 1, len(df)-1, 5)
df_nrow = df.head(nrow)
st.write(df_nrow)
colored_header(label="特征变量和目标变量",description=" ",color_name="violet-70")
target_num = st.number_input('目标变量数量', min_value=1, max_value=10, value=1)
col_feature, col_target = st.columns(2)
# features
features = df.iloc[:,:-target_num]
# targets
targets = df.iloc[:,-target_num:]
with col_feature:
st.write(features.head())
with col_target:
st.write(targets.head())
colored_header(label="丢弃唯一值特征变量",description=" ",color_name="violet-70")
fs = FeatureSelector(features, targets)
plot = customPlot()
col1, col2 = st.columns([1,3])
with col1:
fs.identify_nunique()
option_counts = st.slider('丢弃唯一值特征数量',0, int(fs.unique_stats.max())-1,1)
st.write(fs.unique_stats)
with col2:
fs.identify_nunique(option_counts)
fs.features_dropped_single = fs.features.drop(columns=fs.ops['single_unique'])
data = pd.concat([fs.features_dropped_single, targets], axis=1)
st.write(fs.features_dropped_single)
tmp_download_link = download_button(data, f'丢弃唯一值特征数据.csv', button_text='download')
st.markdown(tmp_download_link, unsafe_allow_html=True)
st.write('%d features $\leq$ %d unique value.\n' % (len(fs.ops['single_unique']),option_counts))
with st.expander('绘图'):
col1, col2 = st.columns([1,3])
with col1:
options_selected = [plot.set_title_fontsize(6),plot.set_label_fontsize(7),
plot.set_tick_fontsize(8),plot.set_legend_fontsize(9),plot.set_color('bin color',19,10)]
with col2:
plot.feature_nunique(options_selected, fs.record_single_unique,fs.unique_stats)
st.write('---')
elif sub_option == "特征和特征相关性":
colored_header(label="特征和特征相关性",description=" ",color_name="violet-90")
file = st.file_uploader("Upload `.csv`file", type=['csv'], label_visibility="collapsed")
if file is None:
table = PrettyTable(['上传文件名称', '名称','数据说明'])
table.add_row(['file_1','dataset','数据集'])
st.write(table)
if file is not None:
df = pd.read_csv(file)
# 检测缺失值
check_string_NaN(df)
colored_header(label="数据信息", description=" ",color_name="violet-70")
nrow = st.slider("rows", 1, len(df)-1, 5)
df_nrow = df.head(nrow)
st.write(df_nrow)
colored_header(label="特征变量和目标变量",description=" ",color_name="violet-70")
target_num = st.number_input('目标变量数量', min_value=1, max_value=10, value=1)
col_feature, col_target = st.columns(2)
# features
features = df.iloc[:,:-target_num]
# targets
targets = df.iloc[:,-target_num:]
with col_feature:
st.write(features.head())
with col_target:
st.write(targets.head())
colored_header(label="丢弃双线性特征变量",description=" ",color_name="violet-30")
fs = FeatureSelector(features, targets)
plot = customPlot()
target_selected_option = st.selectbox('选择目标', list(fs.targets))
target_selected = fs.targets[target_selected_option]
col1, col2 = st.columns([1,3])
with col1:
corr_method = st.selectbox("相关性分析方法",["pearson","spearman","kendall"])
correlation_threshold = st.slider("相关性阈值",0.001, 1.0, 0.9) # 0.52
corr_matrix = pd.concat([fs.features, target_selected], axis=1).corr(corr_method)
fs.identify_collinear(corr_matrix, correlation_threshold)
fs.judge_drop_f_t_after_f_f([target_selected_option], corr_matrix)
is_mask = st.selectbox('掩码',('Yes', 'No'))
with st.expander('绘图参数'):
options_selected = [plot.set_title_fontsize(19),plot.set_label_fontsize(20),
plot.set_tick_fontsize(21),plot.set_legend_fontsize(22)]
with st.expander('丢弃的特征变量'):
st.write(fs.record_collinear)
with col2:
fs.features_dropped_collinear = fs.features.drop(columns=fs.ops['collinear'])
assert fs.features_dropped_collinear.size != 0,'zero feature !'
corr_matrix_drop_collinear = fs.features_dropped_collinear.corr(corr_method)
plot.corr_cofficient(options_selected, is_mask, corr_matrix_drop_collinear)
with st.expander('处理之后的数据'):
data = pd.concat([fs.features_dropped_collinear, targets], axis=1)
st.write(data)
tmp_download_link = download_button(data, f'双线性特征变量处理数据.csv', button_text='download')
st.markdown(tmp_download_link, unsafe_allow_html=True)
elif sub_option == "特征和目标相关性":
colored_header(label="特征和目标相关性",description=" ",color_name="violet-90")
file = st.file_uploader("Upload `.csv`file", type=['csv'], label_visibility="collapsed")
if file is None:
table = PrettyTable(['上传文件名称', '名称','数据说明'])
table.add_row(['file_1','dataset','数据集'])
st.write(table)
if file is not None:
df = pd.read_csv(file)
# 检测缺失值
check_string_NaN(df)
colored_header(label="数据信息", description=" ",color_name="violet-70")
nrow = st.slider("rows", 1, len(df)-1, 5)
df_nrow = df.head(nrow)
st.write(df_nrow)
colored_header(label="特征变量和目标变量",description=" ",color_name="violet-70")
target_num = st.number_input('目标变量数量', min_value=1, max_value=10, value=1)
col_feature, col_target = st.columns(2)
# features
features = df.iloc[:,:-target_num]
# targets
targets = df.iloc[:,-target_num:]
with col_feature:
st.write(features.head())
with col_target:
st.write(targets.head())
colored_header(label="丢弃与目标的低相关性特征",description=" ",color_name="violet-70")
fs = FeatureSelector(features, targets)
plot = customPlot()
target_selected_option = st.selectbox('选择特征', list(fs.targets))
col1, col2 = st.columns([1,3])
with col1:
corr_method = st.selectbox("相关性分析方法",["pearson","spearman","kendall","MIR"], key=15)
if corr_method != "MIR":
option_dropped_threshold = st.slider('相关性阈值',0.0, 1.0,0.0)
if corr_method == 'MIR':
options_seed = st.checkbox('random state 1024',True)
with st.expander('绘图参数'):
options_selected = [plot.set_title_fontsize(11),plot.set_label_fontsize(12),
plot.set_tick_fontsize(13),plot.set_legend_fontsize(14),plot.set_color('bin color',19,16)]
with col2:
target_selected = fs.targets[target_selected_option]
if corr_method != "MIR":
corr_matrix = pd.concat([fs.features, target_selected], axis=1).corr(corr_method).abs()
fs.judge_drop_f_t([target_selected_option], corr_matrix, option_dropped_threshold)
fs.features_dropped_f_t = fs.features.drop(columns=fs.ops['f_t_low_corr'])
corr_f_t = pd.concat([fs.features_dropped_f_t, target_selected], axis=1).corr(corr_method)[target_selected_option][:-1]
plot.corr_feature_target(options_selected, corr_f_t)
with st.expander('处理之后的数据'):
data = pd.concat([fs.features_dropped_f_t, targets], axis=1)
st.write(data)
tmp_download_link = download_button(data, f'丢弃与目标的低相关性特征数据.csv', button_text='download')
st.markdown(tmp_download_link, unsafe_allow_html=True)
else:
if options_seed:
corr_mir = MIR(fs.features, target_selected, random_state=1024)
else:
corr_mir = MIR(fs.features, target_selected)
corr_mir = pd.DataFrame(corr_mir).set_index(pd.Index(list(fs.features.columns)))
corr_mir.rename(columns={0: 'mutual info'}, inplace=True)
plot.corr_feature_target_mir(options_selected, corr_mir)
st.write('---')
elif sub_option == "One-hot编码":
colored_header(label="One-hot编码",description=" ",color_name="violet-90")
file = st.file_uploader("Upload `.csv`file", type=['csv'], label_visibility="collapsed")
if file is None:
table = PrettyTable(['上传文件名称', '名称','数据说明'])
table.add_row(['file_1','dataset','数据集'])
st.write(table)
if file is not None:
df = pd.read_csv(file)
# 检测缺失值
check_string_NaN(df)
colored_header(label="数据信息", description=" ",color_name="violet-70")
nrow = st.slider("rows", 1, len(df)-1, 5)
df_nrow = df.head(nrow)
st.write(df_nrow)
colored_header(label="特征变量和目标变量",description=" ",color_name="violet-70")
target_num = st.number_input('目标变量数量', min_value=1, max_value=10, value=1)
col_feature, col_target = st.columns(2)
# features
features = df.iloc[:,:-target_num]
# targets
targets = df.iloc[:,-target_num:]
with col_feature:
st.write(features.head())
with col_target:
st.write(targets.head())
#=============== drop major missing features ================
colored_header(label="特征变量one-hot编码",description=" ",color_name="violet-70")
fs = FeatureSelector(features, targets)
plot = customPlot()
str_col_list = fs.features.select_dtypes(include=['object']).columns.tolist()
fs.one_hot_feature_encoder(True)
data = pd.concat([fs.features_plus_oneHot, targets], axis=1)
# delete origin string columns
data = data.drop(str_col_list, axis=1)
st.write(data)
tmp_download_link = download_button(data, f'特征变量one-hot编码数据.csv', button_text='download')
st.markdown(tmp_download_link, unsafe_allow_html=True)
st.write('---')
elif sub_option == "特征重要性":
colored_header(label="特征重要性",description=" ",color_name="violet-90")
file = st.file_uploader("Upload `.csv`file", type=['csv'], label_visibility="collapsed")
if file is None:
table = PrettyTable(['上传文件名称', '名称','数据说明'])
table.add_row(['file_1','dataset','数据集'])
st.write(table)
if file is not None:
df = pd.read_csv(file)
# 检测缺失值
check_string_NaN(df)
colored_header(label="数据信息", description=" ",color_name="violet-70")
nrow = st.slider("rows", 1, len(df)-1, 5)
df_nrow = df.head(nrow)
st.write(df_nrow)
colored_header(label="特征变量和目标变量",description=" ",color_name="violet-70")
target_num = st.number_input('目标变量数量', min_value=1, max_value=10, value=1)
col_feature, col_target = st.columns(2)
# features
features = df.iloc[:,:-target_num]
# targets
targets = df.iloc[:,-target_num:]
with col_feature:
st.write(features.head())
with col_target:
st.write(targets.head())
fs = FeatureSelector(features,targets)
colored_header(label="选择目标变量", description=" ", color_name="violet-70")
target_selected_name = st.selectbox('目标变量', list(fs.targets)[::-1])
fs.targets = targets[target_selected_name]
colored_header(label="Selector", description=" ",color_name="violet-70")
model_path = './models/feature importance'
template_alg = model_platform(model_path=model_path)
colored_header(label="Training", description=" ",color_name="violet-70")
inputs, col2 = template_alg.show()
# st.write(inputs)
if inputs['model'] == 'LinearRegressor':
fs.model = LinearR()
with col2:
option_cumulative_importance = st.slider('累计重要性阈值',0.0, 1.0, 0.95)
Embedded_method = st.checkbox('Embedded method',False)
if Embedded_method:
cv = st.number_input('cv',1,10,5)
with st.container():
button_train = st.button('train', use_container_width=True)
if button_train:
fs.LinearRegressor()
fs.identify_zero_low_importance(option_cumulative_importance)
fs.feature_importance_select_show()
if Embedded_method:
threshold = fs.cumulative_importance
feature_importances = fs.feature_importances.set_index('feature',drop = False)
features = []
scores = []
cumuImportance = []
for i in range(1, len(fs.features.columns) + 1):
features.append(feature_importances.iloc[:i, 0].values.tolist())
X_selected = fs.features[features[-1]]
score = CVS(fs.model, X_selected, fs.targets, cv=cv ,scoring='r2').mean()
cumuImportance.append(feature_importances.loc[features[-1][-1], 'cumulative_importance'])
scores.append(score)
cumu_importance = np.array(cumuImportance)
scores = np.array(scores)
fig, ax = plt.subplots()
ax = plt.plot(cumu_importance, scores,'o-')
plt.xlabel("cumulative feature importance")
plt.ylabel("r2")
st.pyplot(fig)
elif inputs['model'] == 'LassoRegressor':
fs.model = Lasso(random_state=inputs['random state'])
with col2:
option_cumulative_importance = st.slider('累计重要性阈值',0.0, 1.0, 0.95)
Embedded_method = st.checkbox('Embedded method',False)
if Embedded_method:
cv = st.number_input('cv',1,10,5)
with st.container():
button_train = st.button('train', use_container_width=True)
if button_train:
fs.LassoRegressor()
fs.identify_zero_low_importance(option_cumulative_importance)
fs.feature_importance_select_show()
if Embedded_method:
threshold = fs.cumulative_importance
feature_importances = fs.feature_importances.set_index('feature',drop = False)
features = []
scores = []
cumuImportance = []
for i in range(1, len(fs.features.columns) + 1):
features.append(feature_importances.iloc[:i, 0].values.tolist())
X_selected = fs.features[features[-1]]
score = CVS(fs.model, X_selected, fs.targets, cv=cv, scoring='r2').mean()
cumuImportance.append(feature_importances.loc[features[-1][-1], 'cumulative_importance'])
scores.append(score)
cumu_importance = np.array(cumuImportance)
scores = np.array(scores)
fig, ax = plt.subplots()
ax = plt.plot(cumu_importance, scores,'o-')
plt.xlabel("cumulative feature importance")
plt.ylabel("r2")
st.pyplot(fig)
elif inputs['model'] == 'RidgeRegressor':
fs.model = Ridge(random_state=inputs['random state'])
with col2:
option_cumulative_importance = st.slider('累计重要性阈值',0.0, 1.0, 0.95)
Embedded_method = st.checkbox('Embedded method',False)
if Embedded_method:
cv = st.number_input('cv',1,10,5)
with st.container():
button_train = st.button('train', use_container_width=True)
if button_train:
fs.RidgeRegressor()
fs.identify_zero_low_importance(option_cumulative_importance)
fs.feature_importance_select_show()
if Embedded_method:
threshold = fs.cumulative_importance
feature_importances = fs.feature_importances.set_index('feature',drop = False)
features = []
scores = []
cumuImportance = []
for i in range(1, len(fs.features.columns) + 1):
features.append(feature_importances.iloc[:i, 0].values.tolist())
X_selected = fs.features[features[-1]]
score = CVS(fs.model, X_selected, fs.targets, cv=cv, scoring='r2').mean()
cumuImportance.append(feature_importances.loc[features[-1][-1], 'cumulative_importance'])
scores.append(score)
cumu_importance = np.array(cumuImportance)
scores = np.array(scores)
fig, ax = plt.subplots()
ax = plt.plot(cumu_importance, scores,'o-')
plt.xlabel("cumulative feature importance")
plt.ylabel("r2")
st.pyplot(fig)
elif inputs['model'] == 'LassoRegressor':
fs.model = Lasso(random_state=inputs['random state'])
with col2:
option_cumulative_importance = st.slider('累计重要性阈值',0.0, 1.0, 0.95)
Embedded_method = st.checkbox('Embedded method',False)
if Embedded_method:
cv = st.number_input('cv',1,10,5)
with st.container():
button_train = st.button('train', use_container_width=True)
if button_train:
fs.LassoRegressor()
fs.identify_zero_low_importance(option_cumulative_importance)
fs.feature_importance_select_show()
if Embedded_method:
threshold = fs.cumulative_importance
feature_importances = fs.feature_importances.set_index('feature',drop = False)
features = []
scores = []
cumuImportance = []
for i in range(1, len(fs.features.columns) + 1):
features.append(feature_importances.iloc[:i, 0].values.tolist())
X_selected = fs.features[features[-1]]
score = CVS(fs.model, X_selected, fs.targets, cv=cv, scoring='r2').mean()
cumuImportance.append(feature_importances.loc[features[-1][-1], 'cumulative_importance'])
scores.append(score)
cumu_importance = np.array(cumuImportance)
scores = np.array(scores)
fig, ax = plt.subplots()
ax = plt.plot(cumu_importance, scores,'o-')
plt.xlabel("cumulative feature importance")
plt.ylabel("r2")
st.pyplot(fig)
elif inputs['model'] == 'RandomForestRegressor':
fs.model = RFR(criterion = inputs['criterion'], n_estimators=inputs['nestimators'] ,random_state=inputs['random state'],max_depth=inputs['max depth'],min_samples_leaf=inputs['min samples leaf'],
min_samples_split=inputs['min samples split'],oob_score=inputs['oob score'], warm_start=inputs['warm start'],
n_jobs=inputs['njobs'])
with col2:
option_cumulative_importance = st.slider('累计重要性阈值',0.5, 1.0, 0.95)
Embedded_method = st.checkbox('Embedded method',False)
if Embedded_method:
cv = st.number_input('cv',1,10,5)
with st.container():
button_train = st.button('train', use_container_width=True)
if button_train:
fs.RandomForestRegressor()
fs.identify_zero_low_importance(option_cumulative_importance)
fs.feature_importance_select_show()
if Embedded_method:
threshold = fs.cumulative_importance
feature_importances = fs.feature_importances.set_index('feature',drop = False)
features = []
scores = []
cumuImportance = []
for i in range(1, len(fs.features.columns) + 1):
features.append(feature_importances.iloc[:i, 0].values.tolist())
X_selected = fs.features[features[-1]]
score = CVS(fs.model, X_selected, fs.targets, cv=cv ,scoring='r2').mean()
cumuImportance.append(feature_importances.loc[features[-1][-1], 'cumulative_importance'])
scores.append(score)
cumu_importance = np.array(cumuImportance)
scores = np.array(scores)
fig, ax = plt.subplots()
ax = plt.plot(cumu_importance, scores,'o-')
plt.xlabel("cumulative feature importance")
plt.ylabel("r2")
st.pyplot(fig)
st.write('---')