ium_434732/IUM_05.py

62 lines
1.8 KiB
Python
Raw Normal View History

2021-04-24 12:21:33 +02:00
import torch
2021-05-15 15:54:08 +02:00
import sys
2021-05-15 15:24:37 +02:00
from torch import nn
import numpy as np
2021-04-24 12:21:33 +02:00
import pandas as pd
2021-05-15 15:24:37 +02:00
np.set_printoptions(suppress=False)
class LogisticRegressionModel(nn.Module):
def __init__(self, input_dim, output_dim):
super(LogisticRegressionModel, self).__init__()
self.linear = nn.Linear(input_dim, output_dim)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
out = self.linear(x)
return self.sigmoid(out)
2021-05-15 15:54:08 +02:00
train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
valid = pd.read_csv("valid.csv")
2021-05-15 15:24:37 +02:00
2021-05-15 15:54:08 +02:00
xtrain = train[['age','anaemia','creatinine_phosphokinase','diabetes', 'ejection_fraction', 'high_blood_pressure', 'platelets', 'serum_creatinine', 'serum_sodium', 'sex', 'smoking']].astype(np.float32)
ytrain = train['DEATH_EVENT'].astype(np.float32)
2021-05-15 15:24:37 +02:00
2021-05-15 15:54:08 +02:00
xtest = test[['age','anaemia','creatinine_phosphokinase','diabetes', 'ejection_fraction', 'high_blood_pressure', 'platelets', 'serum_creatinine', 'serum_sodium', 'sex', 'smoking']].astype(np.float32)
ytest = test['DEATH_EVENT'].astype(np.float32)
2021-05-15 15:24:37 +02:00
2021-05-15 15:54:08 +02:00
xTrain = torch.from_numpy(xtrain.values)
yTrain = torch.from_numpy(ytrain.values.reshape(179,1))
2021-05-15 15:24:37 +02:00
2021-05-15 15:54:08 +02:00
xTest = torch.from_numpy(xtest.values)
yTest = torch.from_numpy(ytest.values)
2021-05-15 15:24:37 +02:00
2021-05-15 15:34:10 +02:00
batch_size = 10
num_epochs = 5
learning_rate = 0.002
2021-05-15 15:24:37 +02:00
input_dim = 11
output_dim = 1
model = LogisticRegressionModel(input_dim, output_dim)
2021-05-15 15:54:08 +02:00
criterion = torch.nn.BCELoss(reduction='mean')
2021-05-15 15:24:37 +02:00
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)
for epoch in range(num_epochs):
# print ("Epoch #",epoch)
model.train()
optimizer.zero_grad()
# Forward pass
2021-05-15 15:54:08 +02:00
y_pred = model(xTrain)
2021-05-15 15:24:37 +02:00
# Compute Loss
2021-05-15 15:54:08 +02:00
loss = criterion(y_pred, yTrain)
2021-05-15 15:24:37 +02:00
# print(loss.item())
# Backward pass
loss.backward()
optimizer.step()
2021-05-15 15:54:08 +02:00
y_pred = model(xTest)
2021-05-15 15:24:37 +02:00
print(y_pred.data)
torch.save(model.state_dict(), 'DEATH_EVENT.pth')