PyTorch 笔记
'''
张量类宇 Numpy 中的 ndarray 类似,但是比 ndarray 多了一些功能.
张量表示由一个数值组成的数组,这个数组可能由多个维度。具有一个轴的张量
对应数学上的向量。具有两个轴的张量对应数学上的矩阵。
'''
import torch
import numpy as np
from IPython import display
from torch.distributions import multinomial
from d2l import torch as d2l
x = torch.arange(12)
print(x)
x_shape = x.shape
print(x_shape)
X = x.reshape(3, 4)
print(X)
x_ones = torch.ones(2, 3, 4)
print(x_ones)
x_randn = torch.randn(3, 4)
print(x_randn)
x_tensor = torch.tensor([[1,2], [2,4]])
print(x_tensor)
x_sum = torch.arange(20, dtype = torch.float32).reshape(4, 5)
print(x_sum.sum(axis = 1))
x_d, y_d = torch.ones(4, dtype = torch.float32), torch.ones(4, dtype = torch.float32)
print(x_d, y_d, torch.dot(x_d, y_d))
'''
范数,一个向量的范数告诉我们一个向量有多大
'''
u = torch.tensor([3.0, -4.0])
print(torch.norm(u))
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}, numberical limit = {numerical_lim(f, 1, h): .5f}')
h *= 0.1
def use_svg_display():
"""使⽤svg格式在Jupyter中显⽰绘图。"""
def set_figsize(figsize=(3.5, 2.5)):
"""设置matplotlib的图表⼤⼩。"""
use_svg_display()
d2l.plt.rcParams['figure.figsize'] = figsize
def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
"""设置matplotlib的轴。"""
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
axes.set_xscale(xscale)
axes.set_yscale(yscale)
axes.set_xlim(xlim)
axes.set_ylim(ylim)
if legend:
axes.legend(legend)
axes.grid()
def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None):
"""绘制数据点。"""
if legend is None:
legend = []
set_figsize(figsize)
axes = axes if axes else d2l.plt.gca()
def has_one_axis(X):
return (hasattr(X, "ndim") and X.ndim == 1 or
isinstance(X, list) and not hasattr(X[0], "__len__"))
if has_one_axis(X):
X = [X]
if Y is None:
X, Y = [[]] * len(X), X
elif has_one_axis(Y):
Y = [Y]
if len(X) != len(Y):
X = X * len(Y)
axes.cla()
for x, y, fmt in zip(X, Y, fmts):
if len(x):
axes.plot(x, y, fmt)
else:
axes.plot(y, fmt)
set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
x = np.arange(0, 3, 0.1)
plot(x, [f(x), 2 * x - 3], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])
x_automatic = torch.arange(4.0)
print(x_automatic)
x_automatic.requires_grad = True
print(x_automatic.grad)
y_automatic = 2 + torch.dot(x_automatic, x_automatic)
print(y_automatic)
y_automatic.backward()
print(x_automatic.grad)
x_automatic.grad.zero_()
x_detach = torch.arange(4.0, requires_grad=True)
print(x_detach.grad)
y_detach = x_detach * x_detach
u = y_detach.detach()
z = u * x_detach
z.sum().backward()
print(x_detach.grad == u)
fair_probs = torch.ones([6]) / 6
print(multinomial.Multinomial(10, fair_probs).sample())
counts = multinomial.Multinomial(1000, fair_probs).sample()
print(counts / 1000)
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 = 'black', linestyle = 'dashed')
d2l.plt.gca().set_xlabel('Groups of experiments')
d2l.plt.gca().set_ylabel('Estimated probability')
d2l.plt.legend()
d2l.plt.show()
print(dir(torch.distributions))
help(torch.ones)