TShopping

 找回密碼
 註冊
搜索
查看: 400|回復: 0

[教學] python在win pytorch環境多進程報錯 "freeze_support()"

[複製鏈接]
發表於 2023-11-10 12:12:06 | 顯示全部樓層 |閱讀模式
 
Push to Facebook
在測試 mnist 數字辨識時

代碼來源
https://hackmd.io/@Maxlight/SkuYB0w6_#3-hyperparameter

  1. import torch
  2. from torch.utils import data as data_
  3. import torch.nn as nn
  4. from torch.autograd import Variable
  5. import matplotlib.pyplot as plt
  6. import torchvision
  7. import os

  8. EPOCH = 1
  9. BATCH_SIZE = 50
  10. LR = 0.001
  11. DOWNLOAD_MNIST = False

  12. train_data = torchvision.datasets.MNIST(root = './mnist',train = True,transform = torchvision.transforms.ToTensor(),download = DOWNLOAD_MNIST)

  13. print(train_data.train_data.size())
  14. print(train_data.train_labels.size())
  15. plt.ion()
  16. for i in range(11):
  17.   plt.imshow(train_data.train_data[i].numpy(), cmap = 'gray')
  18.   plt.title('%i' % train_data.train_labels[i])
  19.   plt.pause(0.5)
  20. plt.show()

  21. train_loader = data_.DataLoader(dataset = train_data, batch_size = BATCH_SIZE, shuffle = True,num_workers = 2)

  22. test_data = torchvision.datasets.MNIST(root = './mnist/', train = False)
  23. test_x = torch.unsqueeze(test_data.test_data, dim = 1).type(torch.FloatTensor)[:2000]/255.
  24. test_y = test_data.test_labels[:2000]

  25. class CNN(nn.Module):
  26.   def __init__(self):
  27.     super(CNN, self).__init__()
  28.     self.conv1 = nn.Sequential(
  29.         nn.Conv2d(in_channels = 1, out_channels = 16, kernel_size = 5, stride = 1, padding = 2,),# stride = 1, padding = (kernel_size-1)/2 = (5-1)/2
  30.         nn.ReLU(),
  31.         nn.MaxPool2d(kernel_size = 2),
  32.     )
  33.     self.conv2 = nn.Sequential(
  34.         nn.Conv2d(16, 32, 5, 1, 2),
  35.         nn.ReLU(),
  36.         nn.MaxPool2d(2)
  37.     )
  38.     self.out = nn.Linear(32*7*7, 10)

  39.   def forward(self, x):
  40.     x = self.conv1(x)
  41.     x = self.conv2(x)
  42.     x = x.view(x.size(0), -1)
  43.     output = self.out(x)
  44.     return output, x

  45. cnn = CNN()
  46. print(cnn)

  47. optimization = torch.optim.Adam(cnn.parameters(), lr = LR)
  48. loss_func = nn.CrossEntropyLoss()

  49. for epoch in range(EPOCH):
  50.   for step, (batch_x, batch_y) in enumerate(train_loader):
  51.     bx = Variable(batch_x)
  52.     by = Variable(batch_y)
  53.     output = cnn(bx)[0]
  54.     loss = loss_func(output, by)
  55.     optimization.zero_grad()
  56.     loss.backward()
  57.     optimization.step()

  58.     if step % 50 == 0:
  59.         test_output, last_layer = cnn(test_x)
  60.         pred_y = torch.max(test_output, 1)[1].data.numpy()
  61.         accuracy = float((pred_y == test_y.data.numpy()).astype(int).sum()) / float(test_y.size(0))
  62.         print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)

  63. test_output, _ = cnn(test_x[:10])
  64. pred_y = torch.max(test_output, 1)[1].data.numpy()
  65. print(pred_y, 'prediction number')
  66. print(test_y[:10].numpy(), 'real number')
複製代碼


跑一跑出現
  1. "freeze_support()"
複製代碼

python win pytorch 多進程 freeze_support

python win pytorch 多進程 freeze_support


在這行上面增加
  1. for epoch in range(EPOCH):
複製代碼
變成
  1. if __name__ == '__main__':
  2.     for epoch in range(EPOCH):
複製代碼
這樣就正常了

文章出處: NetYea 網頁設計



 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-4-13 13:45 , Processed in 0.055658 second(s), 26 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表