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
| import numpy as np import torch from torch import nn, optim from torch.utils.data import Dataset, DataLoader import pandas as pd
from torch.optim.lr_scheduler import StepLR
GLOBAL_MEAN = None GLOBAL_STD = None CLASS_LABELS = ['Class_1', 'Class_2', 'Class_3', 'Class_4', 'Class_5', 'Class_6', 'Class_7', 'Class_8', 'Class_9']
class TrainDataset(Dataset): def __init__(self, filepath): global GLOBAL_MEAN, GLOBAL_STD
df = pd.read_csv(filepath)
x_numpy = df.iloc[:, 1:-1].values.astype(np.float32) GLOBAL_MEAN = x_numpy.mean(axis=0) GLOBAL_STD = x_numpy.std(axis=0) GLOBAL_STD[GLOBAL_STD == 0] = 1 x_numpy = (x_numpy - GLOBAL_MEAN) / GLOBAL_STD self.x_data = torch.from_numpy(x_numpy)
df['ClassId'] = pd.Categorical(df['target'], categories=CLASS_LABELS, ordered=True) df['ClassId'] = df['ClassId'].cat.codes.astype(np.int64) y_numpy = df['ClassId'].values self.y_data = torch.from_numpy(y_numpy)
self.len = self.x_data.shape[0]
def __getitem__(self, index): return self.x_data[index], self.y_data[index]
def __len__(self): return self.len
class TestDataset(Dataset): def __init__(self, filepath): global GLOBAL_MEAN, GLOBAL_STD
df = pd.read_csv(filepath)
x_numpy = df.iloc[:, 1:].values.astype(np.float32)
x_numpy = (x_numpy - GLOBAL_MEAN) / GLOBAL_STD self.x_data = torch.from_numpy(x_numpy)
self.PId = df['id'].values
self.len = self.x_data.shape[0]
def __getitem__(self, index): return self.x_data[index], self.PId[index]
def __len__(self): return self.len
class OttoGroupNet(nn.Module): def __init__(self): super(OttoGroupNet, self).__init__() self.l1 = nn.Linear(93, 128) self.l2 = nn.Linear(128, 64) self.l3 = nn.Linear(64, 64) self.l4 = nn.Linear(64, 9) self.relu = nn.ReLU()
self.dropout1 = nn.Dropout(0.3) self.dropout2 = nn.Dropout(0.3)
def forward(self, x): x = self.dropout1(self.relu(self.l1(x))) x = self.dropout2(self.relu(self.l2(x))) x = self.relu(self.l3(x)) return self.l4(x)
def epoch_train(train_loader, model, criterion, optimizer): model.train() total_loss = 0.0 total_batches = 0 for batch_idx, data in enumerate(train_loader): optimizer.zero_grad() inputs, target = data target_pred = model(inputs) loss = criterion(target_pred, target) loss.backward() optimizer.step() total_loss += loss.item() total_batches += 1
if total_batches > 0: epoch_avg_loss = total_loss / total_batches else: epoch_avg_loss = 0.0 return epoch_avg_loss
def test_inference(my_model, test_loader): """【关键修正】: 在测试集上进行推理,生成 Softmax 概率矩阵用于 Kaggle 提交。""" my_model.eval() all_predictions = [] all_ids = []
print("\n--- 开始在测试集上进行推理 ---")
with torch.no_grad(): for x_data, PId in test_loader: outputs = my_model(x_data)
probabilities = torch.softmax(outputs, dim=1)
all_predictions.append(probabilities.cpu().numpy()) all_ids.append(PId.cpu().numpy())
predictions_matrix = np.vstack(all_predictions)
submission_df = pd.DataFrame(predictions_matrix, columns=CLASS_LABELS) submission_df.insert(0, 'id', np.concatenate(all_ids))
print("--- 推理完成 ---") print(f"生成的预测总数:{len(submission_df)}")
return submission_df
if __name__ == '__main__': train_dataset = TrainDataset(filepath='DataSet/ottoGroup/train.csv') train_loader = DataLoader(dataset=train_dataset, batch_size=64, shuffle=True, num_workers=0)
test_dataset = TestDataset(filepath='DataSet/ottoGroup/test.csv') test_loader = DataLoader(dataset=test_dataset, batch_size=64, shuffle=False, num_workers=0)
NUM_EPOCHS = 100
my_model = OttoGroupNet() criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(my_model.parameters(), lr=0.001, weight_decay=1e-5) print("--- 初始化完成,开始训练 ---")
scheduler = StepLR(optimizer, step_size=5, gamma=0.5)
for epoch_num in range(NUM_EPOCHS): train_loss = epoch_train(train_loader, my_model, criterion, optimizer) print(f"Epoch {epoch_num+1} 平均训练损失: {train_loss:.4f}")
scheduler.step()
submission = test_inference(my_model, test_loader)
submission.to_csv('DataSet/ottoGroup/submission.csv', index=False) print("\n预测结果已保存至 'DataSet/ottoGroup/submission.csv'")
|