pytorch笔记5--分类

一、描述:

用简单的例子看一下神经网络是怎么分类的:

二、步骤

1.创建数据

import torch
import matplotlib.pyplot as plt
import torch.functional as func
from torch.autograd import Variable
import torch.nn

#有两组数据,一组数据属于分类1,一组数据属于分类0

#创建数据
n_data=torch.ones(100,2)
data1=torch.normal(2*n_data,1)   #其中一组数据的x坐标和y坐标都包含再data1中
label1=torch.zeros(100)           #data1这堆数据的标签都是0
data2=torch.normal(-2*n_data,1)  #另一堆数据
label2=torch.ones(100)            #data2这堆数据的标签都是1
#数据data和每个数据所对应的分类labels
data=torch.cat((data1,data2),0).type(torch.FloatTensor)   #所有的数据.cat:合并数据集
labels=torch.cat((label1,label2),0).type(torch.LongTensor)     #所有标签

注:

  •  torch.normal()函数
torch.normal(measn,std,out=None) 返回一个张量,包含从给定参数means,std的离散正态分布中抽取随机数。
means:一个张量,包含每个输出元素相关的正态分布的均值。
std:一个张量,包含每个输出元素相关正太分布的标准差。标准差必须是个正数.
均值和标准差的形状可以不匹配,但每个张量的元素个数须相同
import torch

# method1,均值和标准差均为矩阵
means=2.0*torch.ones(3,2)
std=torch.ones(3,2)
tensor1=torch.normal(means,std)
print('tensor1:\n',tensor1)

# method2,样本共享均值
tensor2=torch.normal(1,torch.arange(1.0,4.0))
print('tensor2:\n',tensor2)

# method3,样本共享标准差
tensor3=torch.normal(torch.arange(1,0,-0.2),0.2)
print('tensor3:\n',tensor3)

运行结果:

tensor1:
 tensor([[ 2.2218,  1.7356],
        [ 2.3562,  1.8443],
        [-0.3917,  1.4340]])
tensor2:
 tensor([0.1562, 2.5264, 0.4343])
tensor3:
 tensor([1.2139, 0.6693, 0.7391, 0.5015, 0.4305])
  • torch.cat()函数:合并两个矩阵
import torch

tensor1=torch.rand((3,2))
tensor2=torch.normal(torch.ones(3,2),0.4)

tensor_cat0=torch.cat((tensor1,tensor2),0)
tensor_cat1=torch.cat((tensor1,tensor2),1)
print(
    'tensor_cat0:\n',tensor_cat0,
    '\ntensor_cat1:\n',tensor_cat1
)

运行结果:

tensor_cat0:
 tensor([[0.1172, 0.8874],
        [0.5329, 0.3272],
        [0.8525, 0.9647],
        [1.4242, 0.8938],
        [0.6884, 1.8814],
        [0.9747, 0.9873]]) 
tensor_cat1:
 tensor([[0.1172, 0.8874, 1.4242, 0.8938],
        [0.5329, 0.3272, 0.6884, 1.8814],
        [0.8525, 0.9647, 0.9747, 0.9873]])

2.搭建神经网络

#快速搭建神经网络
x=Variable(data)
y=Variable(labels)
#通过在Sequential里面搭神经层的方法构建神经网络
net=torch.nn.Sequential(
    torch.nn.Linear(2,10),
    torch.nn.ReLU(),
    torch.nn.Linear(10,10),
    torch.nn.ReLU(),
    torch.nn.Linear(10,2)
)       #输入特征是2个:坐标x和y,输出结果的分类为0和1

3.训练网络并可视化

#训练网络
optomizer=torch.optim.SGD(net.parameters(),lr=0.01)
loss_func=torch.nn.CrossEntropyLoss()  #交叉熵损失函数

for i in range(100):
    out=net.forward(x)
    loss=loss_func(out,y)

    optomizer.zero_grad()
    loss.backward()
    optomizer.step()

    #可视化
    if i%2==0:
        plt.cla()                        #清楚原来的图像
        prediction=torch.max(out,1)[1]   #torch.max(out,1)返回每一行的最大值的值和索引。prediction表示所有最大值的索引,也就是分类
        pred_y=prediction.data.numpy()
        target_y=y.data.numpy()
        plt.scatter(x.data.numpy()[:,0],x.data.numpy()[:,1],c=pred_y,s=100,cmap='RdYlGn') #c:色彩或颜色序列,s:点的大小
        accuracy=float((pred_y==target_y).astype(int).sum())/float(target_y.size)  #astype()类型转换
        plt.text(1.5,-4,'Accuracy=%.2f'%accuracy,fontdict={'size':15,'color':'purple'})
        plt.pause(0.1)

plt.show()

注:torch.max()

  • torch.max(input):计算输入的所有数据中的最大值
import torch

data1=torch.tensor([[1,2,3],[4,5,6],[9,8,7]])
data2=torch.tensor([[2,2,3],[4,4,5],[8,9,8]])
print(torch.max(data1))

#运行结果
tensor(9)
  • torch.max(input,dim):按维度返回最大值及索引。dim=0表示按列计算,dim=1表示按行计算。
import torch

data1=torch.tensor([[1,2,3,4],[4,5,6,7],[9,8,7,6]])
data2=torch.tensor([[2,2,3,5],[4,4,5,3],[8,9,8,10]])

print('返回每一列的最大值和索引:\n',torch.max(data1,dim=0))    #返回每一列的最大值及索引
print('返回每一行的最大值和索引:\n',torch.max(data1,dim=1))    #返回每一行的最大值及索引
print('只返回最大值:\n',torch.max(data1,dim=0)[0]) #只返回值
print('只返回索引:\n',torch.max(data1,dim=1)[1]) #只返回索引


#运行结果
返回每一列的最大值和索引:
 torch.return_types.max(
values=tensor([9, 8, 7, 7]),
indices=tensor([2, 2, 2, 1]))
返回每一行的最大值和索引:
 torch.return_types.max(
values=tensor([4, 7, 9]),
indices=tensor([3, 3, 0]))
只返回最大值:
 tensor([9, 8, 7, 7])
只返回索引:
 tensor([3, 3, 0])
  • torch.max(input1,input2):返回对应位置最大的那个数组成新的序列
import torch

data1=torch.tensor([[1,2,3,4],[4,5,6,7],[9,8,7,6]])
data2=torch.tensor([[2,2,3,5],[4,4,5,3],[8,9,8,10]])

print(torch.max(data1,data2))


#运行结果
tensor([[ 2,  2,  3,  5],
        [ 4,  5,  6,  7],
        [ 9,  9,  8, 10]])



 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值