当前位置:网站首页>Hands on deep learning (III)
Hands on deep learning (III)
2022-06-25 06:05:00 【Dream memory teacher】





Manual implementation
%matplotlib inline
import random
import torch
from d2l import torch as d2l
def synthetic_data(w, b, num_examples): #@save
""" Generate y=Xw+b+ noise """
X = torch.normal(0, 1, (num_examples, len(w)))
y = torch.matmul(X, w) + b
y += torch.normal(0, 0.01, y.shape)
return X, y.reshape((-1, 1))
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
# These samples are read at random , There is no specific order
random.shuffle(indices)
for i in range(0, num_examples, batch_size):
batch_indices = torch.tensor(
indices[i: min(i + batch_size, num_examples)])
yield features[batch_indices], labels[batch_indices]
def linreg(X, w, b): #@save
""" linear regression model """
return torch.matmul(X, w) + b
def squared_loss(y_hat, y): #@save
""" Mean square loss """
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
def sgd(params, lr, batch_size): #@save
""" Small batch random gradient drop """
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)
batch_size = 10
for X, y in data_iter(batch_size, features, labels):
print(X, '\n', y)
break
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss
for epoch in range(num_epochs):
for X, y in data_iter(batch_size, features, labels):
l = loss(net(X, w, b), y) # X and y Small batch loss
# because l The shape is (batch_size,1), Instead of a scalar .l All elements in are added together ,
# And calculate about [w,b] Gradient of
l.sum().backward()
sgd([w, b], lr, batch_size) # Update the parameter with the gradient of the parameter
with torch.no_grad():
train_l = loss(net(features, w, b), labels)
print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')
print(f'w The estimation error of : {true_w - w.reshape(true_w.shape)}')
print(f'b The estimation error of : {true_b - b}')Using frames
import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l
from torch import nn
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)
def load_array(data_arrays, batch_size, is_train=True): #@save
""" Construct a PyTorch Data iterators """
dataset = data.TensorDataset(*data_arrays)
return data.DataLoader(dataset, batch_size, shuffle=is_train)
batch_size = 10
data_iter = load_array((features, labels), batch_size)
net = nn.Sequential(nn.Linear(2, 1))
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)
loss = nn.MSELoss()
trainer = torch.optim.SGD(net.parameters(), lr=0.03)
num_epochs = 3
for epoch in range(num_epochs):
for X, y in data_iter:
l = loss(net(X) ,y)
trainer.zero_grad()
l.backward()
trainer.step()
l = loss(net(features), labels)
print(f'epoch {epoch + 1}, loss {l:f}')
边栏推荐
- SAP Fiori tools and corresponding cli (command line interface)
- Incorrect dependency of POM file
- Simple student management system
- Add the author watermark plugin v1.4 update to the posts of elegant grass discuz plugin - some forums post errors and bugs have been fixed
- Kubevela v1.2 release: the graphical operation console velaux you want is finally here!
- Day19 (variable parameter, enhanced for loop traversal, generic wildcard <? >, TreeSet, linkedhashset, nested traversal of sets, set set, static import,)
- Kyma application connectivity feature introduction
- What is flush software? Is it safe to open an account online?
- JS implementation mouse can achieve the effect of left and right scrolling
- Introduction to MySQL test run test framework
猜你喜欢

Day22 send request and parameterization using JMeter
Tutorial 35 of SAP ui5 application development - how to deploy locally developed SAP ui5 applications to ABAP server for trial reading
[kicad image] download and installation
SAP ui5 beginner tutorial No. 28 - Introduction to the integration test tool OPA for SAP ui5 applications
Interviewer: what is an iterator? What is the relationship between async await and iterators?

Jenkins installation and configuration

Getting started with mongodb

Lesson 9: workspace introduction

Understanding the dynamic mode of mongodb document

MySQL uses the where condition to find strange results: solve
随机推荐
SAP ui5 beginner tutorial No. 28 - Introduction to the integration test tool OPA for SAP ui5 applications
Mongodb basic concept learning - Documentation
HashSet implementation class
Jz-066- motion range of robot
How SAP ui5 device type detection device API works
Do you know what a three-tier architecture is?
DF command – displays disk space usage
Vscode voice notes to enrich information (medium)
Copying DNA
Jenkins installation and configuration
Wireless industrial Internet of things data monitoring terminal
Create a complete binary tree in array order
Which securities company is good for opening a mobile account? Is it safe to open a mobile account?
CSDN cerebral palsy bug has wasted nearly two hours of hard work
手机开户一般哪个证券公司好?手机开户是安全么?
MySQL uses the where condition to find strange results: solve
[kicad image] download and installation
Technology inventory: past, present and future of Message Oriented Middleware
Farewell to Lombok in 996
Rhcsa day 4