Iris Classification on PyTorch
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的更多相关文章
- Iris Classification on Tensorflow
Iris Classification on Tensorflow Neural Network formula derivation \[ \begin{align} a & = x \cd ...
- Iris Classification on Keras
Iris Classification on Keras Installation Python3 版本为 3.6.4 : : Anaconda conda install tensorflow==1 ...
- (转)Awesome PyTorch List
Awesome-Pytorch-list 2018-08-10 09:25:16 This blog is copied from: https://github.com/Epsilon-Lee/Aw ...
- Pytorch collate_fn用法
By default, Dataloader use collate_fn method to pack a series of images and target as tensors (first ...
- pytorch和tensorflow的爱恨情仇之定义可训练的参数
pytorch和tensorflow的爱恨情仇之基本数据类型 pytorch和tensorflow的爱恨情仇之张量 pytorch版本:1.6.0 tensorflow版本:1.15.0 之前我们就已 ...
- pytorch下对简单的数据进行分类(classification)
看了Movan大佬的文字教程让我对pytorch的基本使用有了一定的了解,下面简单介绍一下二分类用pytorch的基本实现! 希望详细的注释能够对像我一样刚入门的新手来说有点帮助! import to ...
- pytorch -- CNN 文本分类 -- 《 Convolutional Neural Networks for Sentence Classification》
论文 < Convolutional Neural Networks for Sentence Classification>通过CNN实现了文本分类. 论文地址: 666666 模型图 ...
- pytorch之 classification
import torch import torch.nn.functional as F import matplotlib.pyplot as plt # torch.manual_seed(1) ...
- pytorch 5 classification 分类
import torch from torch.autograd import Variable import torch.nn.functional as F import matplotlib.p ...
随机推荐
- IntelliJ IDEA 17 本地LicenseServer激活
注意:此方法适用于Idea v2017.2.x 版本及以前版本. IntelliJ IDEA及破解包下载地址:百度网盘 密码:hlko 一.将IntelliJIDEALicenseServer.e ...
- python regularexpress1
//test.py 1 import re 2 3 print (re.search('www', 'www.myweb.com').span()) 4 print (re.search('com', ...
- python regularexpress
这个正则表达式,我还真没有接触过,在python首次学习 //test.py 1 import re 2 3 print (re.match('www', 'www.myweb.com').span( ...
- webpack打包报错
Invalid configuration object. Webpack has been initialised using a configuration object that does no ...
- [15]Windows内核情景分析 --- 权限管理
Windows系统是支持多用户的.每个文件可以设置一个访问控制表(即ACL),在ACL中规定每个用户.每个组对该文件的访问权限.不过,只有Ntfs文件系统中的文件才支持ACL. (Ntfs文件系统中, ...
- windows8安装msi或exe软件提示2503错误的解决办法
windows8以后的版本安装msi软件(比如nodejs.msi.Git.msi.python.msi.T ortoiseSVN.msi)的时候老师出现2503.2502的错误,究其原因还是系统权限 ...
- php aes128加密
//[加密数据]AES 128 ECB模式 public function aesEncrypt($str){ $screct_key = Yii::$app->params['encryptK ...
- html5-新元素新布局模板-完善中
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8&qu ...
- C# WPF Halcon HDevEngine混合编程
1. WPF+Halcon 引用halcondotnet.dll和hdevenginedotnet.dll XAML中导入命名空间xmlns:halcon=”clr-namespace:HalconD ...
- Java函数接口实现函数组合及装饰器模式
摘要: 通过求解 (sinx)^2 + (cosx)^2 = 1 的若干写法,逐步展示了如何从过程式的写法转变到函数式的写法,并说明了编写"[接受函数参数]并返回[能够接受函数参数的函数]的 ...