Part_6 Stroke_Prediction_Pytorch

In [1]:
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.utils.data as Data

import matplotlib.pyplot as plt
%matplotlib inline

import numpy as np
import imageio

Krok 1. Tworzenie zbioru danych

In [2]:
import pandas as pd

df = pd.read_csv('c:/1/Stroke_Prediction_NUM.csv')
#  , nrows=1000,parse_dates=['Date'],usecols = ['Unnamed: 0','Date','Consumption']

print(df.shape)
print(df.dtypes)
print(df['Unnamed: 0'].max())
print(df.columns)
df.head(3)
(29062, 20)
Unnamed: 0            int64
ID                    int64
Gender               object
Hypertension          int64
Heart_Disease         int64
Ever_Married         object
Type_Of_Work         object
Residence            object
Avg_Glucose         float64
BMI                 float64
Smoking_Status       object
Stroke                int64
Age_years           float64
Age_years_10         object
Gender_C              int64
Ever_Married_C        int64
Type_Of_Work_C        int64
Residence_C           int64
Smoking_Status_C      int64
Age_years_10_C        int64
dtype: object
29061
Index(['Unnamed: 0', 'ID', 'Gender', 'Hypertension', 'Heart_Disease',
       'Ever_Married', 'Type_Of_Work', 'Residence', 'Avg_Glucose', 'BMI',
       'Smoking_Status', 'Stroke', 'Age_years', 'Age_years_10', 'Gender_C',
       'Ever_Married_C', 'Type_Of_Work_C', 'Residence_C', 'Smoking_Status_C',
       'Age_years_10_C'],
      dtype='object')
Out[2]:
Unnamed: 0 ID Gender Hypertension Heart_Disease Ever_Married Type_Of_Work Residence Avg_Glucose BMI Smoking_Status Stroke Age_years Age_years_10 Gender_C Ever_Married_C Type_Of_Work_C Residence_C Smoking_Status_C Age_years_10_C
0 0 30650 Male 1 0 Yes Private Urban 87.96 39.2 never smoked 0 58.093151 (53.126, 59.076] 1 1 2 1 1 5
1 1 57008 Female 0 0 Yes Private Rural 69.04 35.9 formerly smoked 0 70.076712 (65.121, 74.11] 0 1 2 0 0 7
2 2 53725 Female 0 0 Yes Private Urban 77.59 17.7 formerly smoked 0 52.041096 (48.082, 53.126] 0 1 2 1 0 4
In [3]:
df.describe(include=[np.number]).columns
Out[3]:
Index(['Unnamed: 0', 'ID', 'Hypertension', 'Heart_Disease', 'Avg_Glucose',
       'BMI', 'Stroke', 'Age_years', 'Gender_C', 'Ever_Married_C',
       'Type_Of_Work_C', 'Residence_C', 'Smoking_Status_C', 'Age_years_10_C'],
      dtype='object')
In [4]:
import torch
import torch.nn as nn

# Create dummy input and target tensors (data)
x = torch.tensor((df['Hypertension'],df['Heart_Disease'],df['Avg_Glucose'],df['BMI'],df['Age_years'],df['Gender_C'],df['Ever_Married_C'],df['Type_Of_Work_C'],df['Residence_C'],df['Smoking_Status_C'],df['Age_years_10_C']), dtype=torch.float)
y = torch.tensor(df['Stroke'], dtype=torch.float)
In [5]:
x =torch.transpose(x.flip(0),0,1)
y = y.reshape(-1,1)
y = y.view(y.shape[0],1)
In [6]:
x
Out[6]:
tensor([[ 5.0000,  1.0000,  1.0000,  ..., 87.9600,  0.0000,  1.0000],
        [ 7.0000,  0.0000,  0.0000,  ..., 69.0400,  0.0000,  0.0000],
        [ 4.0000,  0.0000,  1.0000,  ..., 77.5900,  0.0000,  0.0000],
        ...,
        [ 8.0000,  0.0000,  1.0000,  ..., 91.9400,  0.0000,  1.0000],
        [ 2.0000,  1.0000,  1.0000,  ..., 99.1600,  0.0000,  0.0000],
        [ 8.0000,  1.0000,  1.0000,  ..., 79.4800,  0.0000,  0.0000]])
In [7]:
y
Out[7]:
tensor([[0.],
        [0.],
        [0.],
        ...,
        [0.],
        [0.],
        [0.]])
In [8]:
print('x.shape: ',x.shape)
print('y.shape: ',y.shape)
x.shape:  torch.Size([29062, 11])
y.shape:  torch.Size([29062, 1])
In [9]:
# Create a model
model = nn.Sequential(nn.Linear(11, 21),
                     nn.ReLU(),
                     nn.Linear(21, 1),
                     nn.Sigmoid())
In [10]:
# Construct the loss function
criterion = torch.nn.MSELoss()

# Construct the optimizer (Stochastic Gradient Descent in this case)
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
In [11]:
# Gradient Descent
for epoch in range(100):
    # Forward pass: Compute predicted y by passing x to the model
    y_pred = model(x)

    # Compute and print loss
    loss = criterion(y_pred, y)
    print('epoch: ', epoch,' loss: ', loss.item())

    # Zero gradients, perform a backward pass, and update the weights.
    optimizer.zero_grad()
    
    # perform a backward pass (backpropagation)
    loss.backward()
    
    # Update the parameters
    optimizer.step()
