将numpy转为tensor数据类型Tensor、tensor、from_numpy、as_tensor
data = np.array([[1, 2, 3],[4,5,6]])
Tensor = torch.Tensor(data)
tensor = torch.tensor(data)
from_numpy = torch.from_numpy(data)
from_numpy_type = torch.from_numpy(data).type(torch.float32)
as_tensor = torch.as_tensor(data)
print('Tensor:', Tensor, ',dtype =', Tensor.dtype)
print('tensor:', tensor, ',dtype =', tensor.dtype)
print('from_numpy:', from_numpy, ',dtype =', from_numpy.dtype)
print('from_numpy_type:', from_numpy_type, ',dtype =', from_numpy_type.dtype)
print('as_tensor:', as_tensor, ',dtype =', as_tensor.dtype)
改变numpy原数组的数据,观察tensor数据的变化
data[0][0] = 0
print('改变后:')
print('Tensor:', Tensor, ',dtype =', Tensor.dtype)
print('tensor:', tensor, ',dtype =', tensor.dtype)
print('from_numpy:', from_numpy, ',dtype =', from_numpy.dtype)
print('from_numpy_type:', from_numpy_type, ',dtype =', from_numpy_type.dtype)
print('as_tensor:', as_tensor, ',dtype =', as_tensor.dtype)
改变tensor数据后观察numpy原数组的变化
from_numpy_type[0][1] = 23
print('from_numpy_type', data)
tensor[0][1] = 23
print('tensor', data)
Tensor[0][1] = 23
print('Tensor', data)
as_tensor[0][1] = 23
print('as_tensor', data)
from_numpy[0][1] = 24
print('from_numpy', data)
创建一个简单的网络
class Tudui(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(3, 1)
def forward(self, input):
input = input+1
return input
tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.tensor(data,dtype=torch.float32)
output = tudui(x)
print(output)
print(x)
print(data)
tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.from_numpy(data).type(torch.float32)
output = tudui(x)
print(output)
print(x)
print(data)
tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.from_numpy(data)
output = tudui(x)
print(output)
print(x)
print(data)
class Tudui(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(3, 1)
def forward(self, input):
input += 1
return input
tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.from_numpy(data).type(torch.float32)
output = tudui(x)
print(output)
print(x)
print(data)
tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.from_numpy(data)
output = tudui(x)
print(output)
print(x)
print(data)
tudui = Tudui()
data = np.array([[1,2,3],[4,5,6]])
x = torch.tensor(data,dtype=torch.float32)
output = tudui(x)
print(output)
print(x)
print(data)