当前位置:网站首页>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}')
边栏推荐
- Tencent and China Mobile continued to buy back with large sums of money, and the leading Hong Kong stocks "led" the market to rebound?
- SAP ui5 date type sap ui. model. type. Analysis of date parsing format
- Ping command – test network connectivity between hosts
- Trial version of routing history and routing back and history of SAP ui5
- What are the reasons why most webmasters choose Hong Kong site group servers?
- Which securities company is good for opening a mobile account? Is it safe to open a mobile account?
- Copying DNA
- Introduction to the main features of kyma when the cloud native application runs
- Various errors and solutions encountered when deploying SAP ui5 application to ABAP server with SAP Fiori tools
- What happens when redis runs out of memory
猜你喜欢
Kubevela v1.2 release: the graphical operation console velaux you want is finally here!

16 application problem solving

Day18 (set, generic, hash table, tree, stack and queue, graph, array and linked list)
Wind farm visualization: wind farm data

Mongodb delete data

Volatile and JMM memory models
[golang] leetcode intermediate - Search rotation sort array & search two-dimensional matrix II

Jenkins installation and configuration
SAP ui5 beginner tutorial 25 - using proxy server to solve the cross domain problem of SAP ui5 application accessing remote OData service trial version

Tablespace free space
随机推荐
Is the securities account of Qiantang education safe? Is it reliable?
C simple operation mongodb
[JS basic review] scope, this, closure
The simplest way to tell you is to hash and not hash
Understanding the dynamic mode of mongodb document
Yunda's cloud based business in Taiwan construction 𞓜 practical school
How the sap ui5 framework performs single step debugging of batch requests
Differences and connections between sap ui5 and openui5
Three tier architecture experiment
Technology inventory: Technology Evolution and Future Trend Outlook of cloud native Middleware
Do you know what a three-tier architecture is?
Ping command – test network connectivity between hosts
Lesson 8: FTP server setup and loading
DOM proficient? What is the difference between node and elment?
Uname command – displays system information
Find command – find and search for files
Data7202 statistical analysis
What is SAP sup - Sybase unwired platform
Wireless industrial Internet of things data monitoring terminal
Copying DNA