epoch:  0  loss:  0.7619365453720093
epoch:  1  loss:  0.594810426235199
epoch:  2  loss:  0.3751734495162964
epoch:  3  loss:  0.23151186108589172
epoch:  4  loss:  0.14533954858779907
epoch:  5  loss:  0.09627034515142441
epoch:  6  loss:  0.06945375353097916
epoch:  7  loss:  0.054303064942359924
epoch:  8  loss:  0.04516179487109184
epoch:  9  loss:  0.039268966764211655
epoch:  10  loss:  0.03524915874004364
epoch:  11  loss:  0.03237738832831383
epoch:  12  loss:  0.030247367918491364
epoch:  13  loss:  0.02861827053129673
epoch:  14  loss:  0.02734033390879631
epoch:  15  loss:  0.026316413655877113
epoch:  16  loss:  0.025481155142188072
epoch:  17  loss:  0.02478926070034504
epoch:  18  loss:  0.024208463728427887
epoch:  19  loss:  0.023715276271104813
epoch:  20  loss:  0.02329222857952118
epoch:  21  loss:  0.022926034405827522
epoch:  22  loss:  0.022606493905186653
epoch:  23  loss:  0.022325653582811356
epoch:  24  loss:  0.022077234461903572
epoch:  25  loss:  0.021856192499399185
epoch:  26  loss:  0.021658455953001976
epoch:  27  loss:  0.021480709314346313
epoch:  28  loss:  0.021320214495062828
epoch:  29  loss:  0.021174699068069458
epoch:  30  loss:  0.02104226127266884
epoch:  31  loss:  0.020921317860484123
epoch:  32  loss:  0.020810484886169434
epoch:  33  loss:  0.020708631724119186
epoch:  34  loss:  0.020614737644791603
epoch:  35  loss:  0.020527983084321022
epoch:  36  loss:  0.02044760249555111
epoch:  37  loss:  0.020372958853840828
epoch:  38  loss:  0.020303495228290558
epoch:  39  loss:  0.020238704979419708
epoch:  40  loss:  0.02017817460000515
epoch:  41  loss:  0.020121509209275246
epoch:  42  loss:  0.020068373531103134
epoch:  43  loss:  0.02001846395432949
epoch:  44  loss:  0.019971506670117378
epoch:  45  loss:  0.019927268847823143
epoch:  46  loss:  0.019885526970028877
epoch:  47  loss:  0.01984609104692936
epoch:  48  loss:  0.019808778539299965
epoch:  49  loss:  0.019773442298173904
epoch:  50  loss:  0.01973993144929409
epoch:  51  loss:  0.019708123058080673
epoch:  52  loss:  0.01967788301408291
epoch:  53  loss:  0.019649116322398186
epoch:  54  loss:  0.019621726125478745
epoch:  55  loss:  0.019595609977841377
epoch:  56  loss:  0.019570695236325264
epoch:  57  loss:  0.019546905532479286
epoch:  58  loss:  0.019524166360497475
epoch:  59  loss:  0.019502412527799606
epoch:  60  loss:  0.019481591880321503
epoch:  61  loss:  0.01946163736283779
epoch:  62  loss:  0.019442515447735786
epoch:  63  loss:  0.019424162805080414
epoch:  64  loss:  0.019406545907258987
epoch:  65  loss:  0.019389623776078224
epoch:  66  loss:  0.019373351708054543
epoch:  67  loss:  0.019357694312930107
epoch:  68  loss:  0.019342632964253426
epoch:  69  loss:  0.019328124821186066
epoch:  70  loss:  0.01931414194405079
epoch:  71  loss:  0.019300663843750954
epoch:  72  loss:  0.01928766444325447
epoch:  73  loss:  0.01927511766552925
epoch:  74  loss:  0.019262999296188354
epoch:  75  loss:  0.01925128698348999
epoch:  76  loss:  0.01923997327685356
epoch:  77  loss:  0.019229035824537277
epoch:  78  loss:  0.0192184466868639
epoch:  79  loss:  0.01920820213854313
epoch:  80  loss:  0.019198283553123474
epoch:  81  loss:  0.01918867602944374
epoch:  82  loss:  0.019179366528987885
epoch:  83  loss:  0.01917034201323986
epoch:  84  loss:  0.019161585718393326
epoch:  85  loss:  0.01915309950709343
epoch:  86  loss:  0.019144853577017784
epoch:  87  loss:  0.019136855378746986
epoch:  88  loss:  0.019129084423184395
epoch:  89  loss:  0.019121533259749413
epoch:  90  loss:  0.01911420375108719
epoch:  91  loss:  0.019107069820165634
epoch:  92  loss:  0.019100135192275047
epoch:  93  loss:  0.019093390554189682
epoch:  94  loss:  0.019086824730038643
epoch:  95  loss:  0.01908043585717678
epoch:  96  loss:  0.01907421462237835
epoch:  97  loss:  0.01906815730035305
epoch:  98  loss:  0.019062256440520287
epoch:  99  loss:  0.01905650645494461
In [12]:
 y_pred
Out[12]:

tensor([[0.0098], [0.0622], [0.0246], …, [0.0206], [0.0021], [0.0558]], grad_fn=<SigmoidBackward>)

Part_7 Stroke_Prediction – Model Sieci neuronowych PyTorch Technika Osadzania