当前位置:   article > 正文

从零开始深度学习0611——pytorch入门之Pytorch 与 numpy  区别+variable+activation+regression+classification+快速搭建_numpy scatter和pytorch

numpy scatter和pytorch

--------------------- Pytorch 与 numpy  区别----------------------------

#########################################################

#########################################################

 

 

Numpy与torch 数据格式的转换

Torch为tensor 张量的形式

 

 

  1. np_data = np.arange(6).reshape((2, 3))
  2. torch_data = torch.from_numpy(np_data)
  3. tensor2array = torch_data.numpy()
  4. print(
  5.     '\nnumpy array:', np_data,          # [[0 1 2], [3 4 5]]
  6.     '\ntorch tensor:', torch_data,      #  0  1  2 \n 3  4  5    [torch.LongTensor of size 2x3]
  7.     '\ntensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
  8. )

运行结果:

 

 

绝对值,平均值,sin值  写法都是一样基本

需要先将数据转换成tensor的形式  torch.FloatTensor(data)

 

  1. # abs
  2. data = [-1, -2, 1, 2]
  3. tensor = torch.FloatTensor(data)  # 32-bit floating point
  4. print(
  5.     '\nabs',
  6.     '\nnumpy: ', np.abs(data),          # [1 2 1 2]
  7.     '\ntorch: ', torch.abs(tensor)      # [1 2 1 2]
  8. )
  9. # sin
  10. print(
  11.     '\nsin',
  12.     '\nnumpy: ', np.sin(data),      # [-0.84147098 -0.90929743  0.84147098  0.90929743]
  13.     '\ntorch: ', torch.sin(tensor)  # [-0.8415 -0.9093  0.8415  0.9093]
  14. )
  15. # mean
  16. print(
  17.     '\nmean',
  18.     '\nnumpy: ', np.mean(data),         # 0.0
  19.     '\ntorch: ', torch.mean(tensor)     # 0.0
  20. )

 

矩阵乘法

原始数据的话,Numpy是直接np.matmul()

或者将原始数据变为array的形式  data = np.array(data)  然后用numpy中另一种矩阵乘法的形式  data.dot(data)

Torch 计算矩阵乘法为 torch.mm(tensor,tensor)

  1. # matrix multiplication
  2. data = [[1,2], [3,4]]
  3. tensor = torch.FloatTensor(data)  # 32-bit floating point
  4. # correct method
  5. print(
  6.     '\nmatrix multiplication (matmul)',
  7.     '\nnumpy: ', np.matmul(data, data),     # [[7, 10], [15, 22]]
  8.     '\ntorch: ', torch.mm(tensor, tensor)   # [[7, 10], [15, 22]]
  9. )
  10. # incorrect method
  11. data = np.array(data)
  12. print(
  13.     '\nmatrix multiplication (dot)',
  14.     '\nnumpy: ', data.dot(data),        # [[7, 10], [15, 22]]
  15.     '\ntorch: ', tensor.dot(tensor)     # this will convert tensor to [1,2,3,4], you'll get 30.0
  16. )

 

 

 

 

 

-------------------------variable-----------------------------------------------

##################################################################

