借助 PyTorch 实现深度神经网络 - 张量和数据集 - 第 1 周 | Coursera
张量概述
张量运算的本质是向量和矩阵运算。神经网络的输入、输出、参数都将采用张量进行。Pytorch中的张量可以和Python中的numpy相互转换,这使得Pytorch在GPU上应用成为可能。神经网络中的参数是允许计算梯度或导数的张量。
一维张量
三种一维张量:
数据类型:
- "data type"和"dtype"是指相同的概念,即数据类型。它们用于描述张量(tensor)中存储的数据的类型。
- tensor types是张量的类型
求得张量的维度
使用视图重塑张量
numpy 和 tensor 的转换(注意 t 和 n 指向一个地址块), t 改则 n 改
pandas 和 tensor 的转换
取tensor中的数值
张量加法
张量*标量
张量*张量
点积
linspace的用法 + matplotlib辅助画图
二维张量
类比于数据库中的表,二位张量是一个矩阵,每一行代表不同的样本,每一列代表对应一个特征。
二维张量的创建:
张量的维度和大小,以及元素数量:
二维张量加法:
标量*张量:
元素乘积:
矩阵乘积:
注意:
这两个结果不一样是因为在索引和切片时使用了不同的语法。
在第二个例子中,tensor_ques[1:3][1]=0
,首先使用切片tensor_ques[1:3]
选择了第二行和第三行,然后再使用索引[1]
选择了第二行,并将其赋值为0。但是这种写法是错误的,因为切片操作返回的是一个新的张量,而不是原始张量的视图。
Pytorch中的微分
微分:
偏微分:
总结:
创建简单数据集
考虑DataSet对象dataSet,len(dataset)的输出是DataSet对象中的样本数,即下图中的100
迭代dataset:
dataset[i]会自动调用__getitem__(self,index)函数
Transform:
Transform Pipeline(使用Compose函数):
自己手打一遍:
数据集
对于图像的dataset类:
# Create your own dataset objectclass Dataset(Dataset):# Constructordef __init__(self, csv_file, data_dir, transform=None):# Image directoryself.data_dir=data_dir# The transform is goint to be used on imageself.transform = transformdata_dircsv_file=os.path.join(self.data_dir,csv_file)# Load the CSV file contians image infoself.data_name= pd.read_csv(data_dircsv_file)# Number of images in datasetself.len=self.data_name.shape[0] # Get the lengthdef __len__(self):return self.len# Getterdef __getitem__(self, idx):# Image file pathimg_name=os.path.join(self.data_dir,self.data_name.iloc[idx, 1])# Open image fileimage = Image.open(img_name)# The class label for the imagey = self.data_name.iloc[idx, 0]# If there is any transform method, apply it onto the imageif self.transform:image = self.transform(image)return image, y
基本情况与简单数据集的操作类似。