
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df= pd.read_csv('c:/1/Stroke_Prediction_NUM.csv')
df.head(2)
Analiza poziomu zbilansowania zmiennej wynikowej¶
del df['Unnamed: 0']
df.Stroke.value_counts(dropna = False, normalize=True)
Zbiór zmiennych wynikowych wymaga zbilansowania. Do bilansowania zmiennych wynikowych stosuję trzy metody:
- class_weight (http://sigmaquality.pl/models/classification/logistic-regression/model-regresji-logistyczne-czesc-4-zastosowanie-class_weight/)
- oversampling (http://sigmaquality.pl/models/classification/logistic-regression/model-regresji-logistycznej-czesc-2-oversampling/)
- zmiana progu (http://sigmaquality.pl/models/classification/logistic-regression/model-regresji-logistycznej-czesc-3-zmiana-progu-w-modelu-regresji-logistycznej/)
Wszystkie trzy metody powinny dać podobne efekty przy klasyfikacji. Dzisiaj do zbilansowania zbioru zastosuje metodę oversampling. Oversampling odbywa się na zbiorze treningowym, więc najpierw trzeba podzielić zbiór na treningowy i testowy.
Podział na zbiór testowy i wynikowy¶
df2 = df[['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']]
y = df2['Stroke']
X = df2.drop('Stroke', axis=1)
from sklearn.model_selection import train_test_split
Xtrain, Xtest, ytrain, ytest = train_test_split(X,y, test_size=0.33, stratify = y, random_state = 148)
print ('Zbiór X treningowy: ',Xtrain.shape)
print ('Zbiór X testowy: ', Xtest.shape)
print ('Zbiór y treningowy: ', ytrain.shape)
print ('Zbiór y testowy: ', ytest.shape)
print("ytrain = 0: ", sum(ytrain == 0))
print("ytrain = 1: ", sum(ytrain == 1))
Proporcja = sum(ytrain == 0) / sum(ytrain == 1)
Proporcja = np.round(Proporcja, decimals=0)
Proporcja = Proporcja.astype(int)
print('Ilość 0 Stroke na 1 Stroke: ', Proporcja)
ytrain_OVSA = pd.concat([ytrain[ytrain==1]] * Proporcja, axis = 0)
ytrain_OVSA.count()
Powiękrzyliśmy ilość zmiennych wynikowych 1. Teraz mamy tę samą liczbę wierszy zmiennych wynikowych i zmiennych niezależnych. Teraz wprowadzamy nowe, dodatkowe zmienne 1 do zbioru treningowego.
Xtrain_OVSA = pd.concat([Xtrain.loc[ytrain==1, :]] * Proporcja, axis = 0)
ytrain_OVSA.count()
ytrain_OVSA = pd.concat([ytrain, ytrain_OVSA], axis = 0).reset_index(drop = True)
Xtrain_OVSA = pd.concat([Xtrain, Xtrain_OVSA], axis = 0).reset_index(drop = True)
print("ilość elementów w zbiorze Xtrain: ", Xtrain.BMI.count())
print("ilość elementów w zbiorze Xtrain_OVSA: ", Xtrain_OVSA.BMI.count())
print("ilość elementów w zbiorze ytrain: ", ytrain.count())
print("ilość elementów w zbiorze ytrain_OVSA: ", ytrain_OVSA.count())
Poziom zbilansowania zbioru wynikowego:
ytrain_OVSA.value_counts(dropna = False, normalize=True).plot(kind='pie')
Oversampling dla zbioru testowego¶
print("ytest = 0: ", sum(ytest == 0))
print("ytest = 1: ", sum(ytest == 1))
ProporcjaT = sum(ytrain == 0) / sum(ytrain == 1)
ProporcjaT = np.round(ProporcjaT, decimals=0)
ProporcjaT = Proporcja.astype(int)
print('Ilość 0 Stroke na 1 Stroke: ', ProporcjaT)
ytest_OVSA = pd.concat([ytest[ytest==1]] * ProporcjaT, axis = 0)
ytest_OVSA.count()
Xtest_OVSA = pd.concat([Xtest.loc[ytest==1, :]] * ProporcjaT, axis = 0)
ytest_OVSA.count()
ytest_OVSA = pd.concat([ytest, ytest_OVSA], axis = 0).reset_index(drop = True)
Xtest_OVSA = pd.concat([Xtest, Xtest_OVSA], axis = 0).reset_index(drop = True)
print("ilość elementów w zbiorze Xtrain: ", Xtest.BMI.count())
print("ilość elementów w zbiorze Xtrain_OVSA: ", Xtest_OVSA.BMI.count())
print("ilość elementów w zbiorze ytrain: ", ytest.count())
print("ilość elementów w zbiorze ytrain_OVSA: ", ytest_OVSA.count())
Tensorflow neural network¶
import tensorflow as tf
import matplotlib.pyplot as plt
print("Using tensorflow Version
df2.shape
feat_column = tf.contrib.layers.real_valued_column('features', dimension=12)
Definiowanie estymatora¶
estimator = tf.estimator.LinearClassifier(feature_columns=[feat_column],
n_classes=2,
model_dir = "kernel_e"
)
Zmiana wszystkich zmiennych numerycznych na zmienne TensorFlow
df2.columns
FEATURES = ['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']
continuous_features = [tf.feature_column.numeric_column(k) for k in FEATURES]
continuous_features
Definiuje klasyfikator liniowy¶
model = tf.estimator.LinearClassifier(
n_classes = 2,
model_dir="ongoing/ATOS7",
feature_columns=continuous_features)
Tworzę funkcję wprowadzania¶
FEATURES = ['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']
LABEL = 'Stroke'
def get_input_fn(data_set, num_epochs=None, n_batch = 128, shuffle=True):
return tf.estimator.inputs.pandas_input_fn(
x=pd.DataFrame({k: data_set[k].values for k in FEATURES}),
y = pd.Series(data_set[LABEL].values),
batch_size=n_batch,
num_epochs=num_epochs,
shuffle=shuffle)
Trenowanie modelu¶
df_train = pd.concat([Xtrain_OVSA, ytrain_OVSA], axis=1, sort=False)
df_test = pd.concat([Xtest_OVSA, ytest_OVSA], axis=1, sort=False)
model.train(input_fn=get_input_fn(df_train,
num_epochs=None,
n_batch = 128,
shuffle=False),
steps=10000)
Ocena modelu¶
model.evaluate(input_fn=get_input_fn(df_test,
num_epochs=1,
n_batch = 128,
shuffle=False),
steps=1000)
y = model.predict(
input_fn=get_input_fn(df_test,
num_epochs=1,
n_batch = 256,
shuffle=False))
y
Pobranie modelu z grafu i klasyfikacja na danych testowych¶
import time
start_time = time.time() ## pomiar czasu: start pomiaru czasu
print(time.ctime())
with tf.Session() as sess:
saver = tf.train.import_meta_graph('ongoing/ATOS7')
print("Model found.")
saver.restore(sess, tf.train.latest_checkpoint('./'))
print("Model restored compl.")
#z = tf.placeholder(tf.float32, shape= (None,38555))
y_pred= y_pred.as_matrix()
output =sess.run(y,feed_dict={Xtest_OVSA: y_pred})
#output =sess.run(z,feed_dict={Xtest_OVSA: y_pred})
#print(output)
print(’Pomiar czasu wykonania tego zadania’) print(time.time() – start_time) ## koniec pomiaru czasu