修改一点小问题
This commit is contained in:
parent
22b33d63de
commit
18f5eaed19
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,3 +1,5 @@
|
|||||||
dataset/
|
dataset/
|
||||||
|
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|
||||||
|
.ipynb_checkpoints/
|
File diff suppressed because it is too large
Load Diff
@ -393,7 +393,7 @@
|
|||||||
"id": "6ab83528-a88b-4d66-b0c9-b1315cf75c22",
|
"id": "6ab83528-a88b-4d66-b0c9-b1315cf75c22",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"线性层主要有一个权重(weight)和一个偏置(bias)。\n",
|
"线性层主要有一个权重(weight)和一个偏置(bias)。\n",
|
||||||
"线性层的数学公式如下:\n",
|
"线性层的数学公式如下:\n",
|
||||||
"$$\n",
|
"$$\n",
|
||||||
"x:=x \\times weight^T+bias\n",
|
"x:=x \\times weight^T+bias\n",
|
||||||
|
@ -1,39 +0,0 @@
|
|||||||
import torch
|
|
||||||
|
|
||||||
A = torch.tensor([[1, 2, 3]])
|
|
||||||
|
|
||||||
B = torch.tensor([[4],
|
|
||||||
[5]])
|
|
||||||
|
|
||||||
# 方法1: 使用PyTorch的减法操作符
|
|
||||||
result1 = A - B
|
|
||||||
|
|
||||||
# 方法2: 使用PyTorch的sub函数
|
|
||||||
result2 = torch.sub(A, B)
|
|
||||||
|
|
||||||
# 方法3: 手动实现广播机制并作差
|
|
||||||
def my_sub(a:torch.Tensor, b:torch.Tensor):
|
|
||||||
if not (
|
|
||||||
(a.size(0) == 1 and b.size(1) == 1)
|
|
||||||
or
|
|
||||||
(a.size(1) == 1 and b.size(0) == 1)
|
|
||||||
):
|
|
||||||
raise ValueError("输入的张量大小无法满足广播机制的条件。")
|
|
||||||
else:
|
|
||||||
target_shape = torch.Size([max(A.size(0), B.size(0)), max(A.size(1), B.size(1))])
|
|
||||||
A_broadcasted = A.expand(target_shape)
|
|
||||||
B_broadcasted = B.expand(target_shape)
|
|
||||||
result = torch.zeros(target_shape, dtype=torch.int64).to(device=A_broadcasted.device)
|
|
||||||
for i in range(target_shape[0]):
|
|
||||||
for j in range(target_shape[1]):
|
|
||||||
result[i, j] = A_broadcasted[i, j] - B_broadcasted[i, j]
|
|
||||||
return result
|
|
||||||
|
|
||||||
result3 = my_sub(A, B)
|
|
||||||
|
|
||||||
print("方法1的结果:")
|
|
||||||
print(result1)
|
|
||||||
print("方法2的结果:")
|
|
||||||
print(result2)
|
|
||||||
print("方法3的结果:")
|
|
||||||
print(result3)
|
|
Loading…
x
Reference in New Issue
Block a user