张量的随机创建包含的方法有:torch.rand(),torch.randlike(),torch.randn(),torch.randnloike(),torch.randint(),torch.randint_like()和torch.randperm()。
torch.tensor() 用数据创建一个张量。参数:data:输入数据,可以是list,tuple,numpy,scalar或者其他类型。dtype:可选参数,设置data的数据类型,默认使用data原来的type。device:可选参数,返回张量的设备,默认使用当前设备。有cpu张量和cuda张量两种形式。requires_grad:可选参数,bool。默认False,如果自动梯度会在返回的张量上记录操作。pin_memory:可选参数,bool。默认False,只在cpu张量上有效。设置之后返回的张量会被分配到指定的内存。例子 >>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) tensor([[ 0.1000, 1.2000], [ 2.2000, 3.1000], [ 4.9000, 5.2000]]) >>> torch.tensor([0, 1]) # 类型参考原来的数据 tensor([ 0, 1]) >>> torch.tensor([[0.11111, 0.222222, 0.3333333]], dtype=torch.float64, device=torch.device('cuda:0')) # 创建一个cuda上的双精度张量 tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0') >>> torch.tensor(3.14159) # 生成一个标量 (0维的张量) tensor(3.1416) >>> torch.tensor([]) # 生成一个空张量 tensor([])torch.as_tensor(data,dtype=None,device=None)->Tensor 把数据转成TensorFlow张量的形式,如果数据本身就是指定的dtype和device,则不会改变。参数data(数组形式):生成张量的初始数据,可以是list,tuple,ndarray,scalar等等。dtype(torch的dtype,可选参数):指定返回张量的数据类型,默认为None,根据原数据推出类型。device(torch的device,可选参数):默认None,和dtype参数差不多,有CPU Tensor和CUDA Tensor两种形式。例子 >>> a = numpy.array([1, 2, 3]) >>> t = torch.as_tensor(a) >>> t tensor([ 1, 2, 3]) >>> t[0] = -1 >>> a array([-1, 2, 3]) >>> a = numpy.array([1, 2, 3]) >>> t = torch.as_tensor(a, device=torch.device('cuda')) >>> t tensor([ 1, 2, 3]) >>> t[0] = -1 >>> a array([1, 2, 3])torch.asstrided(input,size,stride,storageoffset=0)->Tensor 生成一个指定形状的张量。参数input(Tensor):输入张量size(tuples或ints):输出张量的形状stride(tuple或ints):输出张量的步长storage_offset(int,可选参数):输出张量在存储中的偏移例子 >>> x = torch.randn(3, 3) >>> x tensor([[ 0.9039, 0.6291, 1.0795], [ 0.1586, 2.1939, -0.4900], [-0.1909, -0.7503, 1.9355]]) >>> t = torch.as_strided(x, (2, 2), (1, 2)) >>> t tensor([[0.9039, 1.0795], [0.6291, 0.1586]]) >>> t = torch.as_strided(x, (2, 2), (1, 2), 1) tensor([[0.6291, 0.1586], [1.0795, 2.1939]])torch.from_numpy(ndarray)->Tensor 把ndarray转成张量,返回的张量和ndarray共用相同内存,所以修改ndarray会改变tensor,反之亦然。而且tensor是没法调整大小的。 支持的ndarray的类型有numpy.float64,numpy.float32,numpy.float16,numpy.int64,numpy.int32,numpy.int16,nummpy.int8,numpy.uint8,numpy.bool例子 >>> a = numpy.array([1, 2, 3]) >>> t = torch.from_numpy(a) >>> t tensor([ 1, 2, 3]) >>> t[0] = -1 >>> a array([-1, 2, 3])torch.zeros(*size,out=None,dtype=None,layout=torch.strided,device=None,requrired_grad=False)->Tensor 返回全是0的张量 参数size(int):可以是list,tupleout(张量,可选参数):输出的张量dtype(torch.dtype,可选参数):默认None,使用全局默认torch.setdefaulttensor_type()的值。layout(torch.layout,可选参数):默认是torch.strided,指定返回张量的layoutdevice(可选参数):默认None返回当前的张量类型requires_grad(bool,可选参数):默认False。例子 >>> torch.zeros(2, 3) tensor([[ 0., 0., 0.], [ 0., 0., 0.]]) >>> torch.zeros(5) tensor([ 0., 0., 0., 0., 0.]) ---来自腾讯云社区的---Rare0716Python|张量创建操作[2]---Rare0716
张量创建操作

微信扫一扫打赏
支付宝扫一扫打赏