pytorch
實現卷積神經網路(執行效率相對於keras
慢太多)
import torch
import warnings
import torchvision
from torchvision.datasets import mnist
from torch.utils.data import dataloader
warnings.filterwarnings(
"ignore"
)batch_size =
32train_data = mnist(
root=
'./mnist'
, train=
true
, transform=torchvision.transforms.totensor(),
download=
true
)train_loader = dataloader(dataset=train_data, batch_size=batch_size, shuffle=
true
)test_data = mnist(
root=
'./mnist'
, train=
false
, transform=torchvision.transforms.totensor(),
download=
true
)x_test = torch.unsqueeze(test_data.test_data, dim=1)
.type
(torch.floattensor)[:
2000]/
255.0
y_test = test_data.test_labels[
:2000
]class
model
(torch.nn.module)
:def
__init__
(self)
:super
(model, self)
.__init__(
) self.conv1 = torch.nn.sequential(
torch.nn.conv2d(
# out:(32, 28, 28)
in_channels=1,
out_channels=32,
kernel_size=5,
stride=1,
padding=2)
, torch.nn.relu(),
torch.nn.maxpool2d(stride=
2, kernel_size=2)
,# out:(32, 14, 1
) self.conv2 = torch.nn.sequential(
torch.nn.conv2d(
# out:(64, 14, 14)
in_channels=32,
out_channels=64,
kernel_size=5,
stride=1,
padding=2)
, torch.nn.relu(),
torch.nn.maxpool2d(stride=
2, kernel_size=2)
,# out:(64, 7, 7)
) self.hidden_one = torch.nn.linear(64*
7*7,
120)
self.hidden_two = torch.nn.linear(
120,84)
self.outlayer = torch.nn.linear(84,
10)defforward
(self, x)
: x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(0)
,-1)
x = self.hidden_one(x)
x = self.hidden_two(x)
output = self.outlayer(x)
return output
model = model(
)optimizer = torch.optim.adam(model.parameters(
), lr=1e-
1)# 定義優化器
loss_func = torch.nn.crossentropyloss(
)# 定義損失函式為交叉熵
print
("training-------------------"
)for epoch in
range
(100):
for step,
(x, y)
inenumerate
(train_loader)
: output_train = model(x)
loss = loss_func(output_train, y)
# 計算交叉熵
optimizer.zero_grad(
)# 梯度清零
loss.backward(
)# 實現後向傳播,計算各引數梯度
optimizer.step(
)# 更新各引數的值
if epoch %
10==0:
output_test = model(x_test)
y_pre = output_test.argmax(dim=1)
accuracy =
sum(y_pre == y_test)
/ y_test.size(0)
print
("epoch: "
, epoch,
"------>train loss: %.4f"
% loss.detach(
).numpy(),
"------->test accuracy: %.4f"
% accuracy.numpy(
))
這裡有padding公式,pytorch是在tensor的四周全填0,而padding的數值代表填幾層
pytorch的padding的理解和操作
求解padding的值實際就是解個一元一次方程。
PyTorch 深度學習 筆記
方差 偏差 線性回歸來確定兩種或兩種以上變數間相互依賴的定量關係。線性回歸對於輸入x和輸出y有乙個對映 類似ax b 而我們是訓練a b這兩個引數。以下 使用pytorch建立乙個線性的模型來對其進行擬合,即訓練過程。def linear ex x np.random.rand 256 noise ...
深度學習 Pytorch學習筆記(一)
pytorch中需要自己定義網路模型,該模型需要封裝到乙個自定義的類中,該類只是乙個子類,其繼承的父類為torch.nn.module,可見如下樹形結構圖 module實際又是繼承了object類,關於為什麼要繼承object類有興趣的可以看這篇部落格mro演算法 也就是說,自定義的模型除了要有 i...
pytorch 深度學習
pytorch深度學習實踐 訓練集 開發集 模型評估 測試集。f x wx b f x wx b f x w x bloss 乙個樣本 cost mean square error training set 區域性最優,不一定全域性最優。鞍點 梯度為0,但無法繼續迭代。w w c ost ww w ...