AI课程笔记——深度学习框架Pytorch
1pytorch基本数据类型
1.1回顾:Python的6大数据类型
# 数字:Number【不可变】
# 列表:List【可变】
# 字典:Dictionary【可变】
# 元组:Tuple【不可变】
# 字符串:String【可变】
# 集合:Set【可变】
1.2Pytorch数据类型:张量(一种)
# All is about Tensor(标量和向量都属于张量)
1.2.1将字符串转化称为张量(Embedding)
* 1.word2vec
* 2.glove
1.3实战尝试
1.3.1创建张量+张量的内置函数
import torch
a = torch. tensor( 1 )
print ( a)
print ( a. type ( ) )
print ( type ( a) )
print ( a. device)
print ( a. shape)
print ( a. size( ) )
print ( isinstance ( a, torch. LongTensor) )
print ( a. dim( ) )
print ( len ( a. shape) )
print ( a. item( ) )
1.3.2创建高维向量
一维向量相当于神经网络的线性输入层(以向量的形式进行输入)->linear layer input
import torch
b = torch. tensor( [ 1 , 2 , 3 , 4 ] )
print ( b)
print ( b. type ( ) )
print ( b. dim( ) )
print ( b. device)
print ( b. shape)
二维张量可以看成是batch个一维向量的输入(batch是需要训练的数据的个数)->batch+linear input
import torch
c = torch. tensor( [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] ] )
print ( c)
print ( c. type ( ) )
print ( c. dim( ) )
print ( c. device)
print ( c. shape)
3维张量看成一张图片[3,224,224]表示三通道,每通道都是224*224大小的2维向量
import torch
d = torch. tensor( [ [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] ] , [ [ 9 , 8 , 7 , 6 ] , [ 5 , 4 , 3 , 2 ] ] ] )
print ( d)
print ( d. type ( ) )
print ( d. dim( ) )
print ( d. device)
print ( d. shape)
print ( torch. numel( d) )
模型一般都是4维张量,[B,3,224,224]前面还有一个Batch维度
1.4普通张量的创建(直接利用api&借由numpy库转化)
a = torch. tensor( 4 )
b = torch. FloatTensor( 4 )
import numpy as np
a = np. array( [ 2 , 3 , 3 ] )
print ( a)
b = torch. from_numpy( a)
print ( b)
1.5特殊张量的创建(全1&全0张量&对角矩阵等)
import torch
c = torch. ones( 3 , 3 )
print ( c)
d = torch. zeros( 4 , 4 )
print ( d)
e = torch. eye( 3 , 3 )
print ( e)
f = torch. arange( 0 , 10 , 1 )
print ( f)
print ( f. dim( ) )
g = torch. linspace( 0 , 10 , 4 )
print ( g)
注:创建全0全1矩阵可以在模型中作为初始化lebel使用
注:创建等差向量可以作为模型索引的工具
1.6无初始化的张量创建
import torch
a = torch. empty( ( 2 , 3 ) , dtype = torch. int32, device = "cpu" )
print ( a)
b = torch. Tensor( 1 , 2 )
c = torch. tensor( [ 2 , 3 ] )
print ( b)
print ( c)
d = torch. Tensor( 2 , 3 )
torch. set_default_tensor_type( torch. DoubleTensor)
b = torch. Tensor( 3 , 3 )
print ( a)
print ( b)
print ( a. type ( ) )
print ( b. type ( ) )
e = torch. randn( 3 , 3 )
print ( e)
f = torch. randperm( 10 )
print ( f)
1.7小结
# 利用tensor进行有初始值的初始化操作,传入的值是需要初始化的内容
# 利用Tensor进行没有初始值的初始化操作,传入的值是需要创建的张量的大小