VO2max 特征选择

从 12 个特征中选择出最优组合。

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
# Dataset
class HumanDataset(Dataset):
def __init__(self, features, labels):
self.features = features
self.labels = labels

def __len__(self):
return len(self.features)

def __getitem__(self, index):
item_feature = self.features[index]
item_label = self.labels[index]
return item_feature, item_label

# Net
class MLPNet(torch.nn.Module):
def __init__(self, n_feature, n_hidden1, n_hidden2, n_label):
super(MLPNet, self).__init__()
self.hidden1 = torch.nn.Linear(n_feature, n_hidden1)
self.hidden2 = torch.nn.Linear(n_hidden1, n_hidden2)
self.output = torch.nn.Linear(n_hidden2, n_label)

def forward(self, x):
x = torch.nn.functional.relu(self.hidden1(x))
x = torch.nn.functional.relu(self.hidden2(x))
# 不要分类,直接输出结果
# x = torch.nn.functional.softmax(self.output(x))
x = self.output(x)
return x

方法:

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
def chose_feature():
columns_header = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] # 12 个特征
vo2max_labels = np.zeros((540, 1), dtype=float)
recalls = [] # 召回率
r2s = [] # r2 评分
all_header = [] # 所有特征的组合

cvs_path = '/Users/wonderhoi/Downloads/mipace_mlproject.csv'
df = pd.read_csv(cvs_path)

for item in df.itertuples():
vo2max_labels[[item[0]], :] = item[13] # 按照 index 将 VO2max 放入 labels 中

vo2max_labels = torch.FloatTensor(vo2max_labels)

i = 4 # 选择特征开始数量,这里是 4 到 12
count = 0 # 组合序号
while i < 13:
# 无序排列组合,例如(1, 2, 3)
# [(1, 2), (1, 3), (2, 3)]
headers = list(itertools.combinations(columns_header, i))
for header in headers:
# header = (1, 2)
all_header.append(header)
custom_features = np.zeros((540, i), dtype=float)
count += 1

for item in df.itertuples():
row = []
for j in range(i):
# header[0] = 1
# header[1] = 2
row.append(item[header[j]] if header[j] != 3 else 0 if item[header[j]] == 'Male' else 1)
custom_features[[item[0]], :] = row

# 归一化处理
scaler = Normalizer()
custom_features = scaler.fit_transform(custom_features)
custom_features = torch.FloatTensor(custom_features)

# 把数据集按照 8:2 的比例来划分为训练集和测试集
train_features, \
test_features, \
train_labels, \
test_labels = train_test_split(custom_features, vo2max_labels, test_size=0.2)

train_dataset = HumanDataset(train_features, train_labels)
model = MLPNet(n_feature=i, n_hidden1=64, n_hidden2=32, n_label=1) # ANN
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
loss_func = torch.nn.SmoothL1Loss()
dataloader = DataLoader(train_dataset, batch_size=432, shuffle=True, num_workers=0, pin_memory=True)

for epoch in range(500):
for step, (features, labels) in enumerate(dataloader):
output = model(features)
loss = loss_func(output, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()

predictions = model(test_features)
r2 = r2_score(test_labels.detach(), predictions.detach())
r2s.append(r2)

errors = torch.abs(test_labels - predictions) # 计算预测值与测试 label 的误差
errors = errors / test_labels # 将误差转换成百分比
correct_predictions = (errors <= 5 / 100).float().sum().item() # 统计误差低于 5% 的个数

recall = (len(test_labels) - correct_predictions) / len(test_labels)
recalls.append(recall)
print('组合序号:' + str(count) + ', 召回率:' + str(recall) + ', r2:' + str(r2))

i += 1

max_recalls = heapq.nlargest(10, enumerate(recalls), key=lambda x:x[1])
max_recall_index, max_recall = zip(*max_recalls)

min_recalls = heapq.nsmallest(10, enumerate(recalls), key=lambda x:x[1])
min_recall_index, min_recall = zip(*min_recalls)

max_r2s = heapq.nlargest(10, enumerate(r2s), key=lambda x:x[1])
max_r2_index, max_r2 = zip(*max_r2s)

min_r2s = heapq.nsmallest(10, enumerate(r2s), key=lambda x:x[1])
min_r2_index, min_r2 = zip(*min_r2s)

print('recall指标最坏特征组合:')
print(max_recall)
for i in max_recall_index:
result = []
for item in all_header[i]:
if item == 1 :
result.append('age')
elif item == 2 :
result.append('HRMax')
elif item == 3 :
result.append('gender')
elif item == 4 :
result.append('weight')
elif item == 5 :
result.append('height')
elif item == 6 :
result.append('bmi')
elif item == 7 :
result.append('AmbTemp')
elif item == 8 :
result.append('RHHumidity')
elif item == 9 :
result.append('avgHR')
elif item == 10 :
result.append('MaxSpeed')
elif item == 11 :
result.append('avgRE')
elif item == 12 :
result.append('eSV')
print(result)

print('r2指标最坏特征组合:')
print(min_r2)
for i in min_r2_index:
result = []
for item in all_header[i]:
if item == 1 :
result.append('age')
elif item == 2 :
result.append('HRMax')
elif item == 3 :
result.append('gender')
elif item == 4 :
result.append('weight')
elif item == 5 :
result.append('height')
elif item == 6 :
result.append('bmi')
elif item == 7 :
result.append('AmbTemp')
elif item == 8 :
result.append('RHHumidity')
elif item == 9 :
result.append('avgHR')
elif item == 10 :
result.append('MaxSpeed')
elif item == 11 :
result.append('avgRE')
elif item == 12 :
result.append('eSV')
print(result)

print('recall指标最优特征组合:')
print(min_recall)
for i in min_recall_index:
result = []
for item in all_header[i]:
if item == 1:
result.append('age')
elif item == 2:
result.append('HRMax')
elif item == 3:
result.append('gender')
elif item == 4:
result.append('weight')
elif item == 5:
result.append('height')
elif item == 6:
result.append('bmi')
elif item == 7:
result.append('AmbTemp')
elif item == 8:
result.append('RHHumidity')
elif item == 9:
result.append('avgHR')
elif item == 10:
result.append('MaxSpeed')
elif item == 11:
result.append('avgRE')
elif item == 12:
result.append('eSV')
print(result)

print('r2指标最优特征组合:')
print(max_r2)
for i in max_r2_index:
result = []
for item in all_header[i]:
if item == 1:
result.append('age')
elif item == 2:
result.append('HRMax')
elif item == 3:
result.append('gender')
elif item == 4:
result.append('weight')
elif item == 5:
result.append('height')
elif item == 6:
result.append('bmi')
elif item == 7:
result.append('AmbTemp')
elif item == 8:
result.append('RHHumidity')
elif item == 9:
result.append('avgHR')
elif item == 10:
result.append('MaxSpeed')
elif item == 11:
result.append('avgRE')
elif item == 12:
result.append('eSV')
print(result)

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
import pandas as pd
import numpy as np
import itertools
import heapq
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, Normalizer, MinMaxScaler
import torch
from torch.utils.data import Dataset, DataLoader
from sklearn.metrics import r2_score

if __name__ == '__main__':

chose_feature()

VO2max 特征选择
https://wonderhoi.com/2024/11/12/VO2max-特征选择/
作者
wonderhoi
发布于
2024年11月12日
许可协议