import numpy as np
import torch
# cpu tensor 转 numpy
arr = torch.zeros(3, device='cpu') # 等同于 arr = torch.zeros(3)
print(arr) # tensor([0., 0., 0.])
arr2 = arr.numpy()
print(arr2) # [0. 0. 0.]
# numpy 转 cpu tensor
num = np.zeros(3)
print(num) # [0. 0. 0.]
num2 = torch.from_numpy(num)
print(num2) # tensor([0., 0., 0.], dtype=torch.float64)
# GPU tensor 转 numpy
arr3 = torch.zeros(3, device='cuda')
print(arr3) # tensor([0., 0., 0.], device='cuda:0')
arr4 = arr3.detach().cpu().numpy()
print(arr4) # [0. 0. 0.]
二值交叉损失函数 binary_cross_entropy
import numpy as np
import torch
import torch.nn.functional as F
if __name__ == "__main__":
print(1)
inputs = torch.randn(3, 2)
target = torch.rand(3, 2)
loss = F.binary_cross_entropy(torch.sigmoid(inputs), target)
print(inputs.shape) # torch.Size([3, 2])
print(target.shape) # torch.Size([3, 2])
print(loss) # tensor(0.7674)
data = []
label = []
for i in range(4):
data.append(inputs.numpy())
label.append(target.numpy())
data_tenser = torch.from_numpy(np.array(data))
label_tenser = torch.from_numpy(np.array(label))
print(data_tenser.shape) # torch.Size([4, 3, 2])
print(label_tenser.shape) # torch.Size([4, 3, 2])
error = F.binary_cross_entropy(torch.sigmoid(data_tenser), label_tenser)
print(error) # tensor(0.7674)