id
int64
1
564
tensorflow
stringclasses
52 values
pytorch
stringclasses
81 values
mxnet
stringclasses
66 values
paddle
stringclasses
73 values
101
null
counts = multinomial.Multinomial(10, fair_probs).sample((500,)) cum_counts = counts.cumsum(dim=0) estimates = cum_counts / cum_counts.sum(dim=1, keepdims=True) d2l.set_figsize((6, 4.5)) for i in range(6): d2l.plt.plot(estimates[:, i].numpy(), label=("P(die=" + str(i + 1) + ")")) d2l.plt.axhline(y=0.167, color='blac...
counts = np.random.multinomial(10, fair_probs, size=500) cum_counts = counts.astype(np.float32).cumsum(axis=0) estimates = cum_counts / cum_counts.sum(axis=1, keepdims=True) d2l.set_figsize((6, 4.5)) for i in range(6): d2l.plt.plot(estimates[:, i].asnumpy(), label=("P(die=" + str(i + 1) + ")")) d2l.plt.axhline(y=0....
null
102
null
%matplotlib inline import math import time import numpy as np import torch from d2l import torch as d2l n = 10000 a = torch.ones(n) b = torch.ones(n) c = torch.zeros(n) timer = Timer() for i in range(n): c[i] = a[i] + b[i] x = np.arange(-7, 7, 0.01) params = [(0, 1), (0, 2), (3, 1)] d2l.plot(x, [normal(x, mu, sigma...
%matplotlib inline import math import time from mxnet import np from d2l import mxnet as d2l n = 10000 a = np.ones(n) b = np.ones(n) c = np.zeros(n) timer = Timer() for i in range(n): c[i] = a[i] + b[i] x = np.arange(-7, 7, 0.01) params = [(0, 1), (0, 2), (3, 1)] d2l.plot(x.asnumpy(), [normal(x, mu, sigma).asnumpy(...
null
103
null
%matplotlib inline import random import torch from d2l import torch as d2l def synthetic_data(w, b, num_examples): 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)) true_w = torch.tensor([2, -3.4]) true_b = 4.2 feat...
%matplotlib inline import random from mxnet import autograd, np, npx from d2l import mxnet as d2l npx.set_np() def synthetic_data(w, b, num_examples): X = np.random.normal(0, 1, (num_examples, len(w))) y = np.dot(X, w) + b y += np.random.normal(0, 0.01, y.shape) return X, y.reshape((-1, 1)) true_w = np....
null
104
null
import numpy as np import torch from torch.utils import data from d2l import torch as d2l 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): dataset = data.TensorDataset(*data_arrays) return data.DataL...
from mxnet import autograd, gluon, np, npx from d2l import mxnet as d2l npx.set_np() true_w = np.array([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): dataset = gluon.data.ArrayDataset(*data_arrays) return gluon.data.Dat...
null
105
null
%matplotlib inline import torch import torchvision from torch.utils import data from torchvision import transforms from d2l import torch as d2l d2l.use_svg_display() trans = transforms.ToTensor() mnist_train = torchvision.datasets.FashionMNIST( root="../data", train=True, transform=trans, download=True) mnist_test ...
%matplotlib inline import sys from mxnet import gluon from d2l import mxnet as d2l d2l.use_svg_display() mnist_train = gluon.data.vision.FashionMNIST(train=True) mnist_test = gluon.data.vision.FashionMNIST(train=False) def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5): figsize = (num_cols * scale, n...
null
106
null
import torch from IPython import display from d2l import torch as d2l batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs = 784 num_outputs = 10 W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True) b = torch.zeros(num_outputs, requires_grad=True) X = torc...
from IPython import display from mxnet import autograd, gluon, np, npx from d2l import mxnet as d2l npx.set_np() batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs = 784 num_outputs = 10 W = np.random.normal(0, 0.01, (num_inputs, num_outputs)) b = np.zeros(num_outputs) W.attach_...
null
107
null
import torch from torch import nn from d2l import torch as d2l batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10)) def init_weights(m): if type(m) == nn.Linear: nn.init.normal_(m.weight, std=0.01) net.apply(init_weights); los...
from mxnet import gluon, init, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) net = nn.Sequential() net.add(nn.Dense(10)) net.initialize(init.Normal(sigma=0.01)) loss = gluon.loss.SoftmaxCrossEntropyLoss() trainer...
null
108
null
%matplotlib inline import torch from d2l import torch as d2l x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True) y = torch.relu(x) d2l.plot(x.detach(), y.detach(), 'x', 'relu(x)', figsize=(5, 2.5)) y.backward(torch.ones_like(x), retain_graph=True) d2l.plot(x.detach(), x.grad, 'x', 'grad of relu', figsize=(5, 2.5)) y =...
%matplotlib inline from mxnet import autograd, np, npx from d2l import mxnet as d2l npx.set_np() x = np.arange(-8.0, 8.0, 0.1) x.attach_grad() with autograd.record(): y = npx.relu(x) d2l.plot(x, y, 'x', 'relu(x)', figsize=(5, 2.5)) y.backward() d2l.plot(x, x.grad, 'x', 'grad of relu', figsize=(5, 2.5)) with autogra...
null
109
null
import torch from torch import nn from d2l import torch as d2l batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs, num_outputs, num_hiddens = 784, 10, 256 W1 = nn.Parameter(torch.randn( num_inputs, num_hiddens, requires_grad=True) * 0.01) b1 = nn.Parameter(torch.zeros(num_hi...
from mxnet import gluon, np, npx from d2l import mxnet as d2l npx.set_np() batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs, num_outputs, num_hiddens = 784, 10, 256 W1 = np.random.normal(scale=0.01, size=(num_inputs, num_hiddens)) b1 = np.zeros(num_hiddens) W2 = np.random.norm...
null
110
null
import torch from torch import nn from d2l import torch as d2l net = nn.Sequential(nn.Flatten(), nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10)) def init_weights(m): if type(m) == nn.Linear: nn.init.normal_(m.weight, std=0.01) net.apply(init_weights); batch_size, lr, num_epochs = 256, 0.1, 10 loss = nn....
from mxnet import gluon, init, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() net = nn.Sequential() net.add(nn.Dense(256, activation='relu'), nn.Dense(10)) net.initialize(init.Normal(sigma=0.01)) batch_size, lr, num_epochs = 256, 0.1, 10 loss = gluon.loss.SoftmaxCrossEntropyLoss() trainer = gl...
null
111
null
import math import numpy as np import torch from torch import nn from d2l import torch as d2l true_w, features, poly_features, labels = [torch.tensor(x, dtype=torch.float32) for x in [true_w, features, poly_features, labels]] features[:2], poly_features[:2, :], labels[:2] def evaluate_loss(net, data_iter, loss): me...
import math from mxnet import gluon, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() features[:2], poly_features[:2, :], labels[:2] def evaluate_loss(net, data_iter, loss): metric = d2l.Accumulator(2) for X, y in data_iter: l = loss(net(X), y) metric.add(l.sum(), d2l...
null
112
null
%matplotlib inline import torch from torch import nn from d2l import torch as d2l n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5 true_w, true_b = torch.ones((num_inputs, 1)) * 0.01, 0.05 train_data = d2l.synthetic_data(true_w, true_b, n_train) train_iter = d2l.load_array(train_data, batch_size) test_data = d...
%matplotlib inline from mxnet import autograd, gluon, init, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5 true_w, true_b = np.ones((num_inputs, 1)) * 0.01, 0.05 train_data = d2l.synthetic_data(true_w, true_b, n_train) train_iter = ...
null
113
null
import torch from torch import nn from d2l import torch as d2l def dropout_layer(X, dropout): assert 0 <= dropout <= 1 if dropout == 1: return torch.zeros_like(X) if dropout == 0: return X mask = (torch.rand(X.shape) > dropout).float() return mask * X / (1.0 - dropout) X= torch.arang...
from mxnet import autograd, gluon, init, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() def dropout_layer(X, dropout): assert 0 <= dropout <= 1 if dropout == 1: return np.zeros_like(X) if dropout == 0: return X mask = np.random.uniform(0, 1, X.shape) > dropo...
null
114
null
trainer = torch.optim.SGD(net.parameters(), lr=lr) d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer) %matplotlib inline import torch from d2l import torch as d2l x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True) y = torch.sigmoid(x) y.backward(torch.ones_like(x)) d2l.plot(x.detach().numpy(), [y.de...
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': lr}) d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer) %matplotlib inline from mxnet import autograd, np, npx from d2l import mxnet as d2l npx.set_np() x = np.arange(-8.0, 8.0, 0.1) x.attach_grad() with autograd.record(): y = ...
null
115
null
%matplotlib inline import numpy as np import pandas as pd import torch from torch import nn from d2l import torch as d2l n_train = train_data.shape[0] train_features = torch.tensor(all_features[:n_train].values, dtype=torch.float32) test_features = torch.tensor(all_features[n_train:].values, dtype=torch.float32) train_...
%matplotlib inline import pandas as pd from mxnet import autograd, gluon, init, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() n_train = train_data.shape[0] train_features = np.array(all_features[:n_train].values, dtype=np.float32) test_features = np.array(all_features[n_train:].values, dt...
null
116
null
import torch from torch import nn from torch.nn import functional as F net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10)) X = torch.rand(2, 20) net(X) class MLP(nn.Module): def __init__(self): super().__init__() self.hidden = nn.Linear(20, 256) self.out = nn.Linear(256, 1...
from mxnet import np, npx from mxnet.gluon import nn npx.set_np() net = nn.Sequential() net.add(nn.Dense(256, activation='relu')) net.add(nn.Dense(10)) net.initialize() X = np.random.uniform(size=(2, 20)) net(X) class MLP(nn.Block): def __init__(self, **kwargs): super().__init__(**kwargs) self.hidde...
null
117
null
import torch from torch import nn net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1)) X = torch.rand(size=(2, 4)) net(X) net.state_dict()['2.bias'].data def block1(): return nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 4), nn.ReLU()) def block2(): net = nn.Sequential() for i in range(...
from mxnet import init, np, npx from mxnet.gluon import nn npx.set_np() net = nn.Sequential() net.add(nn.Dense(8, activation='relu')) net.add(nn.Dense(1)) net.initialize() X = np.random.uniform(size=(2, 4)) net(X) net.collect_params()['dense1_bias'].data() def block1(): net = nn.Sequential() net.add(nn.Dense(32...
null
118
null
import torch import torch.nn.functional as F from torch import nn class CenteredLayer(nn.Module): def __init__(self): super().__init__() def forward(self, X): return X - X.mean() Y = net(torch.rand(4, 8)) Y.mean() class MyLinear(nn.Module): def __init__(self, in_units, units): super(...
from mxnet import np, npx from mxnet.gluon import nn npx.set_np() class CenteredLayer(nn.Block): def __init__(self, **kwargs): super().__init__(**kwargs) def forward(self, X): return X - X.mean() Y = net(np.random.uniform(size=(4, 8))) Y.mean() class MyDense(nn.Block): def __init__(self, uni...
null
119
null
import torch from torch import nn from torch.nn import functional as F x = torch.arange(4) torch.save(x, 'x-file') x2 = torch.load('x-file') y = torch.zeros(4) torch.save([x, y],'x-files') x2, y2 = torch.load('x-files') mydict = {'x': x, 'y': y} torch.save(mydict, 'mydict') mydict2 = torch.load('mydict') class MLP(nn.M...
from mxnet import np, npx from mxnet.gluon import nn npx.set_np() x = np.arange(4) npx.save('x-file', x) x2 = npx.load('x-file') y = np.zeros(4) npx.save('x-files', [x, y]) x2, y2 = npx.load('x-files') mydict = {'x': x, 'y': y} npx.save('mydict', mydict) mydict2 = npx.load('mydict') class MLP(nn.Block): def __init_...
null
120
null
import torch from torch import nn torch.device('cpu'), torch.device('cuda'), torch.device('cuda:1') torch.cuda.device_count() def try_gpu(i=0): if torch.cuda.device_count() >= i + 1: return devices = [torch.device(f'cuda:{i}') return torch.device('cpu') def try_all_gpus(): devices = [torch.device(f'cuda...
from mxnet import np, npx from mxnet.gluon import nn npx.set_np() npx.cpu(), npx.gpu(), npx.gpu(1) npx.num_gpus() def try_gpu(i=0): return npx.gpu(i) if npx.num_gpus() >= i + 1 else npx.cpu() def try_all_gpus(): devices = [npx.gpu(i) for i in range(npx.num_gpus())] return devices if devices else [npx.cpu()]...
null
121
null
import torch from torch import nn from d2l import torch as d2l def corr2d(X, K): h, w = K.shape Y = torch.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1)) for i in range(Y.shape[0]): for j in range(Y.shape[1]): Y[i, j] = (X[i:i + h, j:j + w] * K).sum() return Y X = torch.tensor([[0.0,...
from mxnet import autograd, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() def corr2d(X, K): h, w = K.shape Y = np.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1)) for i in range(Y.shape[0]): for j in range(Y.shape[1]): Y[i, j] = (X[i:i + h, j:j + w] * K).sum...
null
122
null
import torch from torch import nn def comp_conv2d(conv2d, X): X = X.reshape((1, 1) + X.shape) Y = conv2d(X) return Y.reshape(Y.shape[2:]) conv2d = nn.Conv2d(1, 1, kernel_size=3, padding=1) X = torch.rand(size=(8, 8)) comp_conv2d(conv2d, X).shape conv2d = nn.Conv2d(1, 1, kernel_size=(5, 3), padding=(2, 1)) ...
from mxnet import np, npx from mxnet.gluon import nn npx.set_np() def comp_conv2d(conv2d, X): conv2d.initialize() X = X.reshape((1, 1) + X.shape) Y = conv2d(X) return Y.reshape(Y.shape[2:]) conv2d = nn.Conv2D(1, kernel_size=3, padding=1) X = np.random.uniform(size=(8, 8)) comp_conv2d(conv2d, X).shape co...
null
123
null
import torch from d2l import torch as d2l def corr2d_multi_in(X, K): return sum(d2l.corr2d(x, k) for x, k in zip(X, K)) X = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]) K = torch.tensor([[[0.0, 1.0], [2.0, 3.0]], [[1.0, 2.0], [3.0, 4.0]]]) ...
from mxnet import np, npx from d2l import mxnet as d2l npx.set_np() def corr2d_multi_in(X, K): return sum(d2l.corr2d(x, k) for x, k in zip(X, K)) X = np.array([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]) K = np.array([[[0.0, 1.0], [2.0, 3.0]], [[1.0, 2....
null
124
null
import torch from torch import nn from d2l import torch as d2l def pool2d(X, pool_size, mode='max'): p_h, p_w = pool_size Y = torch.zeros((X.shape[0] - p_h + 1, X.shape[1] - p_w + 1)) for i in range(Y.shape[0]): for j in range(Y.shape[1]): if mode == 'max': Y[i, j] = X[i:...
from mxnet import np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() def pool2d(X, pool_size, mode='max'): p_h, p_w = pool_size Y = np.zeros((X.shape[0] - p_h + 1, X.shape[1] - p_w + 1)) for i in range(Y.shape[0]): for j in range(Y.shape[1]): if mode == 'max': ...
null
125
null
import torch from torch import nn from d2l import torch as d2l net = nn.Sequential( nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(), nn.AvgPool2d(kernel_size=2, stride=2), nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(), nn.AvgPool2d(kernel_size=2, stride=2), nn.Flatten(), nn.Linear(16 * 5...
from mxnet import autograd, gluon, init, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() net = nn.Sequential() net.add(nn.Conv2D(channels=6, kernel_size=5, padding=2, activation='sigmoid'), nn.AvgPool2D(pool_size=2, strides=2), nn.Conv2D(channels=16, kernel_size=5, activatio...
null
126
null
import torch from torch import nn from d2l import torch as d2l net = nn.Sequential( nn.Conv2d(1, 96, kernel_size=11, stride=4, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(96, 256, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(256, ...
from mxnet import np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() net = nn.Sequential() net.add( nn.Conv2D(96, kernel_size=11, strides=4, activation='relu'), nn.MaxPool2D(pool_size=3, strides=2), nn.Conv2D(256, kernel_size=5, padding=2, activation='relu'), nn.MaxPool2D(pool_...
null
127
null
import torch from torch import nn from d2l import torch as d2l def vgg_block(num_convs, in_channels, out_channels): layers = [] for _ in range(num_convs): layers.append(nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)) layers.append(nn.ReLU()) in_channels = out_channels ...
from mxnet import np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() def vgg_block(num_convs, num_channels): blk = nn.Sequential() for _ in range(num_convs): blk.add(nn.Conv2D(num_channels, kernel_size=3, padding=1, activation='relu')) blk.add(nn.MaxPool2D(pool_size=2, stri...
null
128
null
import torch from torch import nn from d2l import torch as d2l def nin_block(in_channels, out_channels, kernel_size, strides, padding): return nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, strides, padding), nn.ReLU(), nn.Conv2d(out_channels, out_channels, kernel_size=1), ...
from mxnet import np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() def nin_block(num_channels, kernel_size, strides, padding): blk = nn.Sequential() blk.add(nn.Conv2D(num_channels, kernel_size, strides, padding, activation='relu'), nn.Conv2D(num_channels, kernel_size=1, a...
null
129
null
import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l class Inception(nn.Module): def __init__(self, in_channels, c1, c2, c3, c4, **kwargs): super(Inception, self).__init__(**kwargs) self.p1_1 = nn.Conv2d(in_channels, c1, kernel_size=1) self.p2_1...
from mxnet import np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() class Inception(nn.Block): def __init__(self, c1, c2, c3, c4, **kwargs): super(Inception, self).__init__(**kwargs) self.p1_1 = nn.Conv2D(c1, kernel_size=1, activation='relu') self.p2_1 = nn.Conv2D(...
null
130
null
import torch from torch import nn from d2l import torch as d2l def batch_norm(X, gamma, beta, moving_mean, moving_var, eps, momentum): if not torch.is_grad_enabled(): X_hat = (X - moving_mean) / torch.sqrt(moving_var + eps) else: assert len(X.shape) in (2, 4) if len(X.shape) == 2: ...
from mxnet import autograd, init, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() def batch_norm(X, gamma, beta, moving_mean, moving_var, eps, momentum): if not autograd.is_training(): X_hat = (X - moving_mean) / np.sqrt(moving_var + eps) else: assert len(X.shape) in...
null
131
null
import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l class Residual(nn.Module): def __init__(self, input_channels, num_channels, use_1x1conv=False, strides=1): super().__init__() self.conv1 = nn.Conv2d(input_channels, num_channels, kernel_size=3, paddin...
from mxnet import np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() class Residual(nn.Block): def __init__(self, num_channels, use_1x1conv=False, strides=1, **kwargs): super().__init__(**kwargs) self.conv1 = nn.Conv2D(num_channels, kernel_size=3, padding=1, strides=strides...
null
132
null
import torch from torch import nn from d2l import torch as d2l def conv_block(input_channels, num_channels): return nn.Sequential( nn.BatchNorm2d(input_channels), nn.ReLU(), nn.Conv2d(input_channels, num_channels, kernel_size=3, padding=1)) class DenseBlock(nn.Module): def __init__(self, num_con...
from mxnet import np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() def conv_block(num_channels): blk = nn.Sequential() blk.add(nn.BatchNorm(), nn.Activation('relu'), nn.Conv2D(num_channels, kernel_size=3, padding=1)) return blk class DenseBlock(nn.Block): ...
null
133
null
%matplotlib inline import torch from torch import nn from d2l import torch as d2l T = 1000 time = torch.arange(1, T + 1, dtype=torch.float32) x = torch.sin(0.01 * time) + torch.normal(0, 0.2, (T,)) d2l.plot(time, [x], 'time', 'x', xlim=[1, 1000], figsize=(6, 3)) tau = 4 features = torch.zeros((T - tau, tau)) for i in r...
%matplotlib inline from mxnet import autograd, gluon, init, np, npx from mxnet.gluon import nn from d2l import mxnet as d2l npx.set_np() T = 1000 time = np.arange(1, T + 1, dtype=np.float32) x = np.sin(0.01 * time) + np.random.normal(0, 0.2, (T,)) d2l.plot(time, [x], 'time', 'x', xlim=[1, 1000], figsize=(6, 3)) tau = 4...
null
134
null
import collections import re from d2l import torch as d2l
import collections import re from d2l import mxnet as d2l
null
135
null
import random import torch from d2l import torch as d2l tokens = d2l.tokenize(d2l.read_time_machine()) corpus = [token for line in tokens for token in line] vocab = d2l.Vocab(corpus) vocab.token_freqs[:10] def seq_data_iter_random(corpus, batch_size, num_steps): corpus = corpus[random.randint(0, num_steps - 1):] ...
import random from mxnet import np, npx from d2l import mxnet as d2l npx.set_np() tokens = d2l.tokenize(d2l.read_time_machine()) corpus = [token for line in tokens for token in line] vocab = d2l.Vocab(corpus) vocab.token_freqs[:10] def seq_data_iter_random(corpus, batch_size, num_steps): corpus = corpus[random.rand...
null
136
null
import torch from d2l import torch as d2l X, W_xh = torch.normal(0, 1, (3, 1)), torch.normal(0, 1, (1, 4)) H, W_hh = torch.normal(0, 1, (3, 4)), torch.normal(0, 1, (4, 4)) torch.matmul(X, W_xh) + torch.matmul(H, W_hh) torch.matmul(torch.cat((X, H), 1), torch.cat((W_xh, W_hh), 0))
from mxnet import np, npx from d2l import mxnet as d2l npx.set_np() X, W_xh = np.random.normal(0, 1, (3, 1)), np.random.normal(0, 1, (1, 4)) H, W_hh = np.random.normal(0, 1, (3, 4)), np.random.normal(0, 1, (4, 4)) np.dot(X, W_xh) + np.dot(H, W_hh) np.dot(np.concatenate((X, H), 1), np.concatenate((W_xh, W_hh), 0))
null
137
null
%matplotlib inline import math import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) F.one_hot(torch.tensor([0, 2]), len(vocab)) X = torch.arange(10).reshape((2, 5)) F.one_h...
%matplotlib inline import math from mxnet import autograd, gluon, np, npx from d2l import mxnet as d2l npx.set_np() batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) npx.one_hot(np.array([0, 2]), len(vocab)) X = np.arange(10).reshape((2, 5)) npx.one_hot(X.T, 28).shape ...
null
138
null
import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) num_hiddens = 256 rnn_layer = nn.RNN(len(vocab), num_hiddens) state = torch.zeros((1, batch_size, num_hiddens)) state.s...
from mxnet import np, npx from mxnet.gluon import nn, rnn from d2l import mxnet as d2l npx.set_np() batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) num_hiddens = 256 rnn_layer = rnn.RNN(num_hiddens) rnn_layer.initialize() state = rnn_layer.begin_state(batch_size=batc...
null
139
null
import torch from torch import nn from d2l import torch as d2l batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) def get_params(vocab_size, num_hiddens, device): num_inputs = num_outputs = vocab_size def normal(shape): return torch.randn(size=shape, dev...
from mxnet import np, npx from mxnet.gluon import rnn from d2l import mxnet as d2l npx.set_np() batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) def get_params(vocab_size, num_hiddens, device): num_inputs = num_outputs = vocab_size def normal(shape): r...
null
140
null
import torch from torch import nn from d2l import torch as d2l batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) def get_lstm_params(vocab_size, num_hiddens, device): num_inputs = num_outputs = vocab_size def normal(shape): return torch.randn(size=shape...
from mxnet import np, npx from mxnet.gluon import rnn from d2l import mxnet as d2l npx.set_np() batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) def get_lstm_params(vocab_size, num_hiddens, device): num_inputs = num_outputs = vocab_size def normal(shape): ...
null
141
null
import os import torch from d2l import torch as d2l def build_array_nmt(lines, vocab, num_steps): lines = [vocab[l] for l in lines] lines = [l + [vocab['<eos>']] for l in lines] array = torch.tensor([truncate_pad(l, num_steps, vocab['<pad>']) for l in lines]) valid_len = (array != vocab['<pad>']).type(t...
import os from mxnet import np, npx from d2l import mxnet as d2l npx.set_np() def build_array_nmt(lines, vocab, num_steps): lines = [vocab[l] for l in lines] lines = [l + [vocab['<eos>']] for l in lines] array = np.array([truncate_pad(l, num_steps, vocab['<pad>']) for l in lines]) valid_len = (array != ...
null
142
null
x = torch.arange(12) X = x.reshape(3, 4) torch.zeros((2, 3, 4)) torch.ones((2, 3, 4)) torch.randn(3, 4) torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) x = torch.tensor([1.0, 2, 4, 8]) y = torch.tensor([2, 2, 2, 2]) x + y, x - y, x * y, x / y, x ** y torch.exp(x) X = torch.arange(12, dtype=torch.float32).resha...
null
x = paddle.arange(12) X = paddle.reshape(x, (3, 4)) paddle.zeros((2, 3, 4)) paddle.ones((2, 3, 4)) paddle.randn((3, 4),'float32') paddle.to_tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) x = paddle.to_tensor([1.0, 2, 4, 8]) y = paddle.to_tensor([2, 2, 2, 2]) x + y, x - y, x * y, x / y, x**y paddle.exp(x) X = paddle...
143
null
import torch X, y = torch.tensor(inputs.values), torch.tensor(outputs.values)
null
import warnings warnings.filterwarnings(action='ignore') import paddle X, y = paddle.to_tensor(inputs.values), paddle.to_tensor(outputs.values)
144
null
import torch x = torch.tensor(3.0) y = torch.tensor(2.0) print(x + y, x * y, x / y, x**y) x = torch.arange(4) A = torch.arange(20).reshape(5, 4) A.T B = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]]) B == B.T X = torch.arange(24).reshape(2, 3, 4) A = torch.arange(20, dtype=torch.float32).reshape(5, 4) B = A.clone() pr...
null
import warnings warnings.filterwarnings(action='ignore') import paddle x = paddle.to_tensor([3.0]) y = paddle.to_tensor([2.0]) x + y, x * y, x / y, x**y x = paddle.arange(4) A = paddle.reshape(paddle.arange(20), (5, 4)) paddle.transpose(A, perm=[1, 0]) B = paddle.to_tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]]) B == paddle...
145
null
%matplotlib inline import numpy as np from matplotlib_inline import backend_inline from d2l import torch as d2l def f(x): return 3 * x ** 2 - 4 * x def numerical_lim(f, x, h): return (f(x + h) - f(x)) / h h = 0.1 for i in range(5): print(f'h={h:.5f}, numerical limit={numerical_lim(f, 1, h):.5f}') h *= 0...
null
%matplotlib inline import numpy as np from matplotlib_inline import backend_inline from d2l import paddle as d2l def f(x): return 3 * x ** 2 - 4 * x def numerical_lim(f, x, h): return (f(x + h) - f(x)) / h h = 0.1 for i in range(5): print(f'h={h:.5f}, numerical limit={numerical_lim(f, 1, h):.5f}') h *= ...
146
null
import torch x = torch.arange(4.0) x.requires_grad_(True) x.grad y = 2 * torch.dot(x, x) x.grad.zero_() y = x.sum() y.backward() x.grad x.grad.zero_() y = x * x y.sum().backward() x.grad x.grad.zero_() y = x * x u = y.detach() z = u * x z.sum().backward() x.grad == u x.grad.zero_() y.sum().backward() x.grad == 2 * x de...
null
import warnings warnings.filterwarnings(action='ignore') import paddle x = paddle.arange(4, dtype='float32') x = paddle.to_tensor(x, stop_gradient=False) y = 2 * paddle.dot(x, x) x.clear_gradient() y = paddle.sum(x) y.backward() x.grad x.clear_gradient() y = x * x paddle.sum(y).backward() x.grad x.clear_gradient() y = ...
147
null
%matplotlib inline import torch from torch.distributions import multinomial from d2l import torch as d2l fair_probs = torch.ones([6]) / 6 multinomial.Multinomial(1, fair_probs).sample() multinomial.Multinomial(10, fair_probs).sample() counts = multinomial.Multinomial(1000, fair_probs).sample()
null
%matplotlib inline import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import random import numpy as np import paddle fair_probs = [1.0 / 6] * 6 paddle.distribution.Multinomial(1, paddle.to_tensor(fair_probs)).sample() counts = paddle.distribution.Multinomial(1000, paddle.to_tensor(fair_prob...
148
null
counts = multinomial.Multinomial(10, fair_probs).sample((500,)) cum_counts = counts.cumsum(dim=0) estimates = cum_counts / cum_counts.sum(dim=1, keepdims=True) d2l.set_figsize((6, 4.5)) for i in range(6): d2l.plt.plot(estimates[:, i].numpy(), label=("P(die=" + str(i + 1) + ")")) d2l.plt.axhline(y=0.167, color='blac...
null
counts = paddle.distribution.Multinomial(10, paddle.to_tensor(fair_probs)).sample((500,1)) cum_counts = counts.cumsum(axis=0) cum_counts = cum_counts.squeeze(axis=1) estimates = cum_counts / cum_counts.sum(axis=1, keepdim=True) d2l.set_figsize((6, 4.5)) for i in range(6): d2l.plt.plot(estimates[:, i], ...
149
null
%matplotlib inline import math import time import numpy as np import torch from d2l import torch as d2l n = 10000 a = torch.ones(n) b = torch.ones(n) c = torch.zeros(n) timer = Timer() for i in range(n): c[i] = a[i] + b[i] x = np.arange(-7, 7, 0.01) params = [(0, 1), (0, 2), (3, 1)] d2l.plot(x, [normal(x, mu, sigma...
null
%matplotlib inline import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import math import time import numpy as np import paddle n = 10000 a = paddle.ones([n]) b = paddle.ones([n]) c = paddle.zeros([n]) timer = Timer() for i in range(n): c[i] = a[i] + b[i] x = np.arange(-7, 7, 0.01) param...
150
null
%matplotlib inline import random import torch from d2l import torch as d2l def synthetic_data(w, b, num_examples): 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)) true_w = torch.tensor([2, -3.4]) true_b = 4.2 feat...
null
%matplotlib inline import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import random import paddle def synthetic_data(w, b, num_examples): X = paddle.normal(0, 1, (num_examples, len(w))) y = paddle.matmul(X, w) + b y += paddle.normal(0, 0.01, y.shape) return X, y.reshape((-1,...
151
null
import numpy as np import torch from torch.utils import data from d2l import torch as d2l 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): dataset = data.TensorDataset(*data_arrays) return data.DataL...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import numpy as np import paddle true_w = paddle.to_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): dataset = paddle.io.TensorDataset(dat...
152
null
%matplotlib inline import torch import torchvision from torch.utils import data from torchvision import transforms from d2l import torch as d2l d2l.use_svg_display() trans = transforms.ToTensor() mnist_train = torchvision.datasets.FashionMNIST( root="../data", train=True, transform=trans, download=True) mnist_test ...
null
%matplotlib inline import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import sys import paddle from paddle.vision import transforms d2l.use_svg_display() trans = transforms.ToTensor() mnist_train = paddle.vision.datasets.FashionMNIST(mode="train", transform=trans) mnist_test = paddle.vision...
153
null
import torch from IPython import display from d2l import torch as d2l batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs = 784 num_outputs = 10 W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True) b = torch.zeros(num_outputs, requires_grad=True) X = torc...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle from IPython import display batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs = 784 num_outputs = 10 W = paddle.normal(0, 0.01, shape=(num_inputs, num_outputs)) b = paddle.zeros(shape=...
154
null
import torch from torch import nn from d2l import torch as d2l batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10)) def init_weights(m): if type(m) == nn.Linear: nn.init.normal_(m.weight, std=0.01) net.apply(init_weights); tra...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle from paddle import nn batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10)) def init_weights(m): if type(m) == nn.Linear: nn.initiali...
155
null
%matplotlib inline import torch from d2l import torch as d2l x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True) y = torch.relu(x) d2l.plot(x.detach(), y.detach(), 'x', 'relu(x)', figsize=(5, 2.5)) y.backward(torch.ones_like(x), retain_graph=True) d2l.plot(x.detach(), x.grad, 'x', 'grad of relu', figsize=(5, 2.5)) y =...
null
%matplotlib inline import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle x = paddle.arange(-8.0, 8.0, 0.1, dtype='float32') x.stop_gradient = False y = paddle.nn.functional.relu(x) d2l.plot(x.detach().numpy(), y.detach().numpy(), 'x', 'relu(x)', figsize=(5, 2.5)) y.backward(paddl...
156
null
import torch from torch import nn from d2l import torch as d2l batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs, num_outputs, num_hiddens = 784, 10, 256 W1 = nn.Parameter(torch.randn( num_inputs, num_hiddens, requires_grad=True) * 0.01) b1 = nn.Parameter(torch.zeros(num_hi...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle from paddle import nn batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs, num_outputs, num_hiddens = 784, 10, 256 W1 = paddle.randn([num_inputs, num_hiddens]) * 0.01 W1.stop_gradient = ...
157
null
import torch from torch import nn from d2l import torch as d2l net = nn.Sequential(nn.Flatten(), nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10)) def init_weights(m): if type(m) == nn.Linear: nn.init.normal_(m.weight, std=0.01) net.apply(init_weights); batch_size, lr, num_epochs = 256, 0.1, 10 loss = nn....
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle from paddle import nn net = nn.Sequential(nn.Flatten(), nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10)) for layer in net: if type(layer) == nn.Linear: ...
158
null
import math import numpy as np import torch from torch import nn from d2l import torch as d2l true_w, features, poly_features, labels = [torch.tensor(x, dtype=torch.float32) for x in [true_w, features, poly_features, labels]] features[:2], poly_features[:2, :], labels[:2] def train(train_features, test_features, train_...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import math import numpy as np import paddle from paddle import nn true_w, features, poly_features, labels = [paddle.to_tensor(x, dtype= paddle.float32) for x in [true_w, features, poly_features, labels]] features[:2], poly_features[:2,...
159
null
%matplotlib inline import torch from torch import nn from d2l import torch as d2l n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5 true_w, true_b = torch.ones((num_inputs, 1)) * 0.01, 0.05 train_data = d2l.synthetic_data(true_w, true_b, n_train) train_iter = d2l.load_array(train_data, batch_size) test_data = d...
null
%matplotlib inline import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle from paddle import nn n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5 true_w, true_b = paddle.ones((num_inputs, 1)) * 0.01, 0.05 train_data = d2l.synthetic_data(true_w, true_b, n_train) train_iter ...
160
null
import torch from torch import nn from d2l import torch as d2l def dropout_layer(X, dropout): assert 0 <= dropout <= 1 if dropout == 1: return torch.zeros_like(X) if dropout == 0: return X mask = (torch.rand(X.shape) > dropout).float() return mask * X / (1.0 - dropout) X= torch.arang...
null
import warnings warnings.filterwarnings(action='ignore') import random import paddle from paddle import nn warnings.filterwarnings("ignore", category=DeprecationWarning) from d2l import paddle as d2l def dropout_layer(X, dropout): assert 0 <= dropout <= 1 if dropout == 1: return paddle.zeros_like(X) ...
161
null
trainer = torch.optim.SGD(net.parameters(), lr=lr) d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer) %matplotlib inline import torch from d2l import torch as d2l x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True) y = torch.sigmoid(x) y.backward(torch.ones_like(x)) d2l.plot(x.detach().numpy(), [y.de...
null
trainer = paddle.optimizer.SGD(learning_rate=0.5, parameters=net.parameters()) d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer) %matplotlib inline import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle x = paddle.arange(start=-8.0, end=8.0, step=0.1, dtype='flo...
162
null
%matplotlib inline import numpy as np import pandas as pd import torch from torch import nn from d2l import torch as d2l n_train = train_data.shape[0] train_features = torch.tensor(all_features[:n_train].values, dtype=torch.float32) test_features = torch.tensor(all_features[n_train:].values, dtype=torch.float32) train_...
null
%matplotlib inline import warnings import numpy as np import pandas as pd warnings.filterwarnings(action='ignore') import paddle from paddle import nn warnings.filterwarnings("ignore", category=DeprecationWarning) from d2l import paddle as d2l n_train = train_data.shape[0] train_features = paddle.to_tensor(all_features...
163
null
import torch from torch import nn from torch.nn import functional as F net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10)) X = torch.rand(2, 20) net(X) class MLP(nn.Module): def __init__(self): super().__init__() self.hidden = nn.Linear(20, 256) self.out = nn.Linear(256, 1...
null
import warnings warnings.filterwarnings(action='ignore') import paddle from paddle import nn from paddle.nn import functional as F net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10)) X = paddle.rand([2, 20]) net(X) class MLP(nn.Layer): def __init__(self): super().__init__() self.h...
164
null
import torch from torch import nn net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1)) X = torch.rand(size=(2, 4)) net(X) net.state_dict()['2.bias'].data def block1(): return nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 4), nn.ReLU()) def block2(): net = nn.Sequential() for i in range(...
null
import warnings warnings.filterwarnings(action='ignore') import paddle from paddle import nn net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1)) X = paddle.rand([2, 4]) net(X) net.state_dict()['2.bias'] def block1(): return nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 4), nn.ReLU()) def block...
165
null
import torch import torch.nn.functional as F from torch import nn class CenteredLayer(nn.Module): def __init__(self): super().__init__() def forward(self, X): return X - X.mean() Y = net(torch.rand(4, 8)) Y.mean() class MyLinear(nn.Module): def __init__(self, in_units, units): super(...
null
import warnings warnings.filterwarnings(action='ignore') import paddle import paddle.nn.functional as F from paddle import nn class CenteredLayer(nn.Layer): def __init__(self): super().__init__() def forward(self, X): return X - X.mean() Y = net(paddle.rand([4, 8])) Y.mean() class MyLinear(nn.La...
166
null
import torch from torch import nn from torch.nn import functional as F x = torch.arange(4) torch.save(x, 'x-file') x2 = torch.load('x-file') y = torch.zeros(4) torch.save([x, y],'x-files') x2, y2 = torch.load('x-files') mydict = {'x': x, 'y': y} torch.save(mydict, 'mydict') mydict2 = torch.load('mydict') class MLP(nn.M...
null
import warnings warnings.filterwarnings(action='ignore') import paddle from paddle import nn from paddle.nn import functional as F x = paddle.arange(4) paddle.save(x, 'x-file') x2 = paddle.load('x-file') y = paddle.zeros([4]) paddle.save([x,y], 'x-file') x2, y2 = paddle.load('x-file') mydict = {'x': x, 'y': y} paddle.s...
167
null
import torch from torch import nn torch.device('cpu'), torch.device('cuda'), torch.device('cuda:1') torch.cuda.device_count() def try_gpu(i=0): if torch.cuda.device_count() >= i + 1: return devices = [torch.device(f'cuda:{i}') return torch.device('cpu') def try_all_gpus(): devices = [torch.device(f'cuda...
null
import paddle from paddle import nn paddle.device.set_device("cpu"), paddle.CUDAPlace(0), paddle.CUDAPlace(1) paddle.device.cuda.device_count() if paddle.device.cuda.device_count() >= i + 1: return paddle.CUDAPlace(i) return paddle.CPUPlace() def try_all_gpus(): devices = [paddle.CUDAPlace(i) for i ...
168
null
import torch from torch import nn from d2l import torch as d2l def corr2d(X, K): h, w = K.shape Y = torch.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1)) for i in range(Y.shape[0]): for j in range(Y.shape[1]): Y[i, j] = (X[i:i + h, j:j + w] * K).sum() return Y X = torch.tensor([[0.0,...
null
import warningsfrom d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle from paddle import nn def corr2d(X, K): h, w = K.shape Y = paddle.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1)) for i in range(Y.shape[0]): for j in range(Y.shape[1]): Y[i, j] = (X[i:i + h, j:j...
169
null
import torch from torch import nn def comp_conv2d(conv2d, X): X = X.reshape((1, 1) + X.shape) Y = conv2d(X) return Y.reshape(Y.shape[2:]) conv2d = nn.Conv2d(1, 1, kernel_size=3, padding=1) X = torch.rand(size=(8, 8)) comp_conv2d(conv2d, X).shape conv2d = nn.Conv2d(1, 1, kernel_size=(5, 3), padding=(2, 1)) ...
null
import warnings warnings.filterwarnings(action='ignore') import paddle from paddle import nn def comp_conv2d(conv2d, X): X = paddle.reshape(X, [1, 1] + X.shape) Y = conv2d(X) return Y.reshape(Y.shape[2:]) conv2d = nn.Conv2D(in_channels=1, out_channels=1, kernel_size=3, padding=1) X = paddle.rand((8, 8)) co...
170
null
import torch from d2l import torch as d2l def corr2d_multi_in(X, K): return sum(d2l.corr2d(x, k) for x, k in zip(X, K)) X = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]) K = torch.tensor([[[0.0, 1.0], [2.0, 3.0]], [[1.0, 2.0], [3.0, 4.0]]]) ...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle def corr2d_multi_in(X, K): return sum(d2l.corr2d(x, k) for x, k in zip(X, K)) X = paddle.to_tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]], [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]]) K = paddle.to_t...
171
null
import torch from torch import nn from d2l import torch as d2l def pool2d(X, pool_size, mode='max'): p_h, p_w = pool_size Y = torch.zeros((X.shape[0] - p_h + 1, X.shape[1] - p_w + 1)) for i in range(Y.shape[0]): for j in range(Y.shape[1]): if mode == 'max': Y[i, j] = X[i:...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle from paddle import nn def pool2d(X, pool_size, mode='max'): p_h, p_w = pool_size Y = paddle.zeros((X.shape[0] - p_h + 1, X.shape[1] - p_w + 1)) for i in range(Y.shape[0]): for j in range(Y.shape[1]): ...
172
null
import torch from torch import nn from d2l import torch as d2l net = nn.Sequential( nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(), nn.AvgPool2d(kernel_size=2, stride=2), nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(), nn.AvgPool2d(kernel_size=2, stride=2), nn.Flatten(), nn.Linear(16 * 5...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle from paddle import nn, optimizer net = nn.Sequential( nn.Conv2D(1, 6, kernel_size=5, padding=2), nn.Sigmoid(), nn.AvgPool2D(kernel_size=2, stride=2), nn.Conv2D(6, 16, kernel_size=5), nn.Sigmoid(), nn.AvgPool2D(...
173
null
import torch from torch import nn from d2l import torch as d2l net = nn.Sequential( nn.Conv2d(1, 96, kernel_size=11, stride=4, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(96, 256, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(256, ...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle import paddle.nn as nn net = nn.Sequential( nn.Conv2D(1, 96, kernel_size=11, stride=4, padding=1), nn.ReLU(), nn.MaxPool2D(kernel_size=3, stride=2), nn.Conv2D(96, 256, kernel_size=5, padding=2), nn.ReLU(), nn.M...
174
null
import torch from torch import nn from d2l import torch as d2l def vgg_block(num_convs, in_channels, out_channels): layers = [] for _ in range(num_convs): layers.append(nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)) layers.append(nn.ReLU()) in_channels = out_channels ...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle import paddle.nn as nn def vgg_block(num_convs, in_channels, out_channels): layers = [] for _ in range(num_convs): layers.append(nn.Conv2D(in_channels, out_channels, kernel_size=3, padding=1)) layers.ap...
175
null
import torch from torch import nn from d2l import torch as d2l def nin_block(in_channels, out_channels, kernel_size, strides, padding): return nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, strides, padding), nn.ReLU(), nn.Conv2d(out_channels, out_channels, kernel_size=1), ...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle import paddle.nn as nn def nin_block(in_channels, out_channels, kernel_size, strides, padding): return nn.Sequential( nn.Conv2D(in_channels, out_channels, kernel_size, strides, padding), nn.ReLU(), ...
176
null
import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l class Inception(nn.Module): def __init__(self, in_channels, c1, c2, c3, c4, **kwargs): super(Inception, self).__init__(**kwargs) self.p1_1 = nn.Conv2d(in_channels, c1, kernel_size=1) self.p2_1...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle import paddle.nn as nn import paddle.nn.functional as F class Inception(nn.Layer): def __init__(self, in_channels, c1, c2, c3, c4, **kwargs): super(Inception, self).__init__(**kwargs) self.p1_1 = nn.Conv2D(...
177
null
import torch from torch import nn from d2l import torch as d2l def batch_norm(X, gamma, beta, moving_mean, moving_var, eps, momentum): if not torch.is_grad_enabled(): X_hat = (X - moving_mean) / torch.sqrt(moving_var + eps) else: assert len(X.shape) in (2, 4) if len(X.shape) == 2: ...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle import paddle.nn as nn def batch_norm(X, gamma, beta, moving_mean, moving_var, eps, momentum, is_training=True): if not is_training: X_hat = (X - moving_mean) / (moving_var + eps) ** 0.5 else: assert le...
178
null
import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l class Residual(nn.Module): def __init__(self, input_channels, num_channels, use_1x1conv=False, strides=1): super().__init__() self.conv1 = nn.Conv2d(input_channels, num_channels, kernel_size=3, paddin...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle import paddle.nn as nn from paddle.nn import functional as F class Residual(nn.Layer): def __init__(self, input_channels, num_channels, use_1x1conv=False, strides=1): super(Residual, self).__init__(...
179
null
import torch from torch import nn from d2l import torch as d2l def conv_block(input_channels, num_channels): return nn.Sequential( nn.BatchNorm2d(input_channels), nn.ReLU(), nn.Conv2d(input_channels, num_channels, kernel_size=3, padding=1)) class DenseBlock(nn.Module): def __init__(self, num_con...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle import paddle.nn as nn def conv_block(input_channels, num_channels): return nn.Sequential( nn.BatchNorm2D(input_channels), nn.ReLU(), nn.Conv2D(input_channels, num_channels, kernel_size=3, padding=1)) class...
180
null
%matplotlib inline import torch from torch import nn from d2l import torch as d2l T = 1000 time = torch.arange(1, T + 1, dtype=torch.float32) x = torch.sin(0.01 * time) + torch.normal(0, 0.2, (T,)) d2l.plot(time, [x], 'time', 'x', xlim=[1, 1000], figsize=(6, 3)) tau = 4 features = torch.zeros((T - tau, tau)) for i in r...
null
%matplotlib inline import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle from paddle import nn T = 1000 time = paddle.arange(1, T + 1, dtype=paddle.float32) x = paddle.sin(0.01 * time) + paddle.normal(0, 0.2, (T,)) d2l.plot(time, [x], 'time', 'x', xlim=[1, 1000], figsize=(6, 3)) ...
181
null
import collections import re from d2l import torch as d2l
null
import collections import re from d2l import paddle as d2l
182
null
import random import torch from d2l import torch as d2l tokens = d2l.tokenize(d2l.read_time_machine()) corpus = [token for line in tokens for token in line] vocab = d2l.Vocab(corpus) vocab.token_freqs[:10] def seq_data_iter_random(corpus, batch_size, num_steps): corpus = corpus[random.randint(0, num_steps - 1):] ...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import random import paddle tokens = d2l.tokenize(d2l.read_time_machine()) corpus = [token for line in tokens for token in line] vocab = d2l.Vocab(corpus) vocab.token_freqs[:10] def seq_data_iter_random(corpus, batch_size, num_steps): c...
183
null
import torch from d2l import torch as d2l X, W_xh = torch.normal(0, 1, (3, 1)), torch.normal(0, 1, (1, 4)) H, W_hh = torch.normal(0, 1, (3, 4)), torch.normal(0, 1, (4, 4)) torch.matmul(X, W_xh) + torch.matmul(H, W_hh) torch.matmul(torch.cat((X, H), 1), torch.cat((W_xh, W_hh), 0))
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle X, W_xh = paddle.normal(0, 1, (3, 1)), paddle.normal(0, 1, (1, 4)) H, W_hh = paddle.normal(0, 1, (3, 4)), paddle.normal(0, 1, (4, 4)) paddle.matmul(X, W_xh) + paddle.matmul(H, W_hh) paddle.matmul(paddle.concat((X, H), 1), padd...
184
null
%matplotlib inline import math import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) F.one_hot(torch.tensor([0, 2]), len(vocab)) X = torch.arange(10).reshape((2, 5)) F.one_h...
null
%matplotlib inline import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import math import paddle from paddle import nn from paddle.nn import functional as F batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) F.one_hot(paddle.to_tensor([0, 2])...
185
null
import torch from torch import nn from torch.nn import functional as F from d2l import torch as d2l batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) num_hiddens = 256 rnn_layer = nn.RNN(len(vocab), num_hiddens) state = torch.zeros((1, batch_size, num_hiddens)) state.s...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle from paddle import nn from paddle.nn import functional as F batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) num_hiddens = 256 rnn_layer = nn.SimpleRNN(len(vocab), num_hidden...
186
null
import torch from torch import nn from d2l import torch as d2l batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) def get_params(vocab_size, num_hiddens, device): num_inputs = num_outputs = vocab_size def normal(shape): return torch.randn(size=shape, dev...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle import paddle.nn.functional as F from paddle import nn batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) def get_params(vocab_size, num_hiddens): num_inputs = num_outputs ...
187
null
import torch from torch import nn from d2l import torch as d2l batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) def get_lstm_params(vocab_size, num_hiddens, device): num_inputs = num_outputs = vocab_size def normal(shape): return torch.randn(size=shape...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import paddle import paddle.nn.functional as Function from paddle import nn batch_size, num_steps = 32, 35 train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps) def get_lstm_params(vocab_size, num_hiddens): num_inputs = ...
188
null
import os import torch from d2l import torch as d2l def build_array_nmt(lines, vocab, num_steps): lines = [vocab[l] for l in lines] lines = [l + [vocab['<eos>']] for l in lines] array = torch.tensor([truncate_pad(l, num_steps, vocab['<pad>']) for l in lines]) valid_len = (array != vocab['<pad>']).type(t...
null
import warnings from d2l import paddle as d2l warnings.filterwarnings("ignore") import os import paddle def build_array_nmt(lines, vocab, num_steps): lines = [vocab[l] for l in lines] lines = [l + [vocab['<eos>']] for l in lines] array = paddle.to_tensor([truncate_pad(l, num_steps, vocab['<pad>']) for l in ...
189
x = tf.range(12) tf.size(x) X = tf.reshape(x, (3, 4)) tf.zeros((2, 3, 4)) tf.ones((2, 3, 4)) tf.random.normal(shape=[3, 4]) tf.constant([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) x = tf.constant([1.0, 2, 4, 8]) y = tf.constant([2.0, 2, 2, 2]) x + y, x - y, x * y, x / y, x ** y tf.exp(x) X = tf.reshape(tf.range(12, dty...
x = torch.arange(12) x.numel() X = x.reshape(3, 4) torch.zeros((2, 3, 4)) torch.ones((2, 3, 4)) torch.randn(3, 4) torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) x = torch.tensor([1.0, 2, 4, 8]) y = torch.tensor([2, 2, 2, 2]) x + y, x - y, x * y, x / y, x ** y torch.exp(x) X = torch.arange(12, dtype=torch.floa...
null
null
190
import tensorflow as tf X, y = tf.constant(inputs.values), tf.constant(outputs.values)
import torch X, y = torch.tensor(inputs.values), torch.tensor(outputs.values)
null
null
191
import tensorflow as tf x = tf.constant(3.0) y = tf.constant(2.0) print(x + y, x * y, x / y, x**y) x = tf.range(4) A = tf.reshape(tf.range(20), (5, 4)) tf.transpose(A) B = tf.constant([[1, 2, 3], [2, 0, 4], [3, 4, 5]]) B == tf.transpose(B) X = tf.reshape(tf.range(24), (2, 3, 4)) A = tf.reshape(tf.range(20, dtype=tf.flo...
import torch x = torch.tensor(3.0) y = torch.tensor(2.0) print(x + y, x * y, x / y, x**y) x = torch.arange(4) A = torch.arange(20).reshape(5, 4) A.T B = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]]) B == B.T X = torch.arange(24).reshape(2, 3, 4) A = torch.arange(20, dtype=torch.float32).reshape(5, 4) B = A.clone() pr...
null
null
192
%matplotlib inline import numpy as np from matplotlib_inline import backend_inline from d2l import tensorflow as d2l def f(x): return 3 * x ** 2 - 4 * x
%matplotlib inline import numpy as np from matplotlib_inline import backend_inline from d2l import torch as d2l def f(x): return 3 * x ** 2 - 4 * x
null
null
193
import tensorflow as tf x = tf.range(4, dtype=tf.float32) x = tf.Variable(x) with tf.GradientTape() as t: y = 2 * tf.tensordot(x, x, axes=1) x_grad = t.gradient(y, x) x_grad x_grad == 4 * x with tf.GradientTape() as t: y = tf.reduce_sum(x) t.gradient(y, x) with tf.GradientTape() as t: y = x * x t.gradient(y...
import torch x = torch.arange(4.0) x.requires_grad_(True) x.grad y = 2 * torch.dot(x, x) y.backward() x.grad x.grad == 4 * x x.grad.zero_() y = x.sum() y.backward() x.grad x.grad.zero_() y = x * x y.sum().backward() x.grad x.grad.zero_() y = x * x u = y.detach() z = u * x z.sum().backward() x.grad == u x.grad.zero_() y...
null
null
194
%matplotlib inline import numpy as np import tensorflow as tf import tensorflow_probability as tfp from d2l import tensorflow as d2l fair_probs = tf.ones(6) / 6 tfp.distributions.Multinomial(1, fair_probs).sample() tfp.distributions.Multinomial(10, fair_probs).sample() counts = tfp.distributions.Multinomial(1000, fair_...
%matplotlib inline import torch from torch.distributions import multinomial from d2l import torch as d2l fair_probs = torch.ones([6]) / 6 multinomial.Multinomial(1, fair_probs).sample() multinomial.Multinomial(10, fair_probs).sample() counts = multinomial.Multinomial(1000, fair_probs).sample()
null
null
195
counts = tfp.distributions.Multinomial(10, fair_probs).sample(500) cum_counts = tf.cumsum(counts, axis=0) estimates = cum_counts / tf.reduce_sum(cum_counts, axis=1, keepdims=True) d2l.set_figsize((6, 4.5)) for i in range(6): d2l.plt.plot(estimates[:, i].numpy(), label=("P(die=" + str(i + 1) + ")")) d2l.plt.axhline(...
counts = multinomial.Multinomial(10, fair_probs).sample((500,)) cum_counts = counts.cumsum(dim=0) estimates = cum_counts / cum_counts.sum(dim=1, keepdims=True) d2l.set_figsize((6, 4.5)) for i in range(6): d2l.plt.plot(estimates[:, i].numpy(), label=("P(die=" + str(i + 1) + ")")) d2l.plt.axhline(y=0.167, color='blac...
null
null
196
%matplotlib inline import math import time import numpy as np import tensorflow as tf from d2l import tensorflow as d2l n = 10000 a = tf.ones(n) b = tf.ones(n) c = tf.Variable(tf.zeros(n)) timer = Timer() for i in range(n): c[i].assign(a[i] + b[i])
%matplotlib inline import math import time import numpy as np import torch from d2l import torch as d2l n = 10000 a = torch.ones(n) b = torch.ones(n) c = torch.zeros(n) timer = Timer() for i in range(n): c[i] = a[i] + b[i]
null
null
197
%matplotlib inline import random import tensorflow as tf from d2l import tensorflow as d2l def synthetic_data(w, b, num_examples): X = tf.zeros((num_examples, w.shape[0])) X += tf.random.normal(shape=X.shape) y = tf.matmul(X, tf.reshape(w, (-1, 1))) + b y += tf.random.normal(shape=y.shape, stddev=0.01) ...
%matplotlib inline import random import torch from d2l import torch as d2l def synthetic_data(w, b, num_examples): 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)) true_w = torch.tensor([2, -3.4]) true_b = 4.2 feat...
null
null
198
import numpy as np import tensorflow as tf from d2l import tensorflow as d2l true_w = tf.constant([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): dataset = tf.data.Dataset.from_tensor_slices(data_arrays) if is_train: ...
import numpy as np import torch from torch.utils import data from d2l import torch as d2l 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): dataset = data.TensorDataset(*data_arrays) return data.DataL...
null
null
199
%matplotlib inline import tensorflow as tf from d2l import tensorflow as d2l d2l.use_svg_display() mnist_train, mnist_test = tf.keras.datasets.fashion_mnist.load_data() len(mnist_train[0]), len(mnist_test[0]) def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5): figsize = (num_cols * scale, num_rows * ...
%matplotlib inline import torch import torchvision from torch.utils import data from torchvision import transforms from d2l import torch as d2l d2l.use_svg_display() trans = transforms.ToTensor() mnist_train = torchvision.datasets.FashionMNIST( root="../data", train=True, transform=trans, download=True) mnist_test ...
null
null
200
import tensorflow as tf from IPython import display from d2l import tensorflow as d2l batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs = 784 num_outputs = 10 W = tf.Variable(tf.random.normal(shape=(num_inputs, num_outputs), mean=0, stddev=0.01)) b = tf.Variable(tf.zeros(num_ou...
import torch from IPython import display from d2l import torch as d2l batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) num_inputs = 784 num_outputs = 10 W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True) b = torch.zeros(num_outputs, requires_grad=True) X = torc...
null
null