PHP头条
热点:

pytorch如何实现CNN卷积神经网络 pytorch实现CNN卷积神经网络代码


本篇文章小编给大家分享一下pytorch实现CNN卷积神经网络代码,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

卷积神经网络是时下最为流行的一种深度学习网络,由于其具有局部感受野等特性,让其与人眼识别图像具有相似性,因此被广泛应用于图像识别中。

对一维信号,通常采取的方法有两种,第一,直接对其做一维卷积,第二,反映到时频图像上,这就变成了图像识别。

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt
`EPOCH = 1
BATCH_SIZE = 50
LR = 0.001
DOWNLOAD_MNIST = True

从网上下载数据集:

```python
train_data = torchvision.datasets.MNIST(
  root="./mnist/",
  train = True,
  transform=torchvision.transforms.ToTensor(),
  download = DOWNLOAD_MNIST,
)

print(train_data.train_data.size())
print(train_data.train_labels.size())

```plt.imshow(train_data.train_data[0].numpy(), cmap='autumn')
plt.title("%i" % train_data.train_labels[0])
plt.show()

train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)

test_data = torchvision.datasets.MNIST(root="./mnist/", train=False)
test_x = torch.unsqueeze(test_data.test_data, dim=1).type(torch.FloatTensor)[:2000]/255.

test_y = test_data.test_labels[:2000]


class CNN(nn.Module):
  def __init__(self):
    super(CNN, self).__init__()
    self.conv1 = nn.Sequential(
      nn.Conv2d(
        in_channels=1,
        out_channels=16,
        kernel_size=5,
        stride=1,
        padding=2,
      ),
      
      nn.ReLU(),
      nn.MaxPool2d(kernel_size=2),
    )
    
    self.conv2 = nn.Sequential(
      nn.Conv2d(16, 32, 5, 1, 2),
      nn.ReLU(),
      nn.MaxPool2d(2),
    )
    
    self.out = nn.Linear(32*7*7, 10) # fully connected layer, output 10 classes
    
  def forward(self, x):
    x = self.conv1(x)
    x = self.conv2(x)
    x = x.view(x.size(0), -1) # flatten the output of conv2 to (batch_size, 32*7*7)
    output = self.out(x)
    return output
 
optimizer = torch.optim.Adam(cnn.parameters(), lr=LR)
loss_func = nn.CrossEntropyLoss()
 
 from matplotlib import cm
try: from sklearn.manifold import TSNE; HAS_SK = True
except: HAS_SK = False; print('Please install sklearn for layer visualization')
def plot_with_labels(lowDWeights, labels):
  plt.cla()
  X, Y = lowDWeights[:, 0], lowDWeights[:, 1]
  for x, y, s in zip(X, Y, labels):
    c = cm.rainbow(int(255 * s / 9)); plt.text(x, y, s, backgroundcolor=c, fontsize=9)
  plt.xlim(X.min(), X.max()); plt.ylim(Y.min(), Y.max()); plt.title('Visualize last layer'); plt.show(); plt.pause(0.01)

plt.ion()

for epoch in range(EPOCH):
  for step, (b_x, b_y) in enumerate(train_loader):
    output = cnn(b_x)
    loss = loss_func(output, b_y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    
    if step % 50 == 0:
      test_output = cnn(test_x)
      pred_y = torch.max(test_output, 1)[1].data.numpy()
      accuracy = float((pred_y == test_y.data.numpy()).astype(int).sum()) / float(test_y.size(0))
      print("Epoch: ", epoch, "| train loss: %.4f" % loss.data.numpy(), 
         "| test accuracy: %.2f" % accuracy)
      
plt.ioff()

www.phpzy.comtrue/php/37401.htmlTechArticlepytorch如何实现CNN卷积神经网络 pytorch实现CNN卷积神经网络代码 本篇文章小编给大家分享一下pytorch实现CNN卷积神经网络代码,小编觉得挺不错的,现在分享给大家供大家参考,有需要的...

相关文章

    暂无相关文章

PHP之友评论

今天推荐