Breast Cancer on PyTorch

Code

# encoding:utf8

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import torch
import torch.nn as nn
import torch.optim as optim
from matplotlib import pyplot as plt
import numpy as np class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.l1 = nn.Linear(30, 60)
self.a1 = nn.Sigmoid()
self.l2 = nn.Linear(60, 2)
self.a2 = nn.ReLU()
self.l3 = nn.Softmax(dim=1) def forward(self, x):
x = self.l1(x)
x = self.a1(x)
x = self.l2(x)
x = self.a2(x)
x = self.l3(x)
return x if __name__ == '__main__':
breast_cancer = load_breast_cancer() x_train, x_test, y_train, y_test = train_test_split(breast_cancer.data, breast_cancer.target, test_size=0.25)
x_train, x_test = torch.tensor(x_train, dtype=torch.float), torch.tensor(x_test, dtype=torch.float)
y_train, y_test = torch.tensor(y_train, dtype=torch.long), torch.tensor(y_test, dtype=torch.long) net = Net() criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.005) # PyTorch suit to tiny learning rate error = list() for epoch in range(250):
optimizer.zero_grad()
y_pred = net(x_train)
loss = criterion(y_pred, y_train)
loss.backward()
optimizer.step()
error.append(loss.item()) y_pred = net(x_test)
y_pred = torch.argmax(y_pred, dim=1) # it is necessary that drawing the loss plot when we fine tuning the model
plt.plot(np.arange(1, len(error)+1), error)
plt.show() print(classification_report(y_test, y_pred, target_names=breast_cancer.target_names))

损失函数图像:

nn.Sequential

# encoding:utf8

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import torch
import torch.nn as nn
import torch.optim as optim
from matplotlib import pyplot as plt
import numpy as np if __name__ == '__main__':
breast_cancer = load_breast_cancer() x_train, x_test, y_train, y_test = train_test_split(breast_cancer.data, breast_cancer.target, test_size=0.25)
x_train, x_test = torch.tensor(x_train, dtype=torch.float), torch.tensor(x_test, dtype=torch.float)
y_train, y_test = torch.tensor(y_train, dtype=torch.long), torch.tensor(y_test, dtype=torch.long) net = nn.Sequential(
nn.Linear(30, 60),
nn.Sigmoid(),
nn.Linear(60, 2),
nn.ReLU(),
nn.Softmax(dim=1)
) criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.005) # PyTorch suit to tiny learning rate error = list() for epoch in range(250):
optimizer.zero_grad()
y_pred = net(x_train)
loss = criterion(y_pred, y_train)
loss.backward()
optimizer.step()
error.append(loss.item()) y_pred = net(x_test)
y_pred = torch.argmax(y_pred, dim=1) # it is necessary that drawing the loss plot when we fine tuning the model
plt.plot(np.arange(1, len(error)+1), error)
plt.show() print(classification_report(y_test, y_pred, target_names=breast_cancer.target_names))

模型性能:

              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        14
versicolor 1.00 1.00 1.00 16
virginica 1.00 1.00 1.00 20 accuracy 1.00 50
macro avg 1.00 1.00 1.00 50
weighted avg 1.00 1.00 1.00 50

Iris Classification on PyTorch的更多相关文章

  1. Iris Classification on Tensorflow

    Iris Classification on Tensorflow Neural Network formula derivation \[ \begin{align} a & = x \cd ...

  2. Iris Classification on Keras

    Iris Classification on Keras Installation Python3 版本为 3.6.4 : : Anaconda conda install tensorflow==1 ...

  3. (转)Awesome PyTorch List

    Awesome-Pytorch-list 2018-08-10 09:25:16 This blog is copied from: https://github.com/Epsilon-Lee/Aw ...

  4. Pytorch collate_fn用法

    By default, Dataloader use collate_fn method to pack a series of images and target as tensors (first ...

  5. pytorch和tensorflow的爱恨情仇之定义可训练的参数

    pytorch和tensorflow的爱恨情仇之基本数据类型 pytorch和tensorflow的爱恨情仇之张量 pytorch版本:1.6.0 tensorflow版本:1.15.0 之前我们就已 ...

  6. pytorch下对简单的数据进行分类(classification)

    看了Movan大佬的文字教程让我对pytorch的基本使用有了一定的了解,下面简单介绍一下二分类用pytorch的基本实现! 希望详细的注释能够对像我一样刚入门的新手来说有点帮助! import to ...

  7. pytorch -- CNN 文本分类 -- 《 Convolutional Neural Networks for Sentence Classification》

    论文  < Convolutional Neural Networks for Sentence Classification>通过CNN实现了文本分类. 论文地址: 666666 模型图 ...

  8. pytorch之 classification

    import torch import torch.nn.functional as F import matplotlib.pyplot as plt # torch.manual_seed(1) ...

  9. pytorch 5 classification 分类

    import torch from torch.autograd import Variable import torch.nn.functional as F import matplotlib.p ...

随机推荐

  1. js模拟队列----小优先队列

    队列:先进先出,后进后出 var Queue = (function(){ var item = new WeakMap(); class Queue{ constructor(){ item.set ...

  2. C++ 类定义

    C++ 类定义 定义一个类,本质上是定义一个数据类型的蓝图.这实际上并没有定义任何数据,但它定义了类的名称意味着什么,也就是说,它定义了类的对象包括了什么,以及可以在这个对象上执行哪些操作. 类定义是 ...

  3. unity3d-角色控制器续

    自学是一个坚持和寂寞的过程,写博客更是一个总结与成长的过程,加油! 角色控制器续 之前学习了角色漫游,但里面有很多效果都不是我想要的.只有自己的动手实践了才能理会其中的奥妙.所以我又琢磨了许久. 为了 ...

  4. 002-一般处理程序(HttpHandler)

    一般处理程序(HttpHandler):是一个实现System.Web.IHttpHandler接口的特殊类.任何一个实现了IHttpHandler接口的类,是作为一个外部请求的目标程序的前提.(凡是 ...

  5. SpringBoot返回json格式到浏览器上,出现乱码问题

    在对应的Controller上的requestMapping中添加: @RestController@EnableAutoConfiguration@RequestMapping(value = &q ...

  6. Unity之Vector3.SignedAngle实现

    如代码: float angle = Vector3.Angle(v1, v2); angle *= Mathf.Sign(Vector3.Cross(v1, v2).y);

  7. notepad去掉空行

    选择替换,把查找模式设置为正则表达式,在查找框中自己输入 ^\s+  ,替换框留空,点“全部替换”,即可(先全选).注意:不要复制我的,自己输入,且用英文格式输入.

  8. Mvcpager以下各节已定义,但尚未为布局页“~/Views/Shared/_Layout.cshtml”呈现:“Scripts”。

    解决办法如下: 1.在_Layout.cshtml布局body内,添加section,Scripts.Render和RenderSection标签示例代码如下: <body class=&quo ...

  9. Applegate 方法使用

    1. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotif ...

  10. Web处理方式

    ProcessRequest 方法简称 PR方法 PR方法内部调用Page_Load方法   MVC设计模式 Model是指要处理的业务代码和数据操作代码 View视图主要是指的跟用户打交道并能够展示 ...