-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpypls.py
3239 lines (2844 loc) · 135 KB
/
pypls.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
# -*- coding: utf-8 -*-
"""
@author: JiangSu
Email: [email protected]
============================= pypls =============================
Provides
1. PartialLeastSquares(CrossValidation, ValsetValidation, Prediction)
-- CrossValidation, cv
-- ValsetValidation, vv
-- Prediction, predict
++ It should be pointed out that before using 'predict', 'cv' or 'vv' must be run first.
Take 'cv' for example, its outputs include 'cv_result' and 'cal_result'.
Assume the DataSet consists of 80 spectra, 700 wavelength points, the max num of latent variable is 5.
The cal_result's outputs are as following:
'cal_result' including:
'b': (回归系数,(700,5))
't2_limit': (t2阈值,(6,5))
'leverage_limit': (杠杆值阈值,(5,))
'q_limit': (Q残差阈值,(6,5),最后一列nan)
't_critical_value': (y学生化残差阈值,(6,5))
'r2': (决定系数R2,(5,))
'press': (预测残差平方和,(5,))
'rmsec': (RMSEC校正均方根误差,(5,))
'sec': (SEC校正标准偏差,(5,))
'rpd': (RPD,(5,))
'bias': (Bias,(5,))
'x_loadings': (X载荷,(700,5))
'x_scores_weights': (X权重,(700,5))
'linear_regression_coefficient': (包含斜率Slope和截距Offset,(2,5))
'fitting_x_list': (list, 每个元素代表1个隐变量下的拟合光谱矩阵)
'residual_matrix_list': (list, 每个元素代表1个隐变量下的残差光谱矩阵)
'fit_value': (拟合值,(80,5))
'y_residual': (拟合残差,(80,5))
'x_residual': (X残差,(80,5))
't2': (T2,(80,5))
'leverage': (Leverage,(80,5))
'x_scores': (X得分,(80,5))
'x_fvalue': (X残差F分布统计量,(80,5))
'x_fprob': (X残差F分布累积概率值,(80,5))
'y_fvalue': (y残差F分布统计量,(80,5))
'y_fprob': (y残差F分布累积概率值,(80,5))
'y_tvalue': (y学生化残差,(80,5)) # 学生化残差
'x_sample_residuals': (80,5)
'x_variable_residuals': (700,5)
'x_total_residuals': (1,5)
'explained_x_sample_variance': (80,5)
'explained_x_variable_variance': (700,5)
'explained_x_total_variance': (1,5)
'explained_x_variance_ratio': (1,5)
'x_outlier_indices_list':
'y_outlier_indices_list':
'just_x_outlier_list':
'just_y_outlier_list':
'both_xy_outlier_list':
2. Three PLS Algorithm:
-- Improved Kernel Partial Least Squares, IKPLS
-- Nonlinear Iterative Partial Least Squares,NIPALS
-- Straightforward Implementation of a statistically inspired Modification of the Partial Least Squares, SIMPLS
3. Several Sampling Algorithm:
-- montecarlo_sampling
-- ks_sampling(Kennard-Stone)
-- spxy_sampling
4. Several Samples split Algorithm:
-- samples_systematic_split
-- samples_ks_split
-- samples_spxy_split
-- samples_random_split
5. Popular Pretreat methods for Spectroscopy
-- Multiplicative Scatter Correction 多元散射校正, MSC
-- Multiplicative Scatter Correction + Savitzky-Golay 多元散射校正+求导, MSCSG
-- Vector Normalization 矢量归一化, VN
-- Standard Normal Variate transformation 标准正态变换, SNV
-- Eliminate Constant Offset 消除常数偏移量, ECO
-- Subtract Straight Line 减去一条直线, SSL
-- De-Trending 去趋势, DT
-- Min-Max Normalization 最小最大归一化, MMN
-- Savitzky-Golay 平滑与求导, SG
-- SNV + Savitzky-Golay, SNVSG
-- SNV + DT, SNVDT
-- SSL + SG, SSLSG
-- Mean Centering 均值中心化, MC
-- Zscore Standardization 标准化, ZS
"""
import numpy as np
from numpy import diag, cumsum, where, dot, outer, zeros, sqrt, mean, sum, min, square, inner
from numpy.linalg import inv, norm
import scipy.stats as sps
from scipy.spatial.distance import pdist, squareform
# ================ PartialLeastSquares Class (Main)================
class PartialLeastSquares(object):
'''
Including 3 important functions, which are 'cv'(CrossValidation), 'vv'(ValsetValidation) and 'predict'(Prediction).
It should be pointed out that before 'predict', 'cv' or 'vv' must be run first.
'''
def __init__(self,
algorithm='ikpls_algorithm',
max_nlv=10,
pretreat_method1='SG',
pretreat_params1=None,
pretreat_method2='MC',
customized_regions=[[4000,6000], [5000, 8000]]
):
self.algorithm = algorithm
self.max_nlv = max_nlv
self.pretreat_method1 = pretreat_method1
if pretreat_params1 is None:
self.pretreat_params1 = {}
else:
self.pretreat_params1 = pretreat_params1
if pretreat_method1 is None:
self.pretreat_params1 = {}
self.pretreat_method2 = pretreat_method2
self.customized_regions = customized_regions
self.significance_level = [0.001, 0.005, 0.01, 0.05, 0.1, 0.25]
return
def _sec_calc(self, fit_value, reference_value):
'''
只能用于Calibration时,拟合值与参考值。只能用于实例内部
不能用于交叉验证
:param fit_value:
:param reference_value:
:param nlv:
:param ifmc:
:return:
'''
if fit_value.ndim == 1:
fit_value = fit_value[:, np.newaxis] # 如果一维数组,增加至二维数组
if reference_value.ndim == 1:
reference_value = reference_value[:, np.newaxis] # 如果一维数组,增加至二维数组
max_nlv = fit_value.shape[1]
n_samples = reference_value.shape[0]
error = fit_value - reference_value
# Error Sum of Squares(SSE)
press = np.sum(error * error, axis=0)
rmsec = sqrt(press / n_samples)
# Total Sum Of Squares(SST) 总离差平方和
sst = np.sum((reference_value - mean(reference_value)) ** 2)
# Regression Sum of Squares(SSR) (1, 10)
ssr = np.sum((fit_value - mean(reference_value)) ** 2, axis=0)
# SST = SSR + SSE
# r2 = ssr / sst = 1 - sse / sst
# r2 = ssr / sst
r2 = 1 - press / sst
sd = sqrt(sst / (n_samples - 1)) # 参考值的标准偏差
# sd = np.std(reference_value, axis=0, ddof=1)
bias = np.mean(error, axis=0)
# ------------- 数据线性回归(横坐标reference_value, 纵坐标fit_value)
# linear_regression_coefficient (2, max_nlv) slope, intercept
linear_regression_coefficient = zeros((2, max_nlv))
# -------------- 校正标准误差 SEC (Standard Error of Calibration, 与自由度有关)
sec = zeros(self.max_nlv)
for i in range(self.max_nlv):
nlv = i + 1
if self.pretreat_method2 is not None:
df = n_samples - nlv - 1
else:
df = n_samples - nlv
e = error[:, i]
sec_lv = sqrt(np.sum(e * e, axis=0) / df)
sec[i] = sec_lv
reg_coeff = polynomial_fit(reference_value, fit_value[:, i], order=1)['regression_coefficient']
linear_regression_coefficient[:, i] = reg_coeff.ravel()
# ------------ 预测标准误差 SEP (Standard Error of Prediction) refer to OPUS, User friendly
SEP = sqrt((np.sum((error - bias) * (error - bias), axis=0)) / (n_samples - 1))
rpd = sd / SEP
relative_error = np.abs(error) / reference_value
return {'r2': r2, 'rmsec': rmsec, 'sep': SEP, 'sec': sec, 'press': press, 'rpd': rpd, 'bias': bias,
'linear_regression_coefficient': linear_regression_coefficient,
'relative_error': relative_error}
def _spec_target_pretreat(self, spec, target):
# ----------------- pretreat1 -----------------
if self.pretreat_method1 is not None:
self.pretreat4spec1 = eval(self.pretreat_method1.upper())(**self.pretreat_params1) # 类的实例
spec_pretreated1 = self.pretreat4spec1.fit_transform(spec)
else:
self.pretreat4spec1 = 'None'
spec_pretreated1 = spec
# 保存pretreat1预处理完的光谱的mean和stdev 为未知样本的pretreat2预处理做准备
self.calx_pretreated1_mean = np.mean(spec_pretreated1[1:, :], axis=0)
self.calx_pretreated1_stdev = np.std(spec_pretreated1[1:, :] - self.calx_pretreated1_mean, axis=0, ddof=1)
# 保存y的mean和stdev
self.caly_mean = np.mean(target, axis=0)
caly_mc = target - self.caly_mean
self.caly_stdev = np.std(caly_mc, axis=0, ddof=1)
# ----------------- pretreat2 -----------------
if self.pretreat_method2 is not None:
self.pretreat4spec2 = eval(self.pretreat_method2.upper())()
self.pretreat4target = eval(self.pretreat_method2.upper() + '4Data')()
spec_pretreated2 = self.pretreat4spec2.fit_transform(spec_pretreated1)
target_pretreated = self.pretreat4target.fit_transform(target)
else:
self.pretreat4spec2 = 'None'
self.pretreat4target = 'None'
spec_pretreated2 = spec_pretreated1
target_pretreated = target
return spec_pretreated2, target_pretreated
def _spec_pretreat4transform(self, spec_matrix):
if self.pretreat_method1 is not None:
# pretreat4spec1 ---- eval(self.pretreat_method1)(**self.pretreat_params1)
# 实例对象
spec_pretreated1 = self.pretreat4spec1.transform(spec_matrix)
else:
spec_pretreated1 = spec_matrix
if self.pretreat_method2 is not None:
# pretreat4spec2 ---- eval(self.pretreat_method2)(**self.pretreat_params2)
# 实例对象
spec_pretreated2 = self.pretreat4spec2.transform(spec_pretreated1)
else:
spec_pretreated2 = spec_pretreated1
return spec_pretreated2
def _target_inverse_pretreat(self, target):
if self.pretreat_method2 is not None:
target_inverse_pretreated = self.pretreat4target.inverse_transform(target)
else:
target_inverse_pretreated = target
return target_inverse_pretreated
def _spec_target_pretreat_cv(self, spec_cv, target_cv):
# ----------------- pretreat1 -----------------
if self.pretreat_method1 is not None:
self.pretreat4spec1_cv = eval(self.pretreat_method1.upper())(**self.pretreat_params1) # 类的实例
spec_pretreated1_cv = self.pretreat4spec1_cv.fit_transform(spec_cv)
else:
self.pretreat4spec1_cv = 'None'
spec_pretreated1_cv = spec_cv
# 保存pretreat1预处理完的光谱的mean和stdev
self.calx_pretreated1_mean_cv = np.mean(spec_pretreated1_cv[1:, :], axis=0)
self.calx_pretreated1_stdev_cv = np.std(spec_pretreated1_cv[1:, :] - self.calx_pretreated1_mean_cv, axis=0, ddof=1)
# 保存y的mean和stdev
self.caly_mean_cv = np.mean(target_cv, axis=0)
caly_mc_cv = target_cv - self.caly_mean_cv
self.caly_stdev_cv = np.std(caly_mc_cv, axis=0, ddof=1)
# ----------------- pretreat2 -----------------
if self.pretreat_method2 is not None:
self.pretreat4spec2_cv = eval(self.pretreat_method2.upper())()
self.pretreat4target_cv = eval(self.pretreat_method2.upper() + '4Data')()
spec_pretreated2_cv = self.pretreat4spec2_cv.fit_transform(spec_pretreated1_cv)
target_pretreated_cv = self.pretreat4target_cv.fit_transform(target_cv)
else:
self.pretreat4spec2_cv = 'None'
self.pretreat4target_cv = 'None'
spec_pretreated2_cv = spec_pretreated1_cv
target_pretreated_cv = target_cv
return spec_pretreated2_cv, target_pretreated_cv
def _spec_pretreat4transform_cv(self, spec_matrix_cv):
if self.pretreat_method1 is not None:
# pretreat4spec1 ---- eval(self.pretreat_method1)(**self.pretreat_params1)
# 实例对象
spec_pretreated1_cv = self.pretreat4spec1_cv.transform(spec_matrix_cv)
else:
spec_pretreated1_cv = spec_matrix_cv
if self.pretreat_method2 is not None:
# pretreat4spec2 ---- eval(self.pretreat_method2)(**self.pretreat_params2)
# 实例对象
spec_pretreated2_cv = self.pretreat4spec2_cv.transform(spec_pretreated1_cv)
else:
spec_pretreated2_cv = spec_pretreated1_cv
return spec_pretreated2_cv
def _target_inverse_pretreat_cv(self, target_cv):
if self.pretreat_method2 is not None:
target_inverse_pretreated_cv = self.pretreat4target_cv.inverse_transform(target_cv)
else:
target_inverse_pretreated_cv = target_cv
return target_inverse_pretreated_cv
def calibration(self, calset_spec_intersect, calset_target, calset_indices=None):
if calset_target.ndim == 1:
calset_target = calset_target[:, np.newaxis] # 用于多维结果的broadcast计算
calset_ab_intersect = calset_spec_intersect[1:, :]
self.calx_mean = np.mean(calset_ab_intersect, axis=0)
n_samples = calset_ab_intersect.shape[0]
if calset_indices is None:
calset_indices = np.arange(n_samples)
# ------------- 光谱预处理,浓度预处理 -------------
spec, target = self._spec_target_pretreat(calset_spec_intersect, calset_target)
# ------------- 截取波长点 -------------
spec_subset = spec[:, self.variable_indices]
ab_subset = spec_subset[1:, :]
# ------------- 开始PLSR -------------
calplsr = PLSR(self.algorithm, self.max_nlv)
cal_result = calplsr.fit_predict(spec_subset, target)
b = cal_result['b']
fit_value_temp = cal_result['fit_value']
fit_value = self._target_inverse_pretreat(fit_value_temp)
pls_result = cal_result['pls_result']
x_loadings = cal_result['x_loadings']
x_scores = cal_result['x_scores']
x_scores_weights = cal_result['x_scores_weights']
# ------------- 开始统计指标计算 -------------
# -------- 光谱残差
q_result = q_calc(x_loadings, x_scores, ab_subset)
q = q_result['q']
x_residual = sqrt(q_result['q'])
residual_matrix_list = q_result['residual_matrix_list']
fitting_x_list = q_result['fitting_x_list']
x_sample_residuals = q_result['x_sample_residuals']
x_variable_residuals = q_result['x_variable_residuals']
x_total_residuals = q_result['x_total_residuals']
explained_x_sample_variance = q_result['explained_x_sample_variance']
explained_x_variable_variance = q_result['explained_x_variable_variance']
explained_x_total_variance = q_result['explained_x_total_variance']
explained_x_variance_ratio = q_result['explained_x_variance_ratio']
# ---- 计算t2_limit, t_critical_value, q_limit
sl = self.significance_level # 显著性水平
t2_limit = zeros((len(sl), self.max_nlv))
t_critical_value = zeros((len(sl), self.max_nlv)) # y_tvalue 学生化残差的临界值
q_limit = zeros((len(sl), self.max_nlv))
# refer to: Interpreting PLS plots
# The critical value of the Q-residuals are estimated from the eigenvalues of E, as described in Jackson and Mudholkar, 1979.
prevent_invalid_for_nan_warn = np.seterr(invalid='ignore')
eigenvalues_list = []
for lv in range(self.max_nlv):
e = q_result['residual_matrix_list'][lv]
U, S, V = np.linalg.svd(e, full_matrices=False)
eigenvalues_list.append(S ** 2 / (n_samples - 1)) # note the (n_samples - 1) part for unbiased estimate of var
for i in range(self.max_nlv): # 0:5 nlv
for j in range(len(sl)): # 不同显著性水平
# ---- t2_limit ----
nlv = i + 1
# .ppf的参数 q ---- lower tail probability
t2_limit_sl = nlv * (n_samples - 1) / (n_samples - nlv) * sps.f.ppf(1 - sl[j], nlv, n_samples - nlv)
t2_limit[j, i] = t2_limit_sl
# ---- 学生化残差临界值, t_critical_value双尾t检验, t.ppf((1 - sl[j]) / 2, df)
if self.pretreat_method2 is not None:
df = n_samples - nlv - 1
else:
df = n_samples - nlv
t_critical_value_sl = sps.t.ppf(1 - sl[j] / 2, df)
t_critical_value[j, i] = t_critical_value_sl
# ---- q_limit ----
evalues_unused = eigenvalues_list[i]
theta1 = np.sum(evalues_unused)
theta2 = np.sum(evalues_unused ** 2)
theta3 = np.sum(evalues_unused ** 3)
h0 = 1 - (2 * theta1 * theta3) / (3 * theta2 ** 2)
if h0 < 0.001:
h0 = 0.001
# .ppf的参数 q ---- lower tail probability
ca = sps.norm.ppf(1 - sl[j])
h1 = ca * sqrt(2 * theta2 * h0 ** 2) / theta1
h2 = theta2 * h0 * (h0 - 1) / (theta1 ** 2)
# 不同显著性水平
q_limit_sl = theta1 * (1 + h1 + h2) ** (1 / h0)
q_limit[j, i] = q_limit_sl
# -------- Leverage & Hotelling TSquared
leverage_t2_result = leverage_t2_calc(x_scores, x_scores)
leverage = leverage_t2_result['leverage']
leverage_limit = 3 * mean(leverage, axis=0)
t2 = leverage_t2_result['t2']
# x_Fvalue, x_Fprob ---- refer to OPUS
x_fvalue = (n_samples - 1) * x_residual ** 2 / (sum(square(x_residual), axis=0) - x_residual ** 2)
x_fprob = sps.distributions.f.cdf(x_fvalue, 1, n_samples - 1)
# y_Fvalue, y_Fprob ---- refer to OPUS
y_residual = fit_value - calset_target
y_fvalue = (n_samples - 1) * y_residual ** 2 / (sum(square(y_residual), axis=0) - y_residual ** 2)
y_fprob = sps.distributions.f.cdf(y_fvalue, 1, n_samples - 1)
# 计算r2, SEC, press, rpd, bias(全部隐变量)
sec_statistics_result = self._sec_calc(fit_value, calset_target)
r2 = sec_statistics_result['r2']
press = sec_statistics_result['press']
rmsec = sec_statistics_result['rmsec']
sec = sec_statistics_result['sep']
rpd = sec_statistics_result['rpd']
bias = sec_statistics_result['bias']
linear_regression_coefficient = sec_statistics_result['linear_regression_coefficient']
relative_error = sec_statistics_result['relative_error']
# ---- 20190115增加y_tvalue(学生化残差)
prevent_invalid_for_negetive_sqrt = np.seterr(invalid='ignore')
y_tvalue = y_residual / (rmsec * sqrt(1 - leverage))
# ---- outlier detect
outlier_dectect_result = outlier_detect(leverage, leverage_limit, y_fprob, calset_indices)
x_outlier_indices_list = outlier_dectect_result['x_outlier_indices_list']
y_outlier_indices_list = outlier_dectect_result['y_outlier_indices_list']
just_x_outlier_list = outlier_dectect_result['just_x_outlier_list']
just_y_outlier_list = outlier_dectect_result['just_y_outlier_list']
both_xy_outlier_list = outlier_dectect_result['both_xy_outlier_list']
########################## 预测需要 ##########################
# calx_mean, calx_pretreated1_mean, calx_pretreated1_stdev,
# caly_mean, caly_stdev, b, calx_loadings, calx_scores, calx_scores_weights,
# leverage_limit, testset_indices = None
model_parameters = {'pretreat_method1':self.pretreat_method1,
'pretreat_params1':self.pretreat_params1,
'pretreat_method2':self.pretreat_method2,
'calx_mean':self.calx_mean,
'calx_pretreated1_mean':self.calx_pretreated1_mean,
'calx_pretreated1_stdev':self.calx_pretreated1_stdev,
'caly_mean':self.caly_mean,
'caly_stdev':self.caly_stdev,
'b':b,
'calx_loadings':x_loadings,
'calx_scores':x_scores,
'calx_scores_weights':x_scores_weights,
'leverage_limit':leverage_limit,
't2_limit':t2_limit,
'q_limit':q_limit,
'variable_indices':self.variable_indices}
return {'b':b,
'fit_value': fit_value,
'y_residual': y_residual,
'x_residual': x_residual,
'fitting_x_list': fitting_x_list,
'residual_matrix_list': residual_matrix_list,
'x_sample_residuals': x_sample_residuals,
'x_variable_residuals': x_variable_residuals,
'x_total_residuals': x_total_residuals,
'explained_x_sample_variance': explained_x_sample_variance,
'explained_x_variable_variance': explained_x_variable_variance,
'explained_x_total_variance': explained_x_total_variance,
'explained_x_variance_ratio': explained_x_variance_ratio,
'pls_result': pls_result,
't2': t2,
't2_limit':t2_limit,
'leverage': leverage,
'leverage_limit': leverage_limit,
'q': q,
'q_limit': q_limit,
'x_loadings': x_loadings,
'x_scores': x_scores,
'x_scores_weights': x_scores_weights,
'x_fvalue': x_fvalue,
'x_fprob': x_fprob,
'y_fvalue': y_fvalue,
'y_fprob': y_fprob,
'y_tvalue': y_tvalue, # 学生化残差
't_critical_value': t_critical_value, # 学生化残差阈值
'r2': r2,
'press': press,
'rmsec': rmsec,
'sec': sec,
'rpd': rpd,
'bias':bias,
'linear_regression_coefficient': linear_regression_coefficient,
'relative_error': relative_error,
'x_outlier_indices_list': x_outlier_indices_list,
'y_outlier_indices_list': y_outlier_indices_list,
'just_x_outlier_list': just_x_outlier_list,
'just_y_outlier_list': just_y_outlier_list,
'both_xy_outlier_list': both_xy_outlier_list,
'model_parameters':model_parameters}
def cv(self, calset_spec_intersect, calset_target, cv_sampling_method='cv_lpo_systematic_sampling',
sampling_param={'p': 3}, calset_indices=None):
'''
Cross PLSValidation
:return:
'''
if calset_target.ndim == 1:
calset_target = calset_target[:, np.newaxis] # 用于多维结果的broadcast计算
self.cv_sampling_method = cv_sampling_method
self.sampling_param=sampling_param
self.calset_target = calset_target
self.calset_spec_intersect = calset_spec_intersect
self.calset_wavelength_intersect = self.calset_spec_intersect[0, :]
self.calset_ab_intersect = self.calset_spec_intersect[1:, :]
n_cal_samples = self.calset_spec_intersect.shape[0] - 1
if calset_indices is None:
calset_indices = np.arange(n_cal_samples)
# -------- 处理variable_indices (indices针对intersect, 而非全谱) --------
# 手工选择的谱区或BIPLS得到的谱区; 如果是离散的波长点,则事先已经得到
if self.customized_regions is not None:
self.verified_regions = verify_customized_regions(self.calset_wavelength_intersect, self.customized_regions)
self.variable_indices = generate_variable_indices(self.calset_wavelength_intersect, self.customized_regions)
else:
self.customized_regions = [[self.calset_wavelength_intersect[0], self.calset_wavelength_intersect[-1]]]
self.verified_regions = verify_customized_regions(self.calset_wavelength_intersect, self.customized_regions)
self.variable_indices = generate_variable_indices(self.calset_wavelength_intersect, self.customized_regions)
# 处理维数过大的问题
if self.max_nlv > np.min((self.calset_spec_intersect.shape[0] - 1, self.variable_indices.size)):
self.max_nlv = np.min((self.calset_spec_intersect.shape[0] - 1, self.variable_indices.size))
n_variables = self.variable_indices.size
# =========================== Calibration start ===========================
self.cal_result = self.calibration(self.calset_spec_intersect, self.calset_target, calset_indices=calset_indices)
calx_scores = self.cal_result['x_scores']
leverage_limit = self.cal_result['leverage_limit']
# =========================== Calibration end ===========================
# =========================== Cross PLSValidation start ===========================
x = self.calset_ab_intersect
y = self.calset_target
# -------- 交叉验证划分集合 --------
train_indices_list, test_indices_list = eval(self.cv_sampling_method)(n_cal_samples, **self.sampling_param)
n_fold = len(train_indices_list)
cv_predict_value = zeros((n_cal_samples, self.max_nlv)) # 列出所有样本各个维数的预测结果
cv_x_residual = zeros((n_cal_samples, self.max_nlv)) # 列出所有样本各个维数的光谱残差
cv_y_residual = zeros((n_cal_samples, self.max_nlv)) # 列出所有样本各个维数的预测残差
cv_x_scores = zeros((n_cal_samples, self.max_nlv)) # 列出所有样本各个维数的得分
cv_residual_matrix = zeros((self.max_nlv, n_cal_samples, n_variables)) # 三维数组(nlv, m, n)
cv_fitting_x = zeros((self.max_nlv, n_cal_samples, n_variables)) # 三维数组(nlv, m, n)
cv_ab_pretreated = zeros((n_cal_samples, n_variables)) # 存储每个交叉验证中预处理后的样品
cv_q = zeros((n_cal_samples, self.max_nlv))
# ======================== 开始交叉验证 ========================
for i in range(n_fold):
calx_cv, caly_cv = x[train_indices_list[i], :], y[train_indices_list[i]]
valx_cv, valy_cv = x[test_indices_list[i], :], y[test_indices_list[i]]
# --------- 区分了校正子集和预测子集,开始光谱和组分预处理 ---------
calspec_cv = np.vstack((self.calset_wavelength_intersect, calx_cv))
valspec_cv = np.vstack((self.calset_wavelength_intersect, valx_cv))
calspec_cv_pretreated, caly_cv_pretreated = self._spec_target_pretreat_cv(calspec_cv, caly_cv)
valspec_cv_pretreated = self._spec_pretreat4transform_cv(valspec_cv)
# --------- 根据variable indices, 截取波长点, 开始计算 ---------
calspec_subset = calspec_cv_pretreated[:, self.variable_indices]
valspec_subset = valspec_cv_pretreated[:, self.variable_indices]
valx_subset = valspec_subset[1:, :]
sub_plsr = PLSR(algorithm=self.algorithm, max_nlv=self.max_nlv)
sub_plsr.fit(calspec_subset, caly_cv_pretreated) # 只需要fit
sub_pls_result = sub_plsr.pls_result
calx_loadings_cv = sub_pls_result['x_loadings']
# calx_scores_cv = sub_pls_result['x_scores']
calx_scores_weights_cv = sub_pls_result['x_scores_weights']
# --------- val_predict_value_temp 根据pretreat_method2做inverse_transform---------
val_predicte_value_temp = sub_plsr.val_predict(valspec_subset)['predict_value']
val_predict_value = self._target_inverse_pretreat_cv(val_predicte_value_temp)
val_y_residual = val_predict_value - valy_cv
cv_predict_value[test_indices_list[i], :] = val_predict_value
# ---------- 部分统计指标 ----------
val_x_scores = dot(valx_subset, calx_scores_weights_cv)
cv_x_scores[test_indices_list[i], :] = val_x_scores
# ---- 光谱残差
cv_ab_pretreated[test_indices_list[i], :] = valx_subset # 用于计算explained_x_total_variance
val_q_result = q_calc_cv(calx_loadings_cv, val_x_scores, valx_subset)
val_q = val_q_result['q']
val_x_residual = sqrt(val_q_result['q'])
val_residual_matrix_list = val_q_result['residual_matrix_list'] # 等待存储
val_fitting_x_list = val_q_result['fitting_x_list'] # 等待存储
for j in range((self.max_nlv)): # 存入三维数组
cv_residual_matrix[j, test_indices_list[i], :] = val_residual_matrix_list[j]
cv_fitting_x[j, test_indices_list[i], :] = val_fitting_x_list[j]
cv_q[test_indices_list[i], :] = val_q
# ---- 处理 x_residual 与 y_residual
cv_x_residual[test_indices_list[i], :] = val_x_residual
cv_y_residual[test_indices_list[i], :] = val_y_residual
# ---------------- 交叉验证完毕,统一计算 ----------------
# ---- x_variable_residuals 和 x_total_residuals
cv_x_sample_residuals = np.sum(cv_residual_matrix ** 2, axis=2).T / n_variables
cv_x_variable_residuals = np.sum(cv_residual_matrix ** 2, axis=1).T / n_cal_samples # (n_variables, n_lv)
cv_x_total_residuals = np.mean(cv_x_variable_residuals, axis=0, keepdims=True) # (1, n_lv)
cv_explained_x_sample_variance = (1 - cv_x_sample_residuals / \
(np.sum(cv_ab_pretreated ** 2, axis=1, keepdims=True) / n_variables)) * 100
cv_explained_x_variable_variance = (1 - cv_x_variable_residuals.T /
(np.sum(cv_ab_pretreated ** 2, axis=0) / n_cal_samples)) * 100
cv_explained_x_total_variance = (1 - cv_x_total_residuals / np.mean(cv_ab_pretreated ** 2)) * 100
cv_explained_x_variance_ratio = np.hstack((cv_explained_x_total_variance[:, 0:1],
np.diff(cv_explained_x_total_variance)))
# ---- 将 cv_residual_matrix 和 cv_fitting_x 三维数组重新处理成list
cv_residual_matrix_list = [cv_residual_matrix[i, :, :] for i in range(self.max_nlv)]
cv_fitting_x_list = [cv_fitting_x[i, :, :] for i in range(self.max_nlv)]
# ---- Leverage & Hotelling TSquared (20190120 OK)
leverage_t2_result = leverage_t2_calc_cv(cv_x_scores, calx_scores)
cv_leverage = leverage_t2_result['leverage']
cv_t2 = leverage_t2_result['t2']
# 计算x_residual的fvalue和fprob
x_fvalue = (n_cal_samples - 1) * cv_x_residual ** 2 / (
sum(square(cv_x_residual), axis=0) - cv_x_residual ** 2)
x_fprob = sps.distributions.f.cdf(x_fvalue, 1, n_cal_samples - 1)
# 计算y_residual的fvalue和fprob
y_fvalue = (n_cal_samples - 1) * cv_y_residual ** 2 / (
sum(square(cv_y_residual), axis=0) - cv_y_residual ** 2)
y_fprob = sps.distributions.f.cdf(y_fvalue, 1, n_cal_samples - 1)
# 计算r2, rmsecv, press, rpd, bias(全部维数)
rmse_statistics = rmse_calc(cv_predict_value, self.calset_target)
r2 = rmse_statistics['r2']
rmsecv = rmse_statistics['rmse']
secv = rmse_statistics['sep']
press = rmse_statistics['press']
rpd = rmse_statistics['rpd']
bias = rmse_statistics['bias']
linear_regression_coefficient = rmse_statistics['linear_regression_coefficient']
relative_error = rmse_statistics['relative_error']
# ---- 20190128增加y_tvalue(学生化残差)
prevent_invalid_for_negetive_sqrt = np.seterr(invalid='ignore')
y_tvalue = cv_y_residual / (rmsecv * sqrt(1 - cv_leverage)) # 20190128 与 Unscrambler 保持一致, 除以RMSECV
# 推荐维数
min_press = min(press)
press_fvalue = press / min_press
press_fprob = sps.distributions.f.cdf(press_fvalue, n_cal_samples, n_cal_samples)
if np.all(press_fprob >= 0.75):
self.optimal_nlv = self.max_nlv
else:
self.optimal_nlv = np.where(press_fprob < 0.75)[0][0] + 1
optimal_rmsecv = rmsecv[self.optimal_nlv - 1]
# ======== outlier 检测 ========
outlier_dectect_result = outlier_detect(cv_leverage, leverage_limit, y_fprob, calset_indices)
x_outlier_indices_list = outlier_dectect_result['x_outlier_indices_list']
y_outlier_indices_list = outlier_dectect_result['y_outlier_indices_list']
just_x_outlier_list = outlier_dectect_result['just_x_outlier_list']
just_y_outlier_list = outlier_dectect_result['just_y_outlier_list']
both_xy_outlier_list = outlier_dectect_result['both_xy_outlier_list']
# ======== 保存cv结果 ========
cv_result = {'predict_value': cv_predict_value,
'x_residual': cv_x_residual,
'y_residual': cv_y_residual,
'fitting_x_list': cv_fitting_x_list,
'residual_matrix_list': cv_residual_matrix_list,
'x_sample_residuals': cv_x_sample_residuals,
'x_variable_residuals': cv_x_variable_residuals,
'x_total_residuals': cv_x_total_residuals,
'explained_x_sample_variance': cv_explained_x_sample_variance,
'explained_x_variable_variance': cv_explained_x_variable_variance.T,
'explained_x_total_variance': cv_explained_x_total_variance,
'explained_x_variance_ratio': cv_explained_x_variance_ratio,
'leverage': cv_leverage,
't2': cv_t2,
'q': cv_q,
'x_scores': cv_x_scores,
'x_fvalue': x_fvalue,
'x_fprob': x_fprob,
'y_fvalue': y_fvalue,
'y_fprob': y_fprob,
'y_tvalue': y_tvalue, # 学生化残差
'r2': r2,
'rmsecv': rmsecv,
'secv': secv,
'optimal_nlv': self.optimal_nlv,
'optimal_rmsecv': optimal_rmsecv,
'press': press,
'rpd': rpd,
'bias': bias,
'linear_regression_coefficient': linear_regression_coefficient,
'relative_error': relative_error,
'x_outlier_indices_list': x_outlier_indices_list,
'y_outlier_indices_list': y_outlier_indices_list,
'just_x_outlier_list': just_x_outlier_list,
'just_y_outlier_list': just_y_outlier_list,
'both_xy_outlier_list': both_xy_outlier_list}
return {'cv_result': cv_result, 'cal_result': self.cal_result}
def vv(self, calset_spec_intersect, calset_target, valset_spec_intersect, valset_target,
calset_indices=None, valset_indices=None):
'''
Valset PLSValidation, 利用校正集校正,预测验证集,得出最佳nlv
:return:
'''
if calset_target.ndim == 1:
calset_target = calset_target[:, np.newaxis] # 用于多维结果的broadcast计算
if valset_target.ndim == 1:
valset_target = valset_target[:, np.newaxis] # 用于多维结果的broadcast计算
self.calset_target = calset_target
self.valset_target = valset_target
self.calset_spec_intersect = calset_spec_intersect
self.calset_wavelength_intersect = self.calset_spec_intersect[0, :]
self.calset_ab_intersect = self.calset_spec_intersect[1:, :]
self.valset_spec_intersect = valset_spec_intersect
self.valset_wavelength_intersect = self.valset_spec_intersect[0, :]
self.valset_ab_intersect = self.valset_spec_intersect[1:, :]
# -------- 处理variable_indices (indices针对intersect, 而非全谱) --------
if self.customized_regions is not None:
self.verified_regions = verify_customized_regions(self.calset_wavelength_intersect, self.customized_regions)
self.variable_indices = generate_variable_indices(self.calset_wavelength_intersect, self.customized_regions)
else:
self.customized_regions = [[self.calset_wavelength_intersect[0], self.calset_wavelength_intersect[-1]]]
self.verified_regions = verify_customized_regions(self.calset_wavelength_intersect, self.customized_regions)
self.variable_indices = generate_variable_indices(self.calset_wavelength_intersect, self.customized_regions)
# 处理维数过大的问题
if self.max_nlv > np.min((self.calset_spec_intersect.shape[0] - 1, self.variable_indices.size)):
self.max_nlv = np.min((self.calset_spec_intersect.shape[0] - 1, self.variable_indices.size))
# =========================== Calibration start ===========================
self.cal_result = self.calibration(self.calset_spec_intersect, self.calset_target, calset_indices=calset_indices)
leverage_limit = self.cal_result['leverage_limit']
calx_loadings = self.cal_result['x_loadings']
calx_scores = self.cal_result['x_scores']
calx_scores_weights = self.cal_result['x_scores_weights']
b = self.cal_result['b']
# =========================== Calibration end ===========================
# =========================== Valset PLSValidation start ===========================
n_val_samples = self.valset_ab_intersect.shape[0]
# ------------------ 验证集光谱预处理 ------------------
valspec_pretreated = self._spec_pretreat4transform(self.valset_spec_intersect)
# --------- 根据variable indices, 截取波长点 ---------
valspec_subset = valspec_pretreated[:, self.variable_indices]
valx_subset = valspec_subset[1:, :]
# --------- 开始预测 ---------
val_predicte_value_temp = dot(valx_subset, b)
val_predict_value = self._target_inverse_pretreat(val_predicte_value_temp)
val_y_residual = val_predict_value - self.valset_target
# ---------- 统计指标 ----------
val_x_scores = dot(valx_subset, calx_scores_weights)
# -------- Leverage & Hotelling TSquared
leverage_t2_result = leverage_t2_calc(val_x_scores, calx_scores)
val_leverage = leverage_t2_result['leverage']
val_t2 = leverage_t2_result['t2']
if n_val_samples < 2:
# 保存vv结果
vv_result = {'predict_value': val_predict_value,
'x_scores': val_x_scores,
'leverage': val_leverage,
't2': val_t2,
'y_residual': val_y_residual}
else:
# --------------- 验证完毕,统一计算 ---------------
# ---- 光谱残差
val_q_result = q_calc(calx_loadings, val_x_scores, valx_subset)
val_q = val_q_result['q']
val_f_residuals = val_q_result['f_residuals']
val_x_residual = sqrt(val_q_result['q'])
val_residual_matrix_list = val_q_result['residual_matrix_list']
val_fitting_x_list = val_q_result['fitting_x_list']
val_x_sample_residuals = val_q_result['x_sample_residuals']
val_x_variable_residuals = val_q_result['x_variable_residuals']
val_x_total_residuals = val_q_result['x_total_residuals']
val_explained_x_sample_variance = val_q_result['explained_x_sample_variance']
val_explained_x_variable_variance = val_q_result['explained_x_variable_variance']
val_explained_x_total_variance = val_q_result['explained_x_total_variance']
val_explained_x_variance_ratio = val_q_result['explained_x_variance_ratio']
# ---- 计算x_residual的fvalue和fprob
x_fvalue = (n_val_samples - 1) * val_x_residual ** 2 / (sum(square(val_x_residual), axis=0) - val_x_residual ** 2)
x_fprob = sps.distributions.f.cdf(x_fvalue, 1, n_val_samples - 1)
# 计算y_residual的fvalue和fprob
y_fvalue = (n_val_samples - 1) * val_y_residual ** 2 / (sum(square(val_y_residual), axis=0) - val_y_residual ** 2)
y_fprob = sps.distributions.f.cdf(y_fvalue, 1, n_val_samples - 1)
# 计算r2, rmsecv, press, rpd, bias(全部维数)
rmse_statistics = rmse_calc(val_predict_value, self.valset_target)
r2 = rmse_statistics['r2']
rmsep = rmse_statistics['rmse']
sep = rmse_statistics['sep']
press = rmse_statistics['press']
rpd = rmse_statistics['rpd']
bias = rmse_statistics['bias']
linear_regression_coefficient = rmse_statistics['linear_regression_coefficient']
relative_error = rmse_statistics['relative_error']
# ---- 20190128增加y_tvalue(学生化残差)
prevent_invalid_for_negetive_sqrt = np.seterr(invalid='ignore')
y_tvalue = val_y_residual / (rmsep * sqrt(1 - val_leverage)) # 20190128 与 Unscrambler 保持一致, 除以RMSEP
# 推荐维数
min_press = min(press)
press_fvalue = press / min_press
press_fprob = sps.distributions.f.cdf(press_fvalue, n_val_samples, n_val_samples)
if np.all(press_fprob >= 0.75) :
self.optimal_nlv = self.max_nlv
else:
self.optimal_nlv = np.where(press_fprob < 0.75)[0][0] + 1
optimal_rmsep = rmsep[self.optimal_nlv - 1]
# ======== outlier 检测 ========
outlier_dectect_result = outlier_detect(val_leverage, leverage_limit, y_fprob, valset_indices)
x_outlier_indices_list = outlier_dectect_result['x_outlier_indices_list']
y_outlier_indices_list = outlier_dectect_result['y_outlier_indices_list']
just_x_outlier_list = outlier_dectect_result['just_x_outlier_list']
just_y_outlier_list = outlier_dectect_result['just_y_outlier_list']
both_xy_outlier_list = outlier_dectect_result['both_xy_outlier_list']
# 保存vv结果
vv_result = {'predict_value': val_predict_value,
'x_scores': val_x_scores,
'leverage': val_leverage,
't2': val_t2,
'q': val_q,
'val_f_residuals': val_f_residuals,
'y_residual': val_y_residual,
'x_residual': val_x_residual,
'fitting_x_list': val_fitting_x_list,
'residual_matrix_list': val_residual_matrix_list,
'x_sample_residuals': val_x_sample_residuals,
'x_variable_residuals': val_x_variable_residuals,
'x_total_residuals': val_x_total_residuals,
'explained_x_sample_variance': val_explained_x_sample_variance,
'explained_x_variable_variance': val_explained_x_variable_variance,
'explained_x_total_variance': val_explained_x_total_variance,
'explained_x_variance_ratio': val_explained_x_variance_ratio,
'x_fvalue': x_fvalue,
'x_fprob': x_fprob,
'y_fvalue': y_fvalue,
'y_fprob': y_fprob,
'y_tvalue': y_tvalue, # 学生化残差
'r2': r2,
'rmsep': rmsep,
'sep': sep,
'optimal_nlv': self.optimal_nlv,
'optimal_rmsep': optimal_rmsep,
'press': press,
'rpd': rpd,
'bias': bias,
'linear_regression_coefficient': linear_regression_coefficient,
'relative_error': relative_error,
'x_outlier_indices_list': x_outlier_indices_list,
'y_outlier_indices_list': y_outlier_indices_list,
'just_x_outlier_list': just_x_outlier_list,
'just_y_outlier_list': just_y_outlier_list,
'both_xy_outlier_list': both_xy_outlier_list,
'residual_matrix_list': val_residual_matrix_list,
'fitting_x_list': val_fitting_x_list}
return {'vv_result': vv_result, 'cal_result': self.cal_result}
def predict(self, testset_spec_intersect, nlv=None, testset_indices=None, testset_target=None):
if nlv is None:
self.nlv = self.optimal_nlv
else:
self.nlv = nlv
self.testset_spec_intersect = testset_spec_intersect
n_test_samples = self.testset_spec_intersect.shape[0] - 1
# --------- 根据隐变量数,生成预测所需参数 ---------
model_parameters = self.cal_result['model_parameters']
b = model_parameters['b'][:, self.nlv - 1]
calx_loadings = model_parameters['calx_loadings'][:, :self.nlv] # 保存0 ~ opt_nlv-1
calx_scores = model_parameters['calx_scores'][:, :self.nlv] # 保存0 ~ opt_nlv-1
calx_scores_weights = model_parameters['calx_scores_weights'][:, :self.nlv] # 保存0 ~ opt_nlv-1
leverage_limit = model_parameters['leverage_limit'][self.nlv - 1] # 保存0 ~ opt_nlv-1
if b.ndim == 1:
b = b[:, np.newaxis]
if testset_indices is None:
testset_indices = np.arange(n_test_samples)
# --------- 测试集光谱预处理 ---------
testspec_pretreated = self._spec_pretreat4transform(self.testset_spec_intersect)
# --------- 根据variable indices, 截取波长点 ---------
testspec_subset = testspec_pretreated[:, self.variable_indices]
testx_subset = testspec_subset[1:, :]
# --------- 开始预测 ---------
predicte_value_temp = dot(testx_subset, b)
predict_value = self._target_inverse_pretreat(predicte_value_temp)
# ===================== 统计指标 =====================
test_x_scores = dot(testx_subset, calx_scores_weights)
# ---- Leverage & Hotelling TSquared leverage_t2_calc(scores, x_scores)
leverage_t2_result = leverage_t2_calc(test_x_scores, calx_scores)
leverage = leverage_t2_result['leverage'][:, -1:]
t2 = leverage_t2_result['t2'][:, -1:]
if testset_target is None or n_test_samples < 2:
return {'predict_value': predict_value,
'x_scores': test_x_scores,
't2': t2,
'leverage': leverage}
else:
# ---- 光谱残差
test_q_result = q_calc(calx_loadings, test_x_scores, testx_subset)
fitting_x_matrix = test_q_result['fitting_x_list'][-1] # 提取最后1个元素
residual_matrix = test_q_result['residual_matrix_list'][-1] # 提取最后1个元素 (n_test_samples, n_variables)
test_q = test_q_result['q'][:, -1:]
test_x_residual = sqrt(test_q_result['q'][:, -1:]) # 提取最后1列
if testset_target.ndim == 1:
testset_target = testset_target[:, np.newaxis]
# ---- x_fvalue and x_fprob
x_fvalue = (n_test_samples - 1) * test_x_residual ** 2 / \
(sum(square(test_x_residual), axis=0) - test_x_residual ** 2)
x_fprob = sps.distributions.f.cdf(x_fvalue, 1, n_test_samples - 1)
# ---- leverage_limit
x_outlier_indices = testset_indices[np.where(leverage > leverage_limit)[0]]
# ---- 计算y_residual的fvalue和fprob
test_y_residual = predict_value - testset_target
y_fvalue = (n_test_samples - 1) * test_y_residual ** 2 / (
sum(square(test_y_residual), axis=0) - test_y_residual ** 2)
y_fprob = sps.distributions.f.cdf(y_fvalue, 1, n_test_samples - 1)
y_outlier_indices = testset_indices[np.where(abs(y_fprob) > 0.99)[0]]
# ---- 各种统计量
rmse_statistics = rmse_calc(predict_value, testset_target)
r2 = rmse_statistics['r2']
rmsep = rmse_statistics['rmse']
sep = rmse_statistics['sep'] # A bias corrected version of rmsep
press = rmse_statistics['press']
rpd = rmse_statistics['rpd']
bias = rmse_statistics['bias']
linear_regression_coefficient = rmse_statistics['linear_regression_coefficient']
relative_error = rmse_statistics['relative_error']
# ---- 20190128增加y_tvalue(学生化残差)
prevent_invalid_for_negetive_sqrt = np.seterr(invalid='ignore')
y_tvalue = test_y_residual / (rmsep * sqrt(1 - leverage))
# 采用t检验方法确定验证集的预测值与相应的已知参考数据是否有统计意义上的偏差
significant_difference_tvalue = np.abs(bias) * sqrt(n_test_samples) / sep
# 95% sl=0.05 双边检验
significant_difference_critical_value = np.array([sps.t.ppf(0.975, n_test_samples)])
# 配对t检验 paired_test_pvalue > 0.05 则无显著性差异
paired_ttest_statistic, paired_ttest_pvalue = sps.ttest_rel(predict_value, testset_target)
return {'predict_value': predict_value,
'x_scores': test_x_scores,
'leverage': leverage,
't2': t2,
'q': test_q,
'x_residual': test_x_residual,
'fitting_x_list': fitting_x_matrix,
'residual_matrix_list': residual_matrix,
'x_fvalue': x_fvalue,
'x_fprob': x_fprob,
'x_outlier_indices': x_outlier_indices,
'y_fvalue': y_fvalue,
'y_fprob': y_fprob,
'y_tvalue': y_tvalue, # 学生化残差
'y_outlier_indices': y_outlier_indices,
'r2': r2,
'rmsep': rmsep,
'sep': sep,
'press': press,
'rpd': rpd,
'bias': bias,
'linear_regression_coefficient': linear_regression_coefficient,
'relative_error': relative_error,
'significant_difference_tvalue': significant_difference_tvalue,
'significant_difference_critical_value': significant_difference_critical_value,
'paired_ttest_pvalue': paired_ttest_pvalue
}
# +++++++++++++++++++++++++++++++++++++++++++++++ Quantitative Algorithm +++++++++++++++++++++++++++++++++++++++++++++++
def ikpls_algorithm(ab, target, max_nlv):
'''
Improved Kernel Partial Least Squares, IKPLS
:param ab: 光谱吸光度矩阵 (100, 700)
:param target: (100, 1) or (100,)
:param max_nlv:
:return:
b: 回归系数
预测时:dot(ab, pls['b'][:, max_nlv-1] 得到一维数组
预测时:dot(ab, pls['b'][:, max_nlv-1:] 得到二维数组
x_weights: X权重矩阵 w
x_loadings: X载荷矩阵 p
x_scores: X得分矩阵 t
y_loadings: y载荷向量 q
x_scores_weights: X得分矩阵的权重矩阵 r ---- 新样品 T = X r
'''
n_samples, n_variables = ab.shape
if n_samples != target.shape[0]:
raise ValueError('光谱数量与参考值数量不一致!')
if max_nlv > np.min((n_samples, n_variables)):
max_nlv = np.min((n_samples, n_variables))
x_scores = zeros((n_samples, max_nlv))
x_loadings = zeros((n_variables, max_nlv))
y_loadings = zeros((1, max_nlv))
x_weights = zeros((n_variables, max_nlv))
x_scores_weights = zeros((n_variables, max_nlv))
xy = dot(ab.T, target).ravel()
for i in range(max_nlv): # 0,1,2,3,4