torch.mm详解

发布时间:2023-05-22

一、torch.mm的基础知识

torch.mm(input, mat2, out=None)函数是计算两个tensor的矩阵乘法。其中,input是第一个矩阵,mat2是第二个矩阵。如果指定out,则结果会被写入该输出张量。 该函数实现了普通矩阵乘法,它也是torch.matmul()函数的一种特殊情况。不同之处在于,torch.matmul()可以广义地计算不同形状的张量的乘积。 下面是一个简单的例子:

import torch
# 生成两个随机矩阵
x = torch.rand(3, 4)
y = torch.rand(4, 5)
# 计算矩阵乘积
z = torch.mm(x, y)
print(z)

输出结果:

tensor([[0.8313, 0.3308, 0.8844, 1.1625, 0.6847],
        [1.1002, 1.0427, 1.2463, 1.4015, 1.1074],
        [0.7341, 0.7045, 0.8077, 0.9469, 0.6974]])

这里,我们先生成了两个随机矩阵xy,它们的形状分别是(3,4)和(4,5)。然后,使用torch.mm()计算它们的矩阵乘积z

二、torch.mm的高级用法

1. 使用torch.mm()实现卷积运算

在深度学习中,卷积神经网络(Convolutional Neural Networks, CNNs)是非常重要的模型,卷积运算是CNNs中的核心操作之一。虽然卷积通常使用专门的卷积函数来实现,但是我们可以使用矩阵乘法来实现卷积。 我们以一维卷积为例,假设输入tensor的形状为(batch_size, input_channels, input_width),卷积核的形状为(output_channels, input_channels * kernel_width)(这里简单地假设卷积核宽度为固定值),输出tensor的形状为(batch_size, output_channels, output_width),则卷积运算可以表示为: $$ \textrm{output} = \textrm{input} \times \textrm{weight}^T + \textrm{bias} $$ 其中,$\textrm{input}$和$\textrm{weight}$是二维矩阵,$\textrm{bias}$是偏置项,$T$表示矩阵转置操作。 下面是一个简单的一维卷积实现:

import torch
batch_size, input_channels, input_width = 10, 5, 100
output_channels, kernel_width = 8, 3
# 生成随机的输入,卷积核和偏置项
input_tensor = torch.randn(batch_size, input_channels, input_width)
weight_tensor = torch.randn(output_channels, input_channels * kernel_width)
bias_tensor = torch.randn(output_channels)
# 通过reshape操作将输入和卷积核转换为二维矩阵
input_matrix = input_tensor.view(batch_size, input_channels, -1).transpose(1, 2).contiguous().view(batch_size * input_width, input_channels)
weight_matrix = weight_tensor.view(output_channels, -1)
# 计算矩阵乘积和偏置项
output_matrix = torch.mm(input_matrix, weight_matrix.t()) + bias_tensor
output_tensor = output_matrix.view(batch_size, output_channels, -1).transpose(1, 2).contiguous()
print(output_tensor.shape)

这里我们先生成了所有随机输入,卷积核和偏置项,然后通过reshape操作将输入和卷积核转换为二维矩阵。然后,我们可以使用torch.mm()计算矩阵乘积,并将结果reshape为输出tensor的形状。

2. 使用torch.mm()实现双线性插值

双线性插值是计算机视觉中的常见操作之一,它通常用于图像缩放和旋转。双线性插值就是在四个最近的像素值之间进行插值,以产生一个新的像素值。具体地,对于输入图片$(I_{kl})$和目标坐标$(x,y)$,双线性插值可以计算为: $$ I(x,y) = [(1-\delta_x)\cdot(1-\delta_y)\cdot I_{\lfloor x \rfloor, \lfloor y \rfloor} + (1-\delta_x)\cdot\delta_y\cdot I_{\lfloor x \rfloor, \lceil y \rceil} + \delta_x\cdot(1-\delta_y)\cdot I_{\lceil x \rceil, \lfloor y \rfloor} + \delta_x\cdot\delta_y\cdot I_{\lceil x \rceil, \lceil y \rceil}] $$ 其中,$\delta_x$和$\delta_y$分别表示$x$和$y$的小数部分。 下面是一个简单的双线性插值实现:

import torch
import torch.nn.functional as F
import numpy as np
import cv2
# 读取一张图片
img = cv2.imread('test.jpg').astype(np.float32) / 255.
img = torch.from_numpy(img.transpose((2, 0, 1))[None])
# 缩放图片
scale_factor = 2
h, w = img.shape[2:]
new_h, new_w = int(h * scale_factor), int(w * scale_factor)
src_h, src_w = np.arange(new_h), np.arange(new_w)
dst_h, dst_w = np.zeros(new_h), np.zeros(new_w)
dst_h[1:-1] = (src_h[1:-1] + 0.5) / scale_factor - 0.5
dst_w[1:-1] = (src_w[1:-1] + 0.5) / scale_factor - 0.5
# 构造网格坐标
grid_x, grid_y = np.meshgrid(dst_w, dst_h)  # (new_h, new_w)
grid_x = np.clip(grid_x, 0, w - 1)
grid_y = np.clip(grid_y, 0, h - 1)
y_0, x_0 = np.floor(grid_y).astype(np.int32), np.floor(grid_x).astype(np.int32)
y_1, x_1 = y_0 + 1, x_0 + 1
dy, dx = grid_y - y_0, grid_x - x_0
# 通过torch.mm()实现双线性插值
I00 = img[..., y_0, x_0]
I01 = img[..., y_0, x_1]
I10 = img[..., y_1, x_0]
I11 = img[..., y_1, x_1]
img_new = (1 - dx) * (1 - dy) * I00 + dx * (1 - dy) * I01 + (1 - dx) * dy * I10 + dx * dy * I11
# 显示原图和新图
img = img.numpy()[0].transpose((1, 2, 0))
img_new = img_new.numpy()[0].transpose((1, 2, 0))
cv2.imshow('input', img)
cv2.imshow('output', img_new)
cv2.waitKey(0)

这里我们首先读取一张图片,并将它转换为tensor格式。然后,我们使用np.meshgrid()函数构造目标网格,并使用np.floor()函数和np.clip()函数计算出每个网格对应的源像素位置。接着,我们可以使用torch.mm()函数计算双线性插值的结果。img_new就是缩放后的新图。

三、总结

本文详细介绍了torch.mm()函数的基础知识和高级用法。在深度学习中,我们经常使用矩阵乘法来实现一些复杂的操作,如卷积运算和双线性插值。希望本文可以为大家提供一些帮助。