##################################################################

 

  1. tensor = torch.FloatTensor([[1,2],[3,4]])
  2. variable = Variable(tensor,requires_grad=True#false 反向传播时不会计算当前节点的梯度
  3. print(tensor)
  4. print(variable)
  5. print(tensor*tensor)
  6. t_out = torch.mean(tensor*tensor)
  7. v_out = torch.mean(variable*variable)
  8. print(t_out)
  9. print(v_out)
  10. v_out.backward()    # backpropagation from v_out
  11. # v_out = 1/4 * sum(variable*variable)
  12. # the gradients w.r.t the variable, d(v_out)/d(variable) = 1/4*2*variable = variable/2
  13. print(variable.grad)
  14. print(variable)     # this is data in variable format
  15. print(variable.data)    # this is data in tensor format   转换成tensor
  16. print(variable.data.numpy())  # numpy format   将variables 转出成numpy需要转成成tensor  再换成numpy

 

 

---------------------------activation-------------------------------------------

##################################################################

##################################################################

 

先通过torch.linspace() 生成一些假的点

再x.data.numpy() 变成numpy array的形式

因为画图的时候 matplot 需要识别numpy的数据

再绘制torch自带的激活函数

 

 

完整程序:

 

  1. # fake data
  2. x = torch.linspace(-5, 5, 200# x data (tensor), shape=(100, 1)
  3. x = Variable(x)
  4. x_np = x.data.numpy()   # numpy array for plotting  画图的时候 matplot 需要识别numpy的数据
  5. # following are popular activation functions
  6. y_relu = torch.relu(x).data.numpy()
  7. y_sigmoid = torch.sigmoid(x).data.numpy()
  8. y_tanh = torch.tanh(x).data.numpy()
  9. y_softplus = F.softplus(x).data.numpy() # there's no softplus in torch
  10. # y_softmax = torch.softmax(x, dim=0).data.numpy() softmax is a special kind of activation function, it is about probability
  11. # plt to visualize these activation function
  12. plt.figure(1, figsize=(8, 6))
  13. plt.subplot(221)
  14. plt.plot(x_np, y_relu, c='red', label='relu')
  15. plt.ylim((-1, 5))
  16. plt.legend(loc='best')
  17. plt.subplot(222)
  18. plt.plot(x_np, y_sigmoid, c='red', label='sigmoid')
  19. plt.ylim((-0.2, 1.2))
  20. plt.legend(loc='best')
  21. plt.subplot(223)
  22. plt.plot(x_np, y_tanh, c='red', label='tanh')
  23. plt.ylim((-1.2, 1.2))
  24. plt.legend(loc='best')
  25. plt.subplot(224)
  26. plt.plot(x_np, y_softplus, c='red', label='softplus')
  27. plt.ylim((-0.2, 6))
  28. plt.legend(loc='best')
  29. plt.show()

 

 

 

运行结果:

 

 

 

---------------------------regression-------------------------------------------

###################################################################################################################################

 

先通过torch.linespace() 生成数据  模拟拟合曲线

再建类 搭建简单的网络结构

实例化网络

定义优化器和损失函数

训练

 

 

 

 torch.unsqueeze()  将原始数据1维变成2维,因为在torch中只能处理2维的数据

 

Net类的固定写法  记住就好

  1. class Net(torch.nn.Module):  #继承torch.nn.Module的模块
  2.     def __init__(self, n_feature, n_hidden, n_output):
  3.         super(Net, self).__init__()
  4.         self.hidden = torch.nn.Linear(n_feature, n_hidden)   # hidden layer    torch.nn.Linear  返回的是一个方法
  5.         self.predict = torch.nn.Linear(n_hidden, n_output)   # output layer
  6.     def forward(self, x):
  7.         x = F.relu(self.hidden(x))      # activation function for hidden layer
  8.         x = self.predict(x)             # linear output
  9.         return x

 

 

  1. optimizer.zero_grad()   # 每次训练的梯度清零
  2. loss.backward()         # 反向传播,计算梯度
  3. optimizer.step()        # 作用到每步上

 

 

 

 

完整程序:

 

  1. # torch.manual_seed(1)    # reproducible
  2. x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1# x data (tensor), shape=(100, 1)   将1维数据变成2维  因为在torch中只能处理2维的数据
  3. y = x.pow(2) + 0.2*torch.rand(x.size())                 # noisy y data (tensor), shape=(100, 1)
  4. # torch can only train on Variable, so convert them to Variable
  5. # The code below is deprecated in Pytorch 0.4. Now, autograd directly supports tensors
  6. # x, y = Variable(x), Variable(y)
  7. # plt.scatter(x.data.numpy(), y.data.numpy())   #打印散点图
  8. # plt.show()
  9. class Net(torch.nn.Module):  #继承torch.nn.Module的模块
  10.     def __init__(self, n_feature, n_hidden, n_output):
  11.         super(Net, self).__init__()
  12.         self.hidden = torch.nn.Linear(n_feature, n_hidden)   # hidden layer    torch.nn.Linear  返回的是一个方法
  13.         self.predict = torch.nn.Linear(n_hidden, n_output)   # output layer
  14.     def forward(self, x):
  15.         x = F.relu(self.hidden(x))      # activation function for hidden layer
  16.         x = self.predict(x)             # linear output
  17.         return x
  18. net = Net(n_feature=1, n_hidden=10, n_output=1)     # define the network
  19. print(net)  # net architecture   会输出搭建的网络的结构
  20. optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
  21. loss_func = torch.nn.MSELoss()  # this is for regression mean squared loss   回归问题用均方差误差就可以了
  22. plt.ion()   # something about plotting
  23. for t in range(200):
  24.     prediction = net(x)     # input x and predict based on x   这里的net调用的是forward函数
  25.     loss = loss_func(prediction, y)     # must be (1. nn output, 2. target)
  26.     optimizer.zero_grad()   # clear gradients for next train  每次训练的梯度清零
  27.     loss.backward()         # backpropagation, compute gradients 
  28.     optimizer.step()        # apply gradients
  29.     if t % 5 == 0:
  30.         # plot and show learning process
  31.         plt.cla()
  32.         plt.scatter(x.data.numpy(), y.data.numpy())
  33.         plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
  34.         plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color''red'})
  35.         plt.pause(0.1)
  36. plt.ioff()
  37. plt.show()

 

运行结果:

 

 

---------------------------classification-----------------------------------------

####################################################################################################################################

 

 

合并数据 torch.cat()   x默认是FloatTensor的形式

 Y默认是LongTensor的形式

x = torch.cat((x0, x1), 0).type(torch.FloatTensor) 

y = torch.cat((y0, y1), ).type(torch.LongTensor)

 

回归问题就用MSE 均方误差  分类问题的话就要使用CrossEntropyLoss的损失函数

 

optimizer.zero_grad()   #清空上一步的残余更新参数值
loss.backward()         #误差反向传播, 计算参数更新值
optimizer.step()        # 将参数更新值施加到 net 的 parameters 上

 

 

torch.max(out, 1)[1]

# torch.max(input, dim, keepdim=False, out=None) -> (Tensor, LongTensor)   按维度dim 返回最大值
# torch.max(out, 1) 表示返回每一行中最大值的那个元素,且返回其索引(返回最大元素在这一行的列索引)  index [0,1] ==>  [元素,索引值]
# 这里第一个1 表示维度的意思   第二个1 表示获得第二个位置的东西
# 前面损失函数是CrossEntropyLoss  计算的softmax概率值

# 这里,因为上面合并数据后,x是每一行都有一个x0的点,一个x1的点    y是对应的标签x0是0 x1标签是1
# 所以softmax计算完的概率 通过 torch.max(out, 1)[1]  得到每个点最大概率的索引值也是0或者1  正好和标签0,1对应

 

 

完整程序:

 

  1. # torch.manual_seed(1)    # reproducible
  2. # make fake data
  3. n_data = torch.ones(100, 2)         # 数据的基本形态
  4. x0 = torch.normal(2*n_data, 1)      # class0 x data (tensor), shape=(100, 2)  正态分布
  5. y0 = torch.zeros(100)               # class0 y data (tensor), shape=(100, 1)  给x0的标签,都是0
  6. x1 = torch.normal(-2*n_data, 1)     # class1 x data (tensor), shape=(100, 2)  正态分布
  7. y1 = torch.ones(100)                # class1 y data (tensor), shape=(100, 1)  给x1的标签,都是1
  8. # 注意 x, y 数据的数据形式是一定要像下面一样 (torch.cat 是在合并数据)
  9. # 按列合并数据   x0是第一列,x1是第二列 所以每一行是有一个x0的点 一个x1的点  所以下面 输入值n_feature=2
  10. x = torch.cat((x0, x1), 0).type(torch.FloatTensor)  # shape (200, 2) FloatTensor = 32-bit floating   在torch中 它的数据默认一定是FloatTensor的形式
  11. y = torch.cat((y0, y1), ).type(torch.LongTensor)    # shape (200,) LongTensor = 64-bit integer  在torch中 它的标签默认一定是LongTenser的形式
  12. # The code below is deprecated in Pytorch 0.4. Now, autograd directly supports tensors
  13. # x, y = Variable(x), Variable(y)
  14. # plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn')
  15. # plt.show()
  16. class Net(torch.nn.Module):
  17.     def __init__(self, n_feature, n_hidden, n_output):
  18.         super(Net, self).__init__()
  19.         self.hidden = torch.nn.Linear(n_feature, n_hidden)   # hidden layer
  20.         self.out = torch.nn.Linear(n_hidden, n_output)   # output layer
  21.     def forward(self, x):
  22.         x = F.relu(self.hidden(x))      # activation function for hidden layer
  23.         x = self.out(x)
  24.         return x
  25. net = Net(n_feature=2, n_hidden=10, n_output=2)     # define the network
  26. print(net)  # net architecture
  27. optimizer = torch.optim.SGD(net.parameters(), lr=0.02)
  28. loss_func = torch.nn.CrossEntropyLoss()  # the target label is NOT an one-hotted  回归问题就用MSE 均方误差  分类问题的话就要使用CrossEntropyLoss的损失函数
  29. plt.ion()   # something about plotting
  30. for t in range(100):
  31.     out = net(x)                 # input x and predict based on x
  32.     loss = loss_func(out, y)     # must be (1. nn output, 2. target), the target label is NOT one-hotted
  33.     optimizer.zero_grad()   # clear gradients for next train       清空上一步的残余更新参数值
  34.     loss.backward()         # backpropagation, compute gradients   误差反向传播, 计算参数更新值
  35.     optimizer.step()        # apply gradients                      将参数更新值施加到 net 的 parameters 上
  36.     if t % 2 == 0:
  37.         # plot and show learning process
  38.         plt.cla()
  39.         prediction = torch.max(out, 1)[1]
  40.         # torch.max(input, dim, keepdim=False, out=None) -> (Tensor, LongTensor)   按维度dim 返回最大值
  41.         # torch.max(out, 1) 表示返回每一行中最大值的那个元素,且返回其索引(返回最大元素在这一行的列索引)  index [0,1] ==>  [元素,索引值]
  42.         # 这里第一个1 表示维度的意思   第二个1 表示获得第二个位置的东西
  43.         # 前面损失函数是CrossEntropyLoss  计算的softmax概率值
  44.         # 这里,因为上面合并数据后,x是每一行都有一个x0的点,一个x1的点    y是对应的标签x0是0 x1标签是1
  45.         # 所以softmax计算完的概率 通过 torch.max(out, 1)[1]  得到每个点最大概率的索引值也是0或者1  正好和标签0,1对应
  46.         pred_y = prediction.data.numpy()
  47.         target_y = y.data.numpy()
  48.         plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=pred_y, s=100, lw=0, cmap='RdYlGn')
  49.         accuracy = float((pred_y == target_y).astype(int).sum()) / float(target_y.size)  # 预测中有多少和真实值一样
  50.         plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color''red'})
  51.         plt.pause(0.1)
  52. plt.ioff()
  53. plt.show()

 

运行结果:

 

--------------------------快速搭建---------------------------------------------

####################################################################################################################################

 

F.relu()   relu为一个功能

 

torch.nn.Sequential  中  torch.nn.ReLU(),   ReLU()为一个类

 

 

完整程序:

 

  1. # replace following class code with an easy sequential network
  2. class Net(torch.nn.Module):
  3.     def __init__(self, n_feature, n_hidden, n_output):
  4.         super(Net, self).__init__()
  5.         self.hidden = torch.nn.Linear(n_feature, n_hidden)   # hidden layer
  6.         self.predict = torch.nn.Linear(n_hidden, n_output)   # output layer
  7.     def forward(self, x):
  8.         x = F.relu(self.hidden(x))      # activation function for hidden layer
  9.         x = self.predict(x)             # linear output
  10.         return x
  11. net1 = Net(1, 10, 1)
  12. # easy and fast way to build your network
  13. net2 = torch.nn.Sequential(
  14.     torch.nn.Linear(1, 10),
  15.     torch.nn.ReLU(),    
  16.     torch.nn.Linear(10, 1)
  17. )
  18. print(net1)     # net1 architecture
  19. print(net2)     # net2 architecture

 

运行结果:

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/747352
推荐阅读
相关标签
  

闽ICP备14008679号