因为我发现直接安装torchkeras安装不上,需要安装torchkeras见博客python安装torchkeras_一条有目标的咸鱼的博客-CSDN博客_torchkeras 安装
对其中用到的几个方法先总结如下:
(1)summary可以用来打印网络的结构
def summary(self,
input_shape: Any,
input_dtype: Type[FloatTensor] = torch.FloatTensor,
batch_size: int = -1) -> None
(2)compile可以将损失函数,优化器,评估指标同模型进行绑定
关于其中的参数解释可以参考keras的compile方法见博客keras: model.compile ()_shuijinghua的博客-CSDN博客_model.compile
def compile(self,
loss_func: Any,
optimizer: Any = None,
metrics_dict: Any = None,
device: Any = None) -> None
(3)fit 进行模型的训练
def fit(self,
epochs: {__add__},
dl_train: {__iter__},
dl_val: Any = None,
log_step_freq: int = 1) -> DataFrame
构建的DNN模型
(1)创建模型
class DNNnet(nn.Module):
def __init__(self):
super(DNNnet, self).__init__()
self.Lin1=nn.Linear(2,4)
self.Lin2=nn.Linear(4,8)
self.Lin3=nn.Linear(8,1)
def forward(self,x):
x=F.relu(self.Lin1(x))
x=F.relu(self.Lin2(x))
y=nn.Sigmoid()(self.Lin3(x))
return y
(2)准确率的计算
def accuracy(y_pred,y_true):
y_pred=torch.where(y_pred>0.5,torch.ones_like(y_pred,dtype=torch.float32),
torch.zeros_like(y_pred,dtype=torch.float32))
acc=torch.mean(1-torch.abs(y_true-y_pred))
return acc
(3)数据准备
sample_positive,sample_negagive=1000,1000
#小圈
r_s=3.0+torch.normal(0.0,1.0,size=[sample_positive,1])
theta_s=2*np.pi*torch.rand([sample_negagive,1])
X_s=torch.cat([r_s*torch.cos(theta_s),r_s*torch.sin(theta_s)],axis=1)
Y_s=torch.ones_like(r_s)
#大圈
r_b = 5.0 + torch.normal(0.0, 1.0, size=[sample_positive, 1])
theta_b = 2 * np.pi * torch.rand([sample_negagive, 1])
X_b = torch.cat([r_b * torch.cos(theta_b), r_b * torch.sin(theta_b)], axis=1)
Y_b = torch.zeros_like(r_b)
#组合
X=torch.cat([X_s,X_b],axis=0)
Y=torch.cat([Y_s,Y_b],axis=0)
data=TensorDataset(X,Y)
data_train,data_valid=torch.utils.data.random_split(data,[int(len(data)*0.7),int(len(data)*0.3)])
dt_train=DataLoader(data_train,batch_size=100,shuffle=True,num_workers=2)
dt_valid=DataLoader(data_valid,batch_size=100,num_workers=2)
(4)开始训练
model=torchkeras.Model(DNNnet())
model.summary(input_shape=(2,))
model.compile(loss_func=nn.BCELoss(),optimizer=torch.optim.Adam(model.parameters(),lr=0.01),
metrics_dict={'accuracy':accuracy})
dfhistory=model.fit(100,dl_train=dt_train,dl_val=dt_valid,log_step_freq=10)