pytorch张量的简介与创建(代码)
生活随笔
收集整理的這篇文章主要介紹了
pytorch张量的简介与创建(代码)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
# -*- coding:utf-8 -*-
"""
@file name : lesson-02.py
@author : TingsongYu https://github.com/TingsongYu
@date : 2018-08-26
@brief : 張量的創(chuàng)建
"""
import torch
import numpy as np
torch.manual_seed(1)# =============================== example 1 ===============================
# 通過(guò)torch.tensor創(chuàng)建張量
#
# flag = True
flag = False
if flag:arr = np.ones((3, 3))print("ndarray的數(shù)據(jù)類型:", arr.dtype)#t = torch.tensor(arr, device='cuda')t = torch.tensor(arr)print(t)
# =============================== example 2 ===============================
# 通過(guò)torch.from_numpy創(chuàng)建張量
# flag = True
flag = False
if flag:arr = np.array([[1, 2, 3], [4, 5, 6]])t = torch.from_numpy(arr)# print("numpy array: ", arr)# print("tensor : ", t)# print("\n修改arr")# arr[0, 0] = 0# print("numpy array: ", arr)# print("tensor : ", t)print("\n修改tensor")t[0, 0] = -1print("numpy array: ", arr)print("tensor : ", t)# =============================== example 3 ===============================
# 通過(guò)torch.zeros創(chuàng)建張量
# flag = True
flag = False
if flag:out_t = torch.tensor([1])t = torch.zeros((3, 3), out=out_t)print(t, '\n', out_t)print(id(t), id(out_t), id(t) == id(out_t))# =============================== example 4 ===============================
# 通過(guò)torch.full創(chuàng)建全1張量
# flag = True
flag = False
if flag:t = torch.full((3, 3), 10.0)print(t)# =============================== example 5 ===============================
# 通過(guò)torch.arange創(chuàng)建等差數(shù)列張量
# flag = True
flag = False
if flag:t = torch.arange(2, 10, 2)print(t)# =============================== example 6 ===============================
# 通過(guò)torch.linspace創(chuàng)建均分?jǐn)?shù)列張量
# flag = True
flag = False
if flag:# t = torch.linspace(2, 10, 5)t = torch.linspace(2, 10, 6)print(t)# =============================== example 7 ===============================
# 通過(guò)torch.normal創(chuàng)建正態(tài)分布張量
flag = True
# flag = False
if flag:# # mean:張量 std: 張量# mean = torch.arange(1, 5, dtype=torch.float)# std = torch.arange(1, 5, dtype=torch.float)# t_normal = torch.normal(mean, std)# print("mean:{}\nstd:{}".format(mean, std))# print(t_normal)# mean:標(biāo)量 std: 標(biāo)量# t_normal = torch.normal(0., 1., size=(4,))# print(t_normal)# mean:張量 std: 標(biāo)量mean = torch.arange(1, 5, dtype=torch.float)std = 1t_normal = torch.normal(mean, std)print("mean:{}\nstd:{}".format(mean, std))print(t_normal)
?
總結(jié)
以上是生活随笔為你收集整理的pytorch张量的简介与创建(代码)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 神经网络与卷积神经网络入门(保证让你懂)
- 下一篇: PHP-mysql基础