这里使用pytorch进行一个简单的二分类模型

导入所有我们需要的库

import torch
import matplotlib.pyplot as plt
import torch.nn.functional as F

接着我们这里 生成我们需要的假数据

# set seed
torch.manual_seed(1) # make fake data
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), ).type(torch.LongTensor)

  

我们先定义好我们需要的net的这个类

class Net(torch.nn.Module):

    def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden)
self.out = torch.nn.Linear(n_hidden, n_output) def forward(self, x):
x = F.relu(self.hidden(x))
x = self.out(x)
return x

现在开始搭建我们需要的网络

我们构建一个只有1个隐藏层的网络

用SGD的方法对损失方程进行优化

然后用交叉熵来作为我们loss function

net = Net(n_feature=2, n_hidden=10, n_output=2)
print(net) optimizer = torch.optim.SGD(net.parameters(), lr=0.0015)
loss_func = torch.nn.CrossEntropyLoss()

接着我们开始训练我们的网络

plt.ion()

for t in range(200):
out = net(x)
loss = loss_func(out, y) optimizer.zero_grad() # clear gradients for next train
loss.backward() # backpropagation, compute gradients
optimizer.step() if t % 2 == 0:
plt.cla()
predcition = torch.max(out, 1)[1]
pred_y = predcition.data.numpy()
target_y = y.data.numpy()
plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=pred_y, s=100, lw=0, cmap='RdYlGn')
accuracy = float((pred_y == target_y).astype(int).sum()) / float(target_y.size)
plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color': 'red'})
plt.pause(0.1) plt.ioff()
plt.show()

  

接着我们可以看到  已经把我们做的假数据成功分成了两类

最新文章

  1. create()创建的控件不能映射消息函数的解决
  2. 使用bokeh-scala进行数据可视化
  3. 基于TCP和多线程实现无线鼠标键盘-GestureDetector
  4. 【实践】jquery实现滑动动画及轮播
  5. memory_limit的一个bug | 风雪之隅
  6. onClick,onServerClick,onClientClick
  7. 零基础Visual Fox Pro 6.0自学笔记(VFP6.0图文教程)
  8. 让我们写的程序生成单个的exe文件(C#winform程序举例)
  9. Android应用开发基础篇(16)-----ScaleGestureDetector(缩放手势检测)
  10. python基础教程(五)
  11. 【DevOps敏捷开发动手实验】开源文档 v2015.2 stable 版发布
  12. 在table表格中实现圆角效果
  13. js中call,caller,callee,aplly
  14. usb枚举
  15. spring 事务传播
  16. Pro * c Oracle 12c
  17. Oracle中append与Nologging
  18. go中的接口
  19. 附9 elasticsearch-curator + Linux定时任务
  20. [转]window下使用SetUnhandledExceptionFilter捕获让程序的崩溃

热门文章

  1. Python基础16
  2. git did not exit cleanly (exit code 1) 的解决办法
  3. openssl生成随机数
  4. Android中设置状态栏颜色和字体颜色
  5. ucoreOS_lab3 实验报告
  6. JVM源码分析之MetaspaceSize和MaxMetaspaceSize的区别
  7. Invalid utf8mb4 character string: '"'
  8. python_数据分析_正态分布
  9. 3-2-Pandas 索引
  10. django-图形验证码(django-simple-captcha)