赞
踩
torchkeras 是在pytorch上实现的仿keras的高层次Model接口。有了它,你可以像Keras那样,对pytorch构建的模型进行summary,compile,fit,evaluate , predict五连击。一切都像行云流水般自然。
听起来,torchkeras的功能非常强大。但实际上,它的实现非常简单,全部源代码不足300行。如果你想理解它实现原理的一些细节,或者修改它的功能,不要犹豫阅读和修改项目源码。
安装它仅需要运行:
pip install torchkeras
下面是一个使用torchkeras来训练模型的完整范例。我们设计了一个3层的神经网络来解决一个正负样本按照同心圆分布的分类问题。
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import Dataset,DataLoader,TensorDataset
from torchkeras import Model,summary #Attention this line!
构造按照同心圆分布的正负样本数据。
%matplotlib inline %config InlineBackend.figure_format = 'svg' #number of samples n_positive,n_negative = 2000,2000 #positive samples r_p = 5.0 + torch.normal(0.0,1.0,size = [n_positive,1]) theta_p = 2*np.pi*torch.rand([n_positive,1]) Xp = torch.cat([r_p*torch.cos(theta_p),r_p*torch.sin(theta_p)],axis = 1) Yp = torch.ones_like(r_p) #negative samples r_n = 8.0 + torch.normal(0.0,1.0,size = [n_negative,1]) theta_n = 2*np.pi*torch.rand([n_negative,1]) Xn = torch.cat([r_n*torch.cos(theta_n),r_n*torch.sin(theta_n)],axis = 1) Yn = torch.zeros_like(r_n) #concat positive and negative samples X = torch.cat([Xp,Xn],axis = 0) Y = torch.cat([Yp,Yn],axis = 0) #visual samples plt.figure(figsize = (6,6)) plt.scatter(Xp[:,0],Xp[:,1],c = "r") plt.scatter(Xn[:,0],Xn[:,1],c = "g") plt.legend(["positive","negative"]);
# split samples into train and valid data.
ds = TensorDataset(X,Y)
ds_train,ds_valid = torch.utils.data.random_split(ds,[int(len(ds)*0.7),len(ds)-int(len(ds)*0.7)])
dl_train = DataLoader(ds_train,batch_size = 100,shuffle=True,num_workers=2)
dl_valid = DataLoader(ds_valid,batch_size = 100,num_workers=2)
我们通过对torchkeras.Model进行子类化来构建模型,而不是对torch.nn.Module的子类化来构建模型。实际上 torchkeras.Model是torch.nn.Moduled的子类。
class DNNModel(Model): ### Attention here
def __init__(self):
super(DNNModel, self).__init__()
self.fc1 = nn.Linear(2,4)
self.fc2 = nn.Linear(4,8)
self.fc3 = nn.Linear(8,1)
def forward(self,x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
y = nn.Sigmoid()(self.fc3(x))
return y
model = DNNModel()
model.summary(input_shape =(2,))
我们需要先用compile将损失函数,优化器以及评估指标和模型绑定。然后就可以用fit方法进行模型训练了。
class CnnModel(nn.Module): def __init__(self): super().__init__() self.layers = nn.ModuleList([ nn.Conv2d(in_channels=1,out_channels=32,kernel_size = 3), nn.MaxPool2d(kernel_size = 2,stride = 2), nn.Conv2d(in_channels=32,out_channels=64,kernel_size = 5), nn.MaxPool2d(kernel_size = 2,stride = 2), nn.Dropout2d(p = 0.1), nn.AdaptiveMaxPool2d((1,1)), nn.Flatten(), nn.Linear(64,32), nn.ReLU(), nn.Linear(32,10)] ) def forward(self,x): for layer in self.layers: x = layer(x) return x model = torchkeras.Model(CnnModel()) print(model)
model.summary(input_shape=(1,32,32))
from sklearn.metrics import accuracy_score
def accuracy(y_pred,y_true):
y_pred_cls = torch.argmax(nn.Softmax(dim=1)(y_pred),dim=1).data
return accuracy_score(y_true.numpy(),y_pred_cls.numpy())
model.compile(loss_func = nn.CrossEntropyLoss(),
optimizer= torch.optim.Adam(model.parameters(),lr = 0.02),
metrics_dict={"accuracy":accuracy})
dfhistory = model.fit(3,dl_train = dl_train, dl_val=dl_valid, log_step_freq=100)
torchKeras的优点之一是以类风格的形式完成整个模型的训练和测试过程,代码简洁明了,不过在后期的学习过程中,torchKearas可能会存在一定的限制,限制你的某些实现方案。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。