問題
對比單個全連接網(wǎng)絡(luò),在卷積神經(jīng)網(wǎng)絡(luò)層的加持下,初始時,整個神經(jīng)網(wǎng)絡(luò)模型的性能是否會更好。
方法
模型設(shè)計
兩層卷積神經(jīng)網(wǎng)絡(luò)(包含池化層),一層全連接網(wǎng)絡(luò)。
-
選擇 5 x 5 的卷積核,輸入通道為 1,輸出通道為 10:
此時圖像矩陣經(jīng)過 5 x 5 的卷積核后會小兩圈,也就是4個數(shù)位,變成 24 x 24,輸出通道為10;
-
選擇 2 x 2 的最大池化層:
此時圖像大小縮短一半,變成 12 x 12,通道數(shù)不變;
-
再次經(jīng)過5 x 5的卷積核,輸入通道為 10,輸出通道為 20:
此時圖像再小兩圈,變成 8*8,輸出通道為20;
-
再次經(jīng)過2 x 2的最大池化層:
此時圖像大小縮短一半,變成 4 x 4,通道數(shù)不變;
-
最后將圖像整型變換成向量,輸入到全連接層中:
輸入一共有 4 x 4 x 20 = 320個元素,輸出為 10.
代碼
準備數(shù)據(jù)集
準備數(shù)據(jù)集
batch_size = 64
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='data’,
train=True,
download=True,
transform=transform)
train_loader = DataLoader(train_dataset,
shuffle=True,
batch_size=batch_size)
test_dataset = datasets.MNIST(root='data',
train=False,
download=True,
transform=transform)
test_loader = DataLoader(test_dataset,
shuffle=False,
batch_size=batch_size)
建立模型
class Net(torch.nn.Module):
def init (self):
super(Net, self).__init__()
self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
self.pooling = torch.nn.MaxPool2d(2)
self.fc = torch.nn.Linear(320, 10)
def forward(self, x):
batch_size = x.size(0)
x = F.relu(self.pooling(self.conv1(x)))
x = F.relu(self.pooling(self.conv2(x)))
x = x.view(batch_size, -1)
x = self.fc(x)
return x
model = Net()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
構(gòu)造損失函數(shù)+優(yōu)化器
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
訓練+測試
def train(epoch):
running_loss = 0.0
for batch_idx, data in enumerate(train_loader, 0):
inputs, target = data
inputs,target=inputs.to(device),target.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, target)
loss.backward()
optimizer.step()
running_loss += loss.item()
if batch_idx % 300 == 299:
print('[%d,%.5d] loss:%.3f' % (epoch + 1, batch_idx + 1, running_loss / 2000))
running_loss = 0.0
def test():
correct=0
total=0
with torch.no_grad():
for data in test_loader:
inputs,target=data
inputs,target=inputs.to(device),target.to(device)
outputs=model(inputs)
_,predicted=torch.max(outputs.data,dim=1)
total+=target.size(0)
correct+=(predicted==target).sum().item()
print('Accuracy on test set:%d %% [%d%d]' %(100*correct/total,correct,total))
if name ==' main ':
for epoch in range(10):
train(epoch)
test()
運行結(jié)果
(1)batch_size:64,訓練次數(shù):10
(2)batch_size:128,訓練次數(shù):10
(3)batch_size:128,訓練次數(shù):10
結(jié)語
對比單個全連接網(wǎng)絡(luò),在卷積神經(jīng)網(wǎng)絡(luò)層的加持下,初始時,整個神經(jīng)網(wǎng)絡(luò)模型的性能顯著提升,準確率最低為96%。在batch_size:64,訓練次數(shù):100情況下,準確率達到99%。下一階在平均池化,3*3卷積核,以及不同通道數(shù)的情況下,探索對模型性能的影響。
-
代碼
+關(guān)注
關(guān)注
30文章
4722瀏覽量
68234 -
數(shù)據(jù)集
+關(guān)注
關(guān)注
4文章
1200瀏覽量
24619 -
卷積神經(jīng)網(wǎng)絡(luò)
+關(guān)注
關(guān)注
4文章
359瀏覽量
11831
發(fā)布評論請先 登錄
相關(guān)推薦
評論