Tensor,又名张量,从工程角度,他就是一个数组,且支持高效的科学计算。它可以是一个数(标量),一维数组(向量),二维数组(矩阵)和更高维的数组
Tensor的接口有意设计成与Numpy类似,方便用户使用。
特点:可以随意的在gpu/cpu上传输使用tensor.cuda(device_id) 或者 tensor.cpu()
Tensor 的操作可分为两类:
1.torch.function,比如torch.save
2.tensor.function,比如 tensor.view
1.创建tensor 的方法:
| 函数 | 功能 |
| Tensor(*sizes) | 基础构造函数 |
| tensor(data,) | 类似np.array的构造函数 |
| ones(*sizes) | 全1Tensor |
| zeros(*sizes) | 全0Tensor |
| eye(*sizes) | 对角线为1,其他为0 |
| arange(s,e,step) | 从s到e,步长为step |
| linspace(s,e,steps) | 从s到e,均匀切分成steps份 |
| rand/randn(*sizes) | 均匀/标准分布 |
| normal(mean,std)/uniform(from,to) | 正态分布/均匀分布 |
| randperm(m) | 随机排列 |
2.常用Tensor操作:类似于python 的numpy.ndarray 的索引操作
| tensor.view | 可以调整tensor的形状 |
| a[0] | # 第0行(下标从0开始) |
| a[:, 0] | # 第0列 |
| a[:2, 0:2] | # 前两行,第0,1列 |
3.常用的函数:
| 函数 | 功能 |
| index_select(input, dim, index) | 在指定维度dim上选取,比如选取某些行、某些列 |
| masked_select(input, mask) | 例子如上,a[a>0],使用ByteTensor进行选取 |
| non_zero(input) | 非0元素的下标 |
| gather(input, dim, index) | 根据index,在dim维度上选取数据,输出的size与index一样 |
逐元素操作
| 函数 | 功能 |
| abs/sqrt/div/exp/fmod/log/pow.. | 绝对值/平方根/除法/指数/求余/求幂.. |
| cos/sin/asin/atan2/cosh.. | 相关三角函数 |
| ceil/round/floor/trunc | 上取整/四舍五入/下取整/只保留整数部分 |
| clamp(input, min, max) | 超过min和max部分截断 |
| sigmod/tanh.. | 激活函数 |
import torch as t
%matplotlib inline
from matplotlib import pyplot as plt
from IPython import display
device = t.device('cpu') #如果你想用gpu,改成t.device('cuda:0')
# 设置随机数种子,保证在不同电脑上运行时下面的输出一致
t.manual_seed(1000)
def get_fake_data(batch_size=8):
''' 产生随机数据:y=x*2+3,加上了一些噪声'''
#*5的话就是[0,5)表示产生的数据在[0,5)之间
x = t.rand(batch_size, 1, device=device) * 5
y = x * 2 + 3 + t.randn(batch_size, 1, device=device)
return x, y
生成样例数据,大致可以看出可以线性回归分析,拟合直线。x是大小为16的tensor,且范围[0,5)
x = tensor([[2.4565],
[1.9970],
[1.0708],
[1.3402],
[2.2084],
[2.6423],
[2.0228],
[4.5221],
[1.4942],
[3.0060],
[4.1383],
[4.8889],
[0.2865],
[4.1327],
[3.4590],
[4.4739]])

回归分析过程
# 随机初始化参数
w = t.rand(1, 1).to(device)
b = t.zeros(1, 1).to(device)
lr =0.02 # 学习率
for ii in range(500):
x, y = get_fake_data(batch_size=4)
# forward:计算loss
#mm矩阵乘法
y_pred = x.mm(w) + b.expand_as(y) # x@W等价于x.mm(w);for python3 only
loss = 0.5 * (y_pred - y) ** 2 # 均方误差
loss = loss.mean()
# backward:手动计算梯度
dloss = 1
dy_pred = dloss * (y_pred - y)
dw = x.t().mm(dy_pred)
db = dy_pred.sum()
# 更新参数
w.sub_(lr * dw)
b.sub_(lr * db)
if ii%50 ==0:
# 画图
display.clear_output(wait=True)
x = t.arange(0, 6).view(-1, 1)
y = x.float().mm(w) + b.expand_as(x)
plt.plot(x.cpu().numpy(), y.cpu().numpy()) # predicted
x2, y2 = get_fake_data(batch_size=32)
plt.scatter(x2.numpy(), y2.numpy()) # true data
plt.xlim(0, 5)
plt.ylim(0, 13)
plt.show()
plt.pause(0.5)
print('w: ', w.item(), 'b: ', b.item())
分析结果展示:

图中直线和数据已经实现较好的拟合,同归是手写的回归算法分析。
本文介绍了如何使用PyTorch进行线性回归分析。首先,详细阐述了Tensor的概念,它是一种支持高效科学计算的多维数组,与Numpy接口相似,可以在GPU/CPU间自由转换。接着,列举了Tensor的创建方法和常见操作,包括torch.function和tensor.function。然后,通过生成样例数据,展示了如何应用线性回归拟合数据,并得到了良好的拟合效果。
1299

被折叠的 条评论
为什么被折叠?



