PyTorch 笔记 (一)

这篇PyTorch笔记介绍了张量的基本操作,包括创建、形状变换、随机采样,以及张量的点积、范数等数学运算。此外,还涉及到了自动微分的概念,展示如何在PyTorch中进行梯度计算,并通过实例解释了概率分布和概率采样的应用。最后,展示了如何查找和使用PyTorch库中的函数。
摘要由CSDN通过智能技术生成

PyTorch 笔记

'''
张量类宇 Numpy 中的 ndarray 类似,但是比 ndarray 多了一些功能.
张量表示由一个数值组成的数组,这个数组可能由多个维度。具有一个轴的张量
对应数学上的向量。具有两个轴的张量对应数学上的矩阵。
'''
# %matplotlib inline
import torch
import numpy as np
from IPython import display
from torch.distributions import multinomial
from d2l import torch as d2l

# arange 常见一个行向量
x = torch.arange(12)
print(x)
# shape 访问张量的形状
x_shape = x.shape
print(x_shape)
# reshape 用于改变张量的形状, 可以自动推断形状,推断位使用 -1 ,x.reshape(-1, 4)
X = x.reshape(3, 4)
print(X)
# 创建所有元素都为一的张量
x_ones = torch.ones(2, 3, 4)
print(x_ones)

# 从特定的概率分布中随机采样到张量中每个元素的值
# 以下代码创建一个形状为 [3, 4] 的张量,其中的
# 每个元素都从均值为 0,标准差为1的高斯分布中随机取样
x_randn = torch.randn(3, 4)
print(x_randn)
# 把 python 列表转换成 tensor
x_tensor = torch.tensor([[1,2], [2,4]])
print(x_tensor)

# 默认情况下调用求和函数会沿着所有轴降低张量的维度,使他变成一个标量。
# 可以适用 axis = n 将岩 n + 1 轴降维
x_sum = torch.arange(20, dtype = torch.float32).reshape(4, 5)
print(x_sum.sum(axis = 1))
# mean 或 average 是求平均值函数
# keepdims = True 降维时保持轴数不变

# 点积 Dot Product
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))
# mm 矩阵乘法
# torch.mm(A, B)

'''
范数,一个向量的范数告诉我们一个向量有多大

'''
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(): #@save
    """使⽤svg格式在Jupyter中显⽰绘图。"""
    # display.set_matplotlib_formats('svg')

def set_figsize(figsize=(3.5, 2.5)): #@save
    """设置matplotlib的图表⼤⼩。"""
    use_svg_display()
    d2l.plt.rcParams['figure.figsize'] = figsize

#@save
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()

#@save
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()
    # 如果 `X` 有⼀个轴,输出True
    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)
# 在我们计算 y 对于 x 的梯度之前,我们需要一个地方来存储梯度。
# 我们不会在每次对于一个参数求导时都分配新的内存。
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)

# 默认情况下, PyTorch 会累积梯度,我们需要清除之前的值
x_automatic.grad.zero_()

# 分离计算
# 我们在计算 z 对于 x 的梯度是由于某些原因我们希望将 y 视为一个常数,
# 并且只考虑 x 在 y 被计算后发挥的作用
# 在这里,我们可以分离 y 来返回一个新变量 u
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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值