nparray和tensor的相互转化(解决TypeError报错)

在学习李沐:动手学深度学习第13章中,原教材代码如下:

import numpy as np
import os
import matplotlib.pyplot as plt
import torch
from d2l import torch as d2l
print(os.getcwd())
d2l.set_figsize()
img = d2l.plt.imread('./img/OIP-C.jpg')
d2l.plt.imshow(img)
plt.show()

def box_corner_to_center(boxes):
    """从(左上,右下)转换到(中间,宽度,高度)"""
    x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
    cx = (x1 + x2) / 2
    cy = (y1 + y2) / 2
    w = x2 - x1
    h = y2 - y1
    boxes = torch.stack((cx, cy, w, h), axis=-1)
    # stack在维度上连接(concatenate)若干个张量,-i为倒数第i个维度
    return boxes

def box_center_to_corner(boxes):
    """从(中间,宽度,高度)转换到(左上,右下)"""
    cx, cy, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3] # 列
    x1 = cx - 0.5 * w
    y1 = cy - 0.5 * h
    x2 = cx + 0.5 * w
    y2 = cy + 0.5 * h
    boxes = torch.stack((x1, y1, x2, y2), axis=-1)
    return boxes

# bbox是边界框的英文缩写
dog_bbox, cat_bbox = [60.0, 45.0, 378.0, 516.0], [400.0, 112.0, 655.0, 493.0]
boxes = np.array((dog_bbox, cat_bbox))
print(box_center_to_corner(box_corner_to_center(boxes)) == boxes)

运行报以下错误:TypeError: expected Tensor as element 0 in argument 0, but got numpy.ndarray

错误原因就是需要将nparray转化成Tensor类型,在原来代码中最后一行之前加入:

boxes = torch.from_numpy(boxes)

问题解决。输出:

tensor([[True, True, True, True],
        [True, True, True, True]])

小结:

1.nparray转化为Tensor

boxes = torch.from_numpy(boxes)

2.Tensor转化为nparray

x=x.numpy()

你可能感兴趣的:(python,深度学习,开发语言)