一、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]])
這裡,我們先生成了兩個隨機矩陣x
和y
,它們的形狀分別是(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()
函數的基礎知識和高級用法。在深度學習中,我們經常使用矩陣乘法來實現一些複雜的操作,如卷積運算和雙線性插值。希望本文可以為大家提供一些幫助。
原創文章,作者:BELLM,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/370725.html