Skip to content

Commit 87226dc

Browse files
Merge pull request apachecn#121 from jiangzhonglian/master
添加 Pytorch版本的cnn + 更新 猫狗识别的描述
2 parents e28faad + ec6bf06 commit 87226dc

4 files changed

Lines changed: 278 additions & 23 deletions

File tree

competitions/getting-started/house-price/README.md

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -56,29 +56,6 @@ import matplotlib.pyplot as plt
5656

5757
### 特征说明
5858

59-
60-
## 步骤:
61-
62-
一. 数据分析
63-
1. 下载并加载数据
64-
2. 总体预览:了解每列数据的含义,数据的格式等
65-
3. 数据初步分析,使用统计学与绘图:初步了解数据之间的相关性,为构造特征工程以及模型建立做准备
66-
67-
二. 特征工程
68-
1. 根据业务,常识,以及第二步的数据分析构造特征工程.
69-
2. 将特征转换为模型可以辨别的类型(如处理缺失值,处理文本进行等)
70-
71-
三. 模型选择
72-
1. 根据目标函数确定学习类型,是无监督学习还是监督学习,是分类问题还是回归问题等.
73-
2. 比较各个模型的分数,然后取效果较好的模型作为基础模型.
74-
75-
四. 模型融合
76-
77-
五. 修改特征和模型参数
78-
1. 可以通过添加或者修改特征,提高模型的上限.
79-
2. 通过修改模型的参数,是模型逼近上限
80-
81-
8259
## 一. 数据分析
8360

8461
### 数据下载和加载
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# **猫和狗**
2+
3+
![](/static/images/competitions/playground/dogs-vs-cats.jpg)
4+
5+
> 注意:[项目规范](/docs/kaggle-quickstart.md)
6+
7+
## 比赛说明
8+
9+
* 在本次比赛中,您将编写一个算法来分类图像是否包含狗或猫。这对人类,狗和猫来说很容易。你的电脑会觉得有点困难。
10+
11+
深蓝在1997年在国际象棋比赛中击败卡斯帕罗夫。
12+
沃森在2011 年击败了Jeopardy最聪明的琐事。
13+
你能否在2013年从米登斯那里告诉菲多?
14+
15+
> Asirra数据集
16+
17+
Web服务通常受到人们解决这个难题的挑战,但这对计算机来说很困难。这样的挑战通常被称为 [CAPTCHA](http://www.captcha.net/) (完全自动公开的图灵测试来告诉计算机和人类)或HIP(人类交互证明)。HIP用于多种用途,例如减少电子邮件和博客垃圾邮件,防止对网站密码进行暴力攻击。
18+
19+
[Asirra](http://research.microsoft.com/en-us/um/redmond/projects/asirra/)(限制访问的动物物种图像识别)是一项HIP,通过询问用户识别猫和狗的照片而工作。这项任务对于计算机来说很难,但研究表明人们可以快速准确地完成任务。许多人甚至认为这很有趣!以下是Asirra界面的一个例子:
20+
21+
Asirra是独一无二的,因为它与全球最大的网站 [Petfinder.com](http://www.petfinder.com/) 合作, 致力于为无家可归的宠物寻找住所。他们向微软研究院提供了超过三百万张猫和狗的图像,由美国各地数千个动物收容所的人员手动分类。Kaggle很幸运能够提供这些数据的一个子集,用于娱乐和研究。
22+
23+
> 图像识别攻击
24+
25+
虽然随机猜测是最简单的攻击形式,但各种形式的图像识别可以让攻击者做出比随机更好的猜测。照片数据库(各种各样的背景,角度,姿势,照明等)具有巨大的多样性,难以进行准确的自动分类。在多年前进行的一项非正式调查中,计算机视觉专家认为,如果没有现有技术的重大进展,精度高于60%的分类器将很困难。作为参考,60%分类器将12幅图像HIP的猜测概率从1/4096提高到1/459。
26+
27+
> 最先进的
28+
29+
目前的文献表明机器分类器可以在这项任务上得到80%以上的准确度[1]。因此,Asirra不再被认为是安全的。我们创建了这个比赛,以针对这个问题对最新的计算机视觉和深度学习方法进行基准测试 你能破解CAPTCHA吗?你能改善艺术状态吗?你能在猫狗之间创造持久的和平吗?
30+
31+
好的,我们会解决前者。
32+
33+
> 致谢
34+
35+
我们感谢微软研究院为此次比赛提供数据。
36+
37+
* Jeremy Elson,John R. Douceur,Jon Howell,Jared Saul,Asirra:在计算机和通信安全(CCS)第14届ACM会议论文集计算机械协会会刊上发表的利用调整手动图像分类的CAPTCHA, 2007年10月
38+
39+
## 参赛成员
40+
41+
* 开源组织: [ApacheCN ~ apachecn.org](http://www.apachecn.org/)
42+
* 参与人员: [片刻](https://github.com/jiangzhonglian)
43+
44+
## 比赛分析
45+
46+
* 回归问题:价格的问题
47+
* 常用算法: `回归``树回归``GBDT``xgboost``lightGBM`
48+
49+
```
50+
步骤:
51+
一. 数据分析
52+
1. 下载并加载数据
53+
2. 总体预览:了解每列数据的含义,数据的格式等
54+
3. 数据初步分析,使用统计学与绘图:初步了解数据之间的相关性,为构造特征工程以及模型建立做准备
55+
56+
二. 特征工程
57+
1.根据业务,常识,以及第二步的数据分析构造特征工程.
58+
2.将特征转换为模型可以辨别的类型(如处理缺失值,处理文本进行等)
59+
60+
三. 模型选择
61+
1.根据目标函数确定学习类型,是无监督学习还是监督学习,是分类问题还是回归问题等.
62+
2.比较各个模型的分数,然后取效果较好的模型作为基础模型.
63+
64+
四. 模型融合
65+
66+
五. 修改特征和模型参数
67+
1.可以通过添加或者修改特征,提高模型的上限.
68+
2.通过修改模型的参数,是模型逼近上限
69+
70+
六. 提交格式
71+
'''(label: 1=dog, 0=cat)
72+
id,label
73+
1,0
74+
2,0
75+
3,0
76+
etc...
77+
'''
78+
```
79+
80+
## 一. 数据分析
81+
82+
### 数据下载和加载
83+
84+
> 数据获取
85+
86+
* 数据集下载地址:<https://www.kaggle.com/c/dogs-vs-cats/data>
87+
88+
> 特征说明
89+
90+
* Dogs vs. Cats是一个传统的二分类问题。
91+
* 训练集包含25000张图片,命名格式为<category>.<num>.jpg, 如cat.10000.jpg、dog.100.jpg
92+
* 测试集包含12500张图片,命名为<num>.jpg,如1000.jpg。
93+
* 参赛者需根据训练集的图片训练模型,并在测试集上进行预测,输出它是狗的概率。
94+
* 最后提交的csv文件如下,第一列是图片的<num>,第二列是图片为狗的概率。
95+
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
#!/usr/bin/python3
2+
# coding: utf-8
3+
'''
4+
Created on 2017-12-18
5+
Update on 2018-03-27
6+
Author: 片刻
7+
Github: https://github.com/apachecn/kaggle
8+
Result:
9+
BATCH_SIZE = 10 and EPOCH = 10; [10, 4000] loss: 0.069
10+
BATCH_SIZE = 10 and EPOCH = 15; [10, 4000] loss: 0.069
11+
'''
12+
# import csv
13+
import pandas as pd
14+
15+
# third-party library
16+
import torch
17+
import torch.nn as nn
18+
from torch.autograd import Variable
19+
from torch.utils.data import Dataset, DataLoader
20+
21+
22+
class CustomedDataSet(Dataset):
23+
def __init__(self, train=True):
24+
self.train = train
25+
if self.train:
26+
trainX = pd.read_csv(
27+
'/opt/data/kaggle/getting-started/digit-recognizer/input/train.csv'
28+
# names=["ImageId", "Label"]
29+
)
30+
trainY = trainX.label.as_matrix().tolist()
31+
trainX = trainX.drop(
32+
'label', axis=1).as_matrix().reshape(trainX.shape[0], 1, 28, 28)
33+
self.datalist = trainX
34+
self.labellist = trainY
35+
else:
36+
testX = pd.read_csv(
37+
'/opt/data/kaggle/getting-started/digit-recognizer/input/test.csv'
38+
)
39+
self.testID = testX.index
40+
testX = testX.as_matrix().reshape(testX.shape[0], 1, 28, 28)
41+
self.datalist = testX
42+
43+
def __getitem__(self, index):
44+
if self.train:
45+
return torch.Tensor(
46+
self.datalist[index].astype(float)), self.labellist[index]
47+
else:
48+
return torch.Tensor(self.datalist[index].astype(float))
49+
50+
def __len__(self):
51+
return self.datalist.shape[0]
52+
53+
54+
train_data = CustomedDataSet()
55+
test_data = CustomedDataSet(train=False)
56+
57+
BATCH_SIZE = 150
58+
train_loader = DataLoader(
59+
dataset=train_data, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)
60+
test_loader = DataLoader(
61+
dataset=test_data, batch_size=BATCH_SIZE, shuffle=False, num_workers=2)
62+
63+
64+
class CNN(nn.Module):
65+
def __init__(self):
66+
super(CNN, self).__init__()
67+
self.conv1 = nn.Sequential( # input shape (1, 28, 28)
68+
nn.Conv2d(
69+
in_channels=1, # input height
70+
out_channels=16, # n_filters
71+
kernel_size=5, # filter size
72+
stride=1, # filter movement/step
73+
padding=2, # if want same width and length of this image after con2d, padding=(kernel_size-1)/2 if stride=1
74+
), # output shape (16, 28, 28)
75+
nn.ReLU(), # activation
76+
nn.MaxPool2d(
77+
kernel_size=2
78+
), # choose max value in 2x2 area, output shape (16, 14, 14)
79+
)
80+
self.conv2 = nn.Sequential( # input shape (1, 14, 14)
81+
nn.Conv2d(16, 32, 5, 1, 2), # output shape (32, 14, 14)
82+
nn.ReLU(), # activation
83+
nn.MaxPool2d(2), # output shape (32, 7, 7)
84+
)
85+
self.out = nn.Linear(32 * 7 * 7,
86+
10) # fully connected layer, output 10 classes
87+
88+
def forward(self, x):
89+
x = self.conv1(x)
90+
x = self.conv2(x)
91+
x = x.view(
92+
x.size(0),
93+
-1) # flatten the output of conv2 to (batch_size, 32 * 7 * 7)
94+
output = self.out(x)
95+
return output, x # return x for visualization
96+
97+
98+
cnn = CNN()
99+
# print(cnn) # net architecture
100+
101+
LR = 0.001 # learning rate
102+
optimizer = torch.optim.Adam(
103+
cnn.parameters(), lr=LR) # optimize all cnn parameters
104+
loss_func = nn.CrossEntropyLoss() # the target label is not one-hotted
105+
106+
# training and testing
107+
print(u'开始训练')
108+
EPOCH = 5 # train the training data n times, to save time, we just train 1 epoch
109+
for epoch in range(EPOCH):
110+
running_loss = 0.0
111+
112+
for step, (x, y) in enumerate(
113+
train_loader
114+
): # gives batch data, normalize x when iterate train_loader
115+
b_x = Variable(x) # batch x
116+
b_y = Variable(y) # batch y
117+
118+
output = cnn(b_x)[0] # 输入训练数据
119+
loss = loss_func(output, b_y) # 计算误差
120+
optimizer.zero_grad() # 清空上一次梯度
121+
loss.backward() # 误差反向传递
122+
optimizer.step() # 优化器参数更新
123+
124+
# 每1000批数据打印一次平均loss值
125+
running_loss += loss.data[
126+
0] # loss本身为Variable类型,所以要使用data获取其Tensor,因为其为标量,所以取0
127+
if step % 500 == 499: # 每2000批打印一次
128+
print('[%d, %5d] loss: %.3f' %
129+
(epoch + 1, step + 1, running_loss / 500))
130+
running_loss = 0.0
131+
print('Finished Training')
132+
133+
# correct = 0
134+
# total = 0
135+
# for img, label in test_loader:
136+
# img = Variable(img, volatile=True)
137+
# label = Variable(label, volatile=True)
138+
139+
# outputs = cnn(img)
140+
# _, predicted = torch.max(outputs[0], 1)
141+
# # print('1-', type(label), '-------', label)
142+
# # print('2-', type(predicted), '-------', predicted)
143+
# total += label.size(0)
144+
# num_correct = (predicted == label).sum()
145+
# correct += num_correct.data[0]
146+
147+
# print('Accuracy of the network on the %d test images: %.3f %%' % (total, 100 * correct / total))
148+
149+
# I just can't throw all of test data into the network,since it was so huge that my GPU memory cann't afford it
150+
ans = torch.LongTensor() # build a tensor to concatenate answers
151+
for img in test_loader:
152+
img = Variable(img)
153+
outputs = cnn(img)
154+
_, predicted = torch.max(outputs[0], 1)
155+
# print('type(predicted) = ', type(predicted), predicted)
156+
ans = torch.cat([ans, predicted.data], 0)
157+
158+
testLabel = ans.numpy() # only tensor on cpu can transform to the numpy array
159+
160+
# # 结果输出保存
161+
# def saveResult(result, csvName):
162+
# with open(csvName, 'w') as myFile:
163+
# myWriter = csv.writer(myFile)
164+
# myWriter.writerow(["ImageId", "Label"])
165+
# index = 0
166+
# for r in result:
167+
# index += 1
168+
# myWriter.writerow([index, int(r)])
169+
170+
# print('Saved successfully...') # 保存预测结果
171+
172+
# saveResult(testLabel,
173+
# '/opt/data/kaggle/getting-started/digit-recognizer/output/Result_pytorch_CNN.csv')
174+
175+
# 提交结果
176+
submission_df = pd.DataFrame(
177+
data={'ImageId': test_data.testID+1,
178+
'Label': testLabel})
179+
# print(submission_df.head(10))
180+
submission_df.to_csv(
181+
'/opt/data/kaggle/getting-started/digit-recognizer/output/Result_pytorch_CNN.csv',
182+
columns=["ImageId", "Label"],
183+
index=False)
53.2 KB
Loading

0 commit comments

Comments
 (0)