Python - torch与numpy的转换

import math
import torch
import numpy as np
import pandas as pd

A = np.array(pd.DataFrame(np.arange(16).reshape(4,4)))
print(A, '\n')


B = torch.from_numpy(A)
print(B,'\n')

C = B.numpy()
C[1] = 0
print(A, '\n')
print(B)

Out:

Python - torch与numpy的转换_第1张图片

注意两种转换都不占用新内存,即一个数据改变,转换的其他数据都会改变

示例:

import math
import torch
import numpy as np
import pandas as pd

A = np.array(pd.DataFrame(np.arange(16).reshape(4,4)))
print(A, '\n')


B = torch.from_numpy(A)
print(B)

C = B.numpy()
C[1] = 0
print(A, '\n')
print(B)

Out:
Python - torch与numpy的转换_第2张图片

你可能感兴趣的:(Python - torch与numpy的转换)