0%

kaggle菜鸡之旅:Digit Recognizer

一直以来都是看论文跑别人的代码,有时候代码里有些地方绕不过去,所以最近打算把pytorch系统地学一遍,过年的时候朋友圈有同学kaggle拿了个10%,心里也是羡慕,于是借此也开始玩kaggle

第一次玩,挑了最简单的手写数字分类,全部的代码也不多,网络结构没有很复杂,随便叠几层卷积就能有99%以上的准确率,主要感到麻烦的还是数据的读取和结果的输出。还是因为对Variable和Tensor这些不熟练吧。
BTW,发现pytorch构建网络比tensorflow方便太多

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

import torch

from torch import nn

from torch.autograd import Variable as V

import torch.nn.functional as F

import numpy as np

import pandas as pd

import scipy

import time

from tqdm import tqdm





IS_TRAINING = False

SUBMIT = True

torch.manual_seed(1)

EPOCH = 50

BATCH_SIZE = 50

LR = 0.001



TRAIN_DATA = "train.csv"



# torch.set_default_tensor_type("torch.DoubleTensor")



#-----Funtions

# 由于给的数据是csv不是图片,于是我们需要将其转为28*28

def to_image(data):

data = data.view(-1,1,28,28)

return data



def read_data(data_path):

train = pd.read_csv(data_path)

data = train.drop('label',axis=1)

data = data.values

label = train['label'].values


# 将数据分一部分出来作为validation
x = data[1000:,:]

x = torch.from_numpy(x).float()

val_x = data[:1000,:]

val_x = torch.from_numpy(val_x).float()

y = label[1000:]

y = torch.from_numpy(y).long()

val_y = label[:1000]

val_y = torch.from_numpy(val_y).long()

# 网络的输入需要为Variable
return V(x),V(y),V(val_x),val_y



#-----Network Structure

class conv_net(nn.Module):



def __init__(self):

super(conv_net,self).__init__()

self.conv1 = nn.Sequential(

nn.Conv2d(1,10,5,1,1),

nn.MaxPool2d(2),

nn.ReLU(),

nn.BatchNorm2d(10)

)

self.conv2 = nn.Sequential(

nn.Conv2d(10,20,5,1,1),

nn.MaxPool2d(2),

nn.ReLU(),

nn.BatchNorm2d(20) # num_features is channels' number

)

self.fc1 = nn.Sequential(

nn.Linear(500,60),

nn.Dropout(0.5),

nn.ReLU()

)

self.fc2 = nn.Sequential(

nn.Linear(60,20),

nn.Dropout(0.5),

nn.ReLU()

)

self.fc3 = nn.Linear(20,10)



def forward(self, x):

x = self.conv1(x)

x = self.conv2(x)

x = x.view(-1,500)

x = self.fc1(x)

x = self.fc2(x)

x = self.fc3(x)

return x





#-----Prepare Work

train_data_x, train_data_y, val_data_x, val_data_y = read_data(TRAIN_DATA)

train_data_x = to_image(train_data_x)

val_data_x = to_image(val_data_x)





if IS_TRAINING:

model = conv_net().cuda()

loss_function = nn.CrossEntropyLoss() # this should be define before usage

optimizer = torch.optim.Adam(model.parameters(),lr=LR)



for epoch in tqdm(range(EPOCH)):

start = time.time()

index = 0

if epoch%100 == 0:

for param_group in optimizer.param_groups:

LR = LR * 0.95

param_group['lr'] = LR


'''
训练的基本流程:
读入数据
计算loss
清除梯度(因为pytorch梯度默认是累积的)
反向传播
优化器
'''
for i in tqdm(range(int(len(train_data_x)/BATCH_SIZE)),total=int(len(train_data_x)/BATCH_SIZE)):

batch_x = train_data_x[index:index+BATCH_SIZE]

batch_y = train_data_y[index:index+BATCH_SIZE]

batch_x = batch_x.cuda()

batch_y = batch_y.cuda()

output = model(batch_x)

loss = loss_function(output,batch_y)

optimizer.zero_grad()

loss.backward()

optimizer.step()

index += BATCH_SIZE # next batch

# print(loss)



duration = time.time()-start

print('Training duration:%.4f'%duration)



torch.save(model.state_dict(),'trained_model.pth')





#-----Validation

model = conv_net().cpu()

model.load_state_dict(torch.load('trained_model.pth'))

model.eval()

test_output = model(val_data_x)



pred_y = torch.max(test_output, 1)[1].data.squeeze()

result = pred_y - val_data_y

accuracy = float(sum(result == 0)) / float(val_data_y.size(0))

print('Val_Acc: %.4f'%accuracy)



#-----Generate Submission



if SUBMIT:

submission = pd.read_csv("sample_submission.csv")

model.eval()

test = pd.read_csv('test.csv')

test_data = torch.from_numpy(test.values).float()

test_data = to_image(V(test_data))

result = torch.Tensor()

index = 0

for i in tqdm(range(int(test_data.shape[0]/BATCH_SIZE)),total=int(test_data.shape[0]/BATCH_SIZE)):

label_prediction = model(test_data[index:index+BATCH_SIZE])



# If I concat result(an empty tensor) and label_prediction together

# Error will occur ---> TypeError: cat received an invalid combination of arguments - got (tuple, int), but expected one of:

# So make a If/else for the first batch

if index == 0:

result = label_prediction.clone()

else:

result = torch.cat((result,label_prediction),0) # concat two tensor on axis 0

index += BATCH_SIZE



_,submission['Label'] = torch.max(result.data,1) # cover the origin csv_file



submission.to_csv("submission.csv",index=False)