数据操作)
一.Pytorch1.1新建torch张量以及查看属性改变形状新建torch张量x torch.arange(20).reshape(4,-1)#元素从0到19x torch.zeros(4,4)#还有.ones和.randnx torch([[1,2],[2,3]])#也可以自己去写元素查看张量形状print(x.shape,x.numel())改变张量形状X x.reshape(5,-1)索引和切片1.2张量的计算基本运算x torch.tensor([1.0, 2, 4, 8])y torch.tensor([2, 2, 2, 2])x y, x - y, x * y, x / y, x ** y xy # **运算符是求幂运算都是对应位置的元素之间的计算torch.exp(x)将张量按照不同的维度通成一个X torch.arange(12, dtypetorch.float32).reshape((3,4))Y torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])torch.cat((X, Y), dim0), torch.cat((X, Y), dim1)广播机制按照维度数为一的维度进行广播a torch.arange(3).reshape((3, 1))b torch.arange(2).reshape((1, 2))a, b1.3节省内存x[:] xy#x的地址不变不分配新内存xy#同上1.4转化为其他数据类型#将numpy转化为tensor张量 A X.numpy() B torch.tensor(A) type(A), type(B) #将标量张量转化为内置数据类型 a torch.tensor([3.5]) a, a.item(), float(a), int(a)1.5线性代数计算张量乘标量形状不变元素分别相乘torch.dot(x,x)#向量点积torch.mv(s,x)#矩阵和向量相乘torch.mm(s,v)#矩阵乘法A A.T#矩阵转置B A.clone()#分配新内存将A的副本给B降维A.sum()#不论A是几维数据都按照0、1的唯独顺序倒着相加求和。A.sum(axis0)#指定降维的轴sum_A A.sum(axis1, keepdimsTrue)#指定求合后维度不变沿某个轴计算A元素的累积总和 比如axis0按行计算可以调用cumsum函数。 此函数不会沿任何轴降低输入张量的维度。A.cumsum(axis0)范数一种求和的方式函数1.向量的范数L2级范数每个元素平方的和再相加torch.norm(u)L1级范数每个元素绝对值的和torch.abs(u).sum()2. 矩阵的范数torch.norm(torch.ones((4, 9)))1.6自动微分import torch x torch.arange(4.0) x x.requires_grad_(True) # 等价于xtorch.arange(4.0,requires_gradTrue) x.grad # 默认值是None y 2 * torch.dot(x, x) y y.backward()分离计算阻断梯度传播x.grad.zero_() y x * x u y.detach() z u * x z.sum().backward() x.grad u二.pandas读取数据并转化为tensor数据预处理#读取csv数据 data pd.read_csv(data_file) print(data)处理缺失值主要有插值法和删除法1.插值法#用同一列的均值进行替代缺失值、inputs, outputs data.iloc[:, 0:2], data.iloc[:, 2]inputs inputs.fillna(inputs.mean())print(inputs)2.将类别型数据转化为数字表示。对于inputs中的类别值或离散值我们将“NaN”视为一个类别。 由于“巷子类型”“Alley”列只接受两种类型的类别值“Pave”和“NaN”pandas可以自动将此列转换为两列“Alley_Pave”和“Alley_nan”。 巷子类型为“Pave”的行会将“Alley_Pave”的值设置为1“Alley_nan”的值设置为0。 缺少巷子类型的行会将“Alley_Pave”和“Alley_nan”分别设置为0和1。inputs pd.get_dummies(inputs, dummy_naTrue)print(inputs)3.将读入的数据转化为tensor类型import torch X torch.tensor(inputs.to_numpy(dtypefloat)) y torch.tensor(outputs.to_numpy(dtypefloat)) X, y三.matplotlib可视化plot函数配置def use_svg_display(): #save 使用svg格式在Jupyter中显示绘图 backend_inline.set_matplotlib_formats(svg)def set_figsize(figsize(3.5, 2.5)): #save 设置matplotlib的图表大小 use_svg_display() d2l.plt.rcParams[figure.figsize] figsizedef set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend): 设置matplotlib的轴 axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) axes.set_xscale(xscale) axes.set_yscale(yscale) axes.set_xlim(xlim) axes.set_ylim(ylim) if legend: axes.legend(legend) axes.grid()#save def plot(X, YNone, xlabelNone, ylabelNone, legendNone, xlimNone, ylimNone, xscalelinear, yscalelinear, fmts(-, m--, g-., r:), figsize(3.5, 2.5), axesNone): 绘制数据点 if legend is None: legend [] set_figsize(figsize) axes axes if axes else d2l.plt.gca() # 如果X有一个轴输出True def has_one_axis(X): return (hasattr(X, ndim) and X.ndim 1 or isinstance(X, list) and not hasattr(X[0], __len__)) if has_one_axis(X): X [X] if Y is None: X, Y [[]] * len(X), X elif has_one_axis(Y): Y [Y] if len(X) ! len(Y): X X * len(Y) axes.cla() for x, y, fmt in zip(X, Y, fmts): if len(x): axes.plot(x, y, fmt) else: axes.plot(y, fmt) set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)然后调用x np.arange(0, 3, 0.1) plot(x, [f(x), 2 * x - 3], x, f(x), legend[f(x), Tangent line (x1)])即可绘制二维图像的切线图