-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCARS.py
219 lines (170 loc) · 5.72 KB
/
CARS.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
# -*- coding: utf-8 -*-
# @Time : 2020/12/12 17:10
# @Author : my_name_is_BUG
# @FileName: CARS.py
# @Software: PyCharm
# @Cnblogs :https://blog.csdn.net/qq2512446791
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager as fm, rcParams
from sklearn.cross_decomposition import PLSRegression
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error
import copy
def PC_Cross_Validation(X, y, pc, cv):
'''
x :光谱矩阵 nxm
y :浓度阵 (化学值)
pc:最大主成分数
cv:交叉验证数量
return :
RMSECV:各主成分数对应的RMSECV
PRESS :各主成分数对应的PRESS
rindex:最佳主成分数
'''
kf = KFold(n_splits=cv)
RMSECV = []
for i in range(pc):
RMSE = []
for train_index, test_index in kf.split(X):
x_train, x_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
pls = PLSRegression(n_components=i + 1)
pls.fit(x_train, y_train)
y_predict = pls.predict(x_test)
RMSE.append(np.sqrt(mean_squared_error(y_test, y_predict)))
RMSE_mean = np.mean(RMSE)
RMSECV.append(RMSE_mean)
rindex = np.argmin(RMSECV)
return RMSECV, rindex
def Cross_Validation(X, y, pc, cv):
'''
x :光谱矩阵 nxm
y :浓度阵 (化学值)
pc:最大主成分数
cv:交叉验证数量
return :
RMSECV:各主成分数对应的RMSECV
'''
kf = KFold(n_splits=cv)
RMSE = []
for train_index, test_index in kf.split(X):
x_train, x_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
pls = PLSRegression(n_components=pc)
pls.fit(x_train, y_train)
y_predict = pls.predict(x_test)
RMSE.append(np.sqrt(mean_squared_error(y_test, y_predict)))
RMSE_mean = np.mean(RMSE)
return RMSE_mean
def CARS_Cloud(X, y, N=50, f=20, cv=10):
p = 0.8
m, n = X.shape
u = np.power((n/2), (1/(N-1)))
k = (1/(N-1)) * np.log(n/2)
cal_num = np.round(m * p)
# val_num = m - cal_num
b2 = np.arange(n)
x = copy.deepcopy(X)
D = np.vstack((np.array(b2).reshape(1, -1), X))
WaveData = []
# Coeff = []
WaveNum =[]
RMSECV = []
r = []
for i in range(1, N+1):
r.append(u*np.exp(-1*k*i))
wave_num = int(np.round(r[i-1]*n))
WaveNum = np.hstack((WaveNum, wave_num))
cal_index = np.random.choice \
(np.arange(m), size=int(cal_num), replace=False)
wave_index = b2[:wave_num].reshape(1, -1)[0]
xcal = x[np.ix_(list(cal_index), list(wave_index))]
#xcal = xcal[:,wave_index].reshape(-1,wave_num)
ycal = y[cal_index]
x = x[:, wave_index]
D = D[:, wave_index]
d = D[0, :].reshape(1,-1)
wnum = n - wave_num
if wnum > 0:
d = np.hstack((d, np.full((1, wnum), -1)))
if len(WaveData) == 0:
WaveData = d
else:
WaveData = np.vstack((WaveData, d.reshape(1, -1)))
if wave_num < f:
f = wave_num
pls = PLSRegression(n_components=f)
pls.fit(xcal, ycal)
beta = pls.coef_
b = np.abs(beta)
b2 = np.argsort(-b, axis=0)
coef = copy.deepcopy(beta)
coeff = coef[b2, :].reshape(len(b2), -1)
# cb = coeff[:wave_num]
#
# if wnum > 0:
# cb = np.vstack((cb, np.full((wnum, 1), -1)))
# if len(Coeff) == 0:
# Coeff = copy.deepcopy(cb)
# else:
# Coeff = np.hstack((Coeff, cb))
rmsecv, rindex = PC_Cross_Validation(xcal, ycal, f, cv)
RMSECV.append(Cross_Validation(xcal, ycal, rindex+1, cv))
# CoeffData = Coeff.T
WAVE = []
# COEFF = []
for i in range(WaveData.shape[0]):
wd = WaveData[i, :]
# cd = CoeffData[i, :]
WD = np.ones((len(wd)))
# CO = np.ones((len(wd)))
for j in range(len(wd)):
ind = np.where(wd == j)
if len(ind[0]) == 0:
WD[j] = 0
# CO[j] = 0
else:
WD[j] = wd[ind[0]]
# CO[j] = cd[ind[0]]
if len(WAVE) == 0:
WAVE = copy.deepcopy(WD)
else:
WAVE = np.vstack((WAVE, WD.reshape(1, -1)))
# if len(COEFF) == 0:
# COEFF = copy.deepcopy(CO)
# else:
# COEFF = np.vstack((WAVE, CO.reshape(1, -1)))
MinIndex = np.argmin(RMSECV)
Optimal = WAVE[MinIndex, :]
boindex = np.where(Optimal != 0)
OptWave = boindex[0]
fig = plt.figure()
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
fonts = 16
plt.subplot(211)
plt.xlabel('蒙特卡洛迭代次数', fontsize=fonts)
plt.ylabel('被选择的波长数量', fontsize=fonts)
plt.title('最佳迭代次数:' + str(MinIndex) + '次', fontsize=fonts)
plt.plot(np.arange(N), WaveNum)
plt.subplot(212)
plt.xlabel('蒙特卡洛迭代次数', fontsize=fonts)
plt.ylabel('RMSECV', fontsize=fonts)
plt.plot(np.arange(N), RMSECV)
# # plt.subplot(313)
# # plt.xlabel('蒙特卡洛迭代次数', fontsize=fonts)
# # plt.ylabel('各变量系数值', fontsize=fonts)
# # plt.plot(COEFF)
# #plt.vlines(MinIndex, -1e3, 1e3, colors='r')
plt.show()
return OptWave
if __name__ == "__main__":
import scipy.io as scio
import pandas as pd
data_path = r"D1.csv"
y_path = r"outlier.csv"
data = pd.read_csv(data_path)
y = pd.read_csv(y_path)
X = data
print(CARS_Cloud(X, y))