1.散点分类数据
代码
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
n_data= torch.ones(100,2)
x0 = torch.normal(2*n_data,1)
y0 = torch.zeros(100)
x1 = torch.normal(-2*n_data,1)
y1 = torch.ones(100)
x = torch.cat((x0,x1),0).type(torch.FloatTensor)
y = torch.cat((y0,y1),0).type(torch.LongTensor)
x,y = Variable(x),Variable(y)
plt.scatter(x.data.numpy()[:,0],x.data.numpy()[:,1],c= y.data.numpy(),s=100,lw =0,cmap ='RdYlGn')
plt.show()
运行结果
2.搭建神经网络
代码
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
n_data= torch.ones(100,2)
x0 = torch.normal(2*n_data,1)
y0 = torch.zeros(100)
x1 = torch.normal(-2*n_data,1)
y1 = torch.ones(100)
x = torch.cat((x0,x1),0).type(torch.FloatTensor)
y = torch.cat((y0,y1),0).type(torch.LongTensor)
x,y = Variable(x),Variable(y)
# plt.scatter(x.data.numpy()[:,0],x.data.numpy()[:,1],c= y.data.numpy(),s=100,lw =0,cmap ='RdYlGn')
# plt.show()
# Net __init__()
class Net(torch.nn.Module):#继承module
def __init__(self,n_features,n_hidden,n_output):
super(Net,self).__init__()#官方步骤,继承
self.hidden = torch.nn.Linear(n_features,n_hidden)
self.predict = torch.nn.Linear(n_hidden,n_output)#预测
def forward(self,x):
# 前向传递过程,搭建神经网络
x = F.relu(self.hidden(x))
x = self.predict(x)
return x
net = Net(2,10,2) #输入、隐藏层、输出分别为1,10,1
#哪个位置为1就是其对应分类
print(net)
运行结果
Net(
(hidden): Linear(in_features=2, out_features=10, bias=True)
(predict): Linear(in_features=10, out_features=2, bias=True)
)
Process finished with exit code 0
3.可视化显示
代码
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
n_data= torch.ones(100,2)
x0 = torch.normal(2*n_data,1)
y0 = torch.zeros(100)
x1 = torch.normal(-2*n_data,1)
y1 = torch.ones(100)
x = torch.cat((x0,x1),0).type(torch.FloatTensor)
y = torch.cat((y0,y1),0).type(torch.LongTensor)
x,y = Variable(x),Variable(y)
# plt.scatter(x.data.numpy()[:,0],x.data.numpy()[:,1],c= y.data.numpy(),s=100,lw =0,cmap ='RdYlGn')
# plt.show()
# Net __init__()
class Net(torch.nn.Module):#继承module
def __init__(self,n_features,n_hidden,n_output):
super(Net,self).__init__()#官方步骤,继承
self.hidden = torch.nn.Linear(n_features,n_hidden)
self.predict = torch.nn.Linear(n_hidden,n_output)#预测
def forward(self,x):
# 前向传递过程,搭建神经网络
x = F.relu(self.hidden(x))
x = self.predict(x)
return x
net = Net(2,10,2) #输入、隐藏层、输出分别为1,10,1
#哪个位置为1就是其对应分类
print(net)
plt.ion() #实时打印可视化
plt.show()
# 优化神经网络,SGD梯度下降求解局部最优,传入参数net.parameters(),
# 给定学习效率learning rate一般小于1,学习太快会在梯度下降时导致“跨过”了介于两次优化之间可能最佳的去噪
optimizer = torch.optim.SGD(net.parameters(),lr=0.02)
loss_func = torch.nn.CrossEntropyLoss()#回归问题用MSELoss均方误差;分类问题用CrossEntropyLoss算概率
for t in range (100):
out = net(x)#[-2,-.12,20]#F.softmax(out)[0.1,0.2,0.7]
loss = loss_func(out,y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if t % 2 == 0:
#打印学习进程
plt.cla()
prediction = torch.max(F.softmax(out,dim=0),1)[1] #F.softmax(x,dim=1/0)对每一行/列进行softmax
pred_y = prediction.data.numpy().squeeze()
target_y = y.data.numpy()
plt.scatter(x.data.numpy()[:,0],x.data.numpy()[:,1],c= y.data.numpy(),s=100,lw =0,cmap ='RdYlGn')
accuracy = sum(pred_y == target_y) /200
plt.text(1.5,-4,'Accuracy = %.2f' % accuracy,fontdict={'size':20,'color':'red'})
plt.pause(0.1)
plt.savefig('./act_func2.jpg')
plt.ioff()
plt.show()
运行结果
Net(
(hidden): Linear(in_features=2, out_features=10, bias=True)
(predict): Linear(in_features=10, out_features=2, bias=True)
)
Process finished with exit code 0