質問編集履歴

1

PyTorch公式チュートリアルの具体例に差し替えました

2019/11/06 10:55

投稿

temsoba11
temsoba11

スコア5

test CHANGED
File without changes
test CHANGED
@@ -1,10 +1,10 @@
1
- 基礎的な質問かもれませんがよろしくお願ます。
1
+ PyTorchを使って機械学習の勉強をいます。pythonの学習も最近始めたばかりです。
2
2
 
3
- Pytorchを使っ機械学習勉強をしていまpythonの学習最近始めたばかりです。
4
-
5
- 以下のようなソースコードでデータxが与えられて時、model = Model(x)のようにインスタンスが作られると思うのですが、なぜxがforward関数に渡されるのでしょうか?クラスのインスタンスの引数は_init_に渡されると思うのですが、nn.Moduleのソースではinitは引数がselfだけでよくわからなかったです。
3
+ 以下のPytorchのtutorialのコードでNet()のインスタンスnet作成し、引数にinputを渡しいると思いますが、なぜこれがforward関数に渡されるょうか?インスタンスの引数は_init_に渡されると思いますが、Netもnn.Moduleも_init_の引数にselfしか持っおらず、どうう仕組みなのか全くわかりせんPython素人なで基礎的な質問かしれませんがよろしくお願いします。
6
4
 
7
5
 
6
+
7
+ [PyTorchのtutorial](https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html)
8
8
 
9
9
 
10
10
 
@@ -16,28 +16,90 @@
16
16
 
17
17
  ```python
18
18
 
19
+ import torch
20
+
19
21
  import torch.nn as nn
20
22
 
21
23
  import torch.nn.functional as F
22
24
 
23
25
 
24
26
 
27
+
28
+
25
- class Model(nn.Module):
29
+ class Net(nn.Module):
30
+
31
+
26
32
 
27
33
  def __init__(self):
28
34
 
29
- super(Model, self).__init__()
35
+ super(Net, self).__init__()
30
36
 
31
- self.conv1 = nn.Conv2d(1, 20, 5)
37
+ # 1 input image channel, 6 output channels, 3x3 square convolution
32
38
 
39
+ # kernel
40
+
41
+ self.conv1 = nn.Conv2d(1, 6, 3)
42
+
33
- self.conv2 = nn.Conv2d(20, 20, 5)
43
+ self.conv2 = nn.Conv2d(6, 16, 3)
44
+
45
+ # an affine operation: y = Wx + b
46
+
47
+ self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
48
+
49
+ self.fc2 = nn.Linear(120, 84)
50
+
51
+ self.fc3 = nn.Linear(84, 10)
34
52
 
35
53
 
36
54
 
37
55
  def forward(self, x):
38
56
 
39
- x = F.relu(self.conv1(x))
57
+ # Max pooling over a (2, 2) window
40
58
 
59
+ x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
60
+
61
+ # If the size is a square you can only specify a single number
62
+
63
+ x = F.max_pool2d(F.relu(self.conv2(x)), 2)
64
+
65
+ x = x.view(-1, self.num_flat_features(x))
66
+
67
+ x = F.relu(self.fc1(x))
68
+
41
- return F.relu(self.conv2(x))
69
+ x = F.relu(self.fc2(x))
70
+
71
+ x = self.fc3(x)
72
+
73
+ return x
74
+
75
+
76
+
77
+ def num_flat_features(self, x):
78
+
79
+ size = x.size()[1:] # all dimensions except the batch dimension
80
+
81
+ num_features = 1
82
+
83
+ for s in size:
84
+
85
+ num_features *= s
86
+
87
+ return num_features
88
+
89
+
90
+
91
+
92
+
93
+ net = Net()
94
+
95
+ print(net)
96
+
97
+
98
+
99
+ input = torch.randn(1, 1, 32, 32)
100
+
101
+ out = net(input)
102
+
103
+ print(out)
42
104
 
43
105
  ```