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
| import torch from torch.utils import data as data_ import torchvision import torchvision.transforms as transforms import torch.nn as nn import torch.optim as optim import pandas as pd import numpy as np
epochs = 100
df = pd.read_csv('mnist_train9.csv')
train_data_x = torch.tensor(df.iloc[:, 1:].values/255, dtype=torch.float32)
train_data_y = torch.tensor(pd.get_dummies(df.iloc[:, 0]).values, dtype=torch.float32)
train_data_amount = (len(train_data_x) // 10) * 8
validation_data_x = train_data_x[train_data_amount:] validation_data_y = train_data_y[train_data_amount:]
train_data_x = train_data_x[:train_data_amount] train_data_y = train_data_y[:train_data_amount]
class NeuralNetwork(nn.Module): def __init__(self): super(NeuralNetwork, self).__init__()
self.fc1 = nn.Linear(784, 30) self.fc2 = nn.Linear(30, 28) self.fc3 = nn.Linear(28, 9)
nn.init.normal_(self.fc1.weight, mean=0.0, std=0.1) nn.init.normal_(self.fc2.weight, mean=0.0, std=0.1) nn.init.normal_(self.fc3.weight, mean=0.0, std=0.1)
def forward(self, x): x = x.view(1, 784) x = torch.sigmoid(self.fc1(x)) x = torch.sigmoid(self.fc2(x)) x = self.fc3(x) return torch.softmax(x, dim=1)
class Early_Stop_checker: def __init__(self, patience=1): self.patience = patience self.counter = 0 self.min_validation_loss = float('inf')
def early_stop(self, validation_loss): if validation_loss < self.min_validation_loss: self.min_validation_loss = validation_loss self.counter = 0 elif validation_loss > self.min_validation_loss: self.counter += 1 if self.counter >= self.patience: return True return False
model = NeuralNetwork()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr = 0.01)
early_stop_checker = Early_Stop_checker(patience=3)
for epoch in range(epochs): for i in range(len(train_data_x)): model.train()
optimizer.zero_grad() predict = model(torch.unsqueeze(train_data_x[i], 0))
loss = criterion(predict, torch.unsqueeze(train_data_y[i], 0).argmax(dim=1))
loss.backward() optimizer.step()
with torch.no_grad(): model.eval()
train_loss = 0
for i in range(len(train_data_x)): train_predict = model(torch.unsqueeze(train_data_x[i], 0)) train_loss += criterion(train_predict, torch.unsqueeze(train_data_y[i], 0).argmax(dim=1))
train_loss = train_loss/len(train_data_x)
validation_loss = 0
for i in range(len(validation_data_x)): validation_predict = model(torch.unsqueeze(validation_data_x[i], 0)) validation_loss += criterion(validation_predict, torch.unsqueeze(validation_data_y[i], 0).argmax(dim=1))
validation_loss = validation_loss/len(validation_data_x)
if early_stop_checker.early_stop(validation_loss): print(f"Early stopping at epoch: {epoch} ") break
print("----------------------") print(f"Epoch {epoch + 1}/{epochs}") print(f"Train Loss: {train_loss:.4f}") print(f"Validation Loss: {validation_loss:.4f}") print("----------------------")
train_correct = 0 validation_correct = 0
for i in range(len(train_data_x)): train_predict = model(torch.unsqueeze(train_data_x[i], 0)) _, predicted_label = torch.max(train_predict, 1)
if(predicted_label == torch.argmax(train_data_y[i])): train_correct += 1
for i in range(len(validation_data_x)): validation_predict = model(torch.unsqueeze(validation_data_x[i], 0))
_, predicted_label = torch.max(validation_predict, 1)
if(predicted_label == torch.argmax(validation_data_y[i])): validation_correct += 1
train_accuracy = train_correct / len(train_data_x) validation_accuracy = validation_correct / len(validation_data_x)
print("----------------------") print('Finished Training') print(f"Epoch result {epoch}") print(f"Train Loss: {train_loss:.4f}") print(f"Train Accuracy: {train_accuracy * 100:.2f}%") print(f"Validation Loss: {validation_loss:.4f}") print(f"Validation Accuracy: {validation_accuracy * 100:.2f}%") print("----------------------")
df = pd.read_csv('mnist_test9.csv')
test_data_x = torch.tensor(df.iloc[:, :].values/255, dtype=torch.float32)
test_predict_result = [] classification = [1, 2, 3, 4, 5, 6, 7, 8, 9]
with torch.no_grad(): model.eval() for i in range(len(test_data_x)): test_predict = model(torch.unsqueeze(test_data_x[i], 0)) _, predicted_label = torch.max(test_predict, 1)
test_predict_result.append(classification[predicted_label.numpy().item()])
test_predict_result = pd.DataFrame({'Label': test_predict_result})
test_predict_result.to_csv('test_predict_result.csv', index=False)
PATH = './mnist_nn.pth' torch.save(model.state_dict(), PATH)
|