import torch
import pandas as pd
import numpy as np
df = pd.DataFrame({
'id':[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
'age':[33,23,45,76,43,23,34,39,19,36,55,83,26,26,43,25,19,23,32,42],
'class':[1,2,3,4,3,4,3,2,1,1,1,3,2,3,4,4,4,2,1,3],
'score1':[98,96,56,88,75,34,56,37,28,54,68,35,77,55,35,12,45,87,43,89],
'score2':[47,32,56,87,34,65,32,56,34,83,26,33,97,95,79,77,98,44,38,65],
'label':[0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,1,0,0],
})
var_list = ['age','class','score1','score2']
Y = 'label'
class model(torch.nn.Module):
def __init__(self):
super(model,self).__init__()
self.line1 = torch.nn.Linear(4,2)
self.relu = torch.nn.ReLU()
self.line2 = torch.nn.Linear(2,1)
def forward(self,input):
x3 = self.line1(input)
x4 = self.relu(x3)
x5 = self.line2(x4)
return x5
mymodel = model()
optimizer = torch.optim.Adam(mymodel.parameters(),lr=0.001)
lossf = torch.nn.BCEWithLogitsLoss()
train_da = torch.tensor(df[var_list].values,dtype=torch.float32)
train_lab = torch.tensor(df[Y].values,dtype=torch.float32)
train_dataset = torch.utils.data.TensorDataset(train_da,train_lab)
traind = torch.utils.data.DataLoader(train_dataset,batch_size=5,shuffle=False)
for jj in range(5):
i = 0
for x,y0 in traind:
i = i+1
y = mymodel(x)
loss = lossf(y,y0.float().unsqueeze(1))
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(jj,i,loss.item())
if torch.isnan(loss).item():
break
yy = mymodel(train_da)