00001 import chainer 00002 import chainer.functions as F 00003 import chainer.links as L 00004 00005 00006 class VGG16(chainer.Chain): 00007 00008 def __init__(self, n_class): 00009 super(VGG16, self).__init__( 00010 conv1_1=L.Convolution2D(3, 64, 3, stride=1, pad=1), 00011 conv1_2=L.Convolution2D(64, 64, 3, stride=1, pad=1), 00012 00013 conv2_1=L.Convolution2D(64, 128, 3, stride=1, pad=1), 00014 conv2_2=L.Convolution2D(128, 128, 3, stride=1, pad=1), 00015 00016 conv3_1=L.Convolution2D(128, 256, 3, stride=1, pad=1), 00017 conv3_2=L.Convolution2D(256, 256, 3, stride=1, pad=1), 00018 conv3_3=L.Convolution2D(256, 256, 3, stride=1, pad=1), 00019 00020 conv4_1=L.Convolution2D(256, 512, 3, stride=1, pad=1), 00021 conv4_2=L.Convolution2D(512, 512, 3, stride=1, pad=1), 00022 conv4_3=L.Convolution2D(512, 512, 3, stride=1, pad=1), 00023 00024 conv5_1=L.Convolution2D(512, 512, 3, stride=1, pad=1), 00025 conv5_2=L.Convolution2D(512, 512, 3, stride=1, pad=1), 00026 conv5_3=L.Convolution2D(512, 512, 3, stride=1, pad=1), 00027 00028 fc6=L.Linear(25088, 4096), 00029 fc7=L.Linear(4096, 4096), 00030 fc8=L.Linear(4096, n_class) 00031 ) 00032 00033 def __call__(self, x, t=None): 00034 h = F.relu(self.conv1_1(x)) 00035 h = F.relu(self.conv1_2(h)) 00036 h = F.max_pooling_2d(h, 2, stride=2) 00037 00038 h = F.relu(self.conv2_1(h)) 00039 h = F.relu(self.conv2_2(h)) 00040 h = F.max_pooling_2d(h, 2, stride=2) 00041 00042 h = F.relu(self.conv3_1(h)) 00043 h = F.relu(self.conv3_2(h)) 00044 h = F.relu(self.conv3_3(h)) 00045 h = F.max_pooling_2d(h, 2, stride=2) 00046 00047 h = F.relu(self.conv4_1(h)) 00048 h = F.relu(self.conv4_2(h)) 00049 h = F.relu(self.conv4_3(h)) 00050 h = F.max_pooling_2d(h, 2, stride=2) 00051 00052 h = F.relu(self.conv5_1(h)) 00053 h = F.relu(self.conv5_2(h)) 00054 h = F.relu(self.conv5_3(h)) 00055 h = F.max_pooling_2d(h, 2, stride=2) 00056 00057 h = F.dropout(F.relu(self.fc6(h)), ratio=0.5) 00058 h = F.dropout(F.relu(self.fc7(h)), ratio=0.5) 00059 h = self.fc8(h) 00060 00061 self.pred = F.softmax(h) 00062 if t is None: 00063 assert not chainer.config.train 00064 return 00065 00066 self.loss = F.softmax_cross_entropy(h, t) 00067 self.acc = F.accuracy(h, t) 00068 return self.loss