Advent of 2022, Day 18 – Statistical analysis, plotting graphs and feature engineering

In the series of Azure Machine Learning posts:

Azure Machine Learning is also a great tool to do ordinary statistical analysis, graph plotting and everything that goes along.

Let’s get an open dataset, that is available on UCI Machine Learning repository and import it in the pandas dataframe.

We can also first save it to the notebook:

import pandas as pd
df = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/german/german.data', delimiter=' ',header=None)
df.columns=['account_bal','duration','payment_status','purpose',
                   'credit_amount','savings_bond_value','employed_since',
                   'installment_rate','sex_marital','guarantor','residence_since',
                   'most_valuable_asset','age','concurrent_credits','type_of_housing',
                   'number_of_exist_cr','job','number_of_dependents','telephone',
                   'foreign','target']

df= df.replace(['A11','A12','A13','A14', 'A171','A172','A173','A174','A121','A122','A123','A124'],
                  ['neg_bal','positive_bal','positive_bal','no_acc','unskilled','unskilled','skilled','highly_skilled',
                   'none','car','life_insurance','real_estate'])

We will be using the target variable further in analysis to check, how we can do the predictions. So let’s first check the missing values:

# check for missing values
df.isna().any().any()

And now the distribution of target variable:

from sklearn.preprocessing import LabelEncoder

le= LabelEncoder()
le.fit(df.target)
df.target=le.transform(df.target)

And check the loans:

loans_good_bad=round(((df.target.value_counts()/df.target.count())*100))

And we want to check the credits values, duration and age, and if there are big differences, we want to use the log() function on selected variables.

df[['credit_amount','duration','age']].describe()

So let’s do it on credit_amount.

df['credit_amount']=np.log(df['credit_amount'])

We can also draw the distributions for continuous variables:

fig, axes = plt.subplots(1,3, figsize=(16,8))
plt.suptitle('Histogram of continuous variables')
axes[0].hist(df['duration'])
axes[0].set_xlabel('No. of observations')
axes[0].set_ylabel('Years')
axes[0].set_title('Histogram of loan duration');

axes[1].hist(df['credit_amount'])
axes[1].set_xlabel('No. of observations')
axes[1].set_ylabel('Credit amount (dollars)')
axes[1].set_title('Histogram of Credit amount');

axes[2].hist(df['age'])
axes[2].set_xlabel('No. of observations')
axes[2].set_ylabel('Age')
axes[2].set_title('Histogram of Age');
Fig 1: Distribution of continous variables

We can also analyse the relationship between credit amount and duration on a scatterplot.

sns.scatterplot(y=df.credit_amount, x=df.duration, hue=df.target, s=100, );
Fig 2: Scattering the relationship between credit amount class and duration

We can also check the risk for the credit (target variable) with job type (focusing on unemployed).

df.groupby('job')['target'].value_counts().unstack(level=1).plot.barh(stacked=True, figsize=(10, 6))

Or even create a line graph, showing credit amount and duration (same as Fig 2, just with a different graph type).

sns.lineplot(data=df, x='duration', y='credit_amount', hue='target', palette='deep');
Fig 3: Line plotting the relationship between credit amount and duration of repayment

Now, let’s do one-hot encoding for 15 features available in the dataset, so we can do further analysis. We will be using sklearn LabelEncoder function.

from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()
le_count = 0

for col in df:
    if df[col].dtype == 'object':
        if len(list(df[col].unique())) <= 2:
            le.fit(df[col])
            df[col] = le.transform(df[col])
            le_count += 1

df = pd.get_dummies(df)

And now plot a heatmap

corr_data = df[['target', 'account_bal_neg_bal','duration','account_bal_no_acc']]
corr_data_corrs = corr_data.corr()

sns.heatmap(corr_data_corrs,  vmin = -0.25, annot = True, vmax = 0.6)
plt.title('Correlation Heatmap');
Fig 4: heatmap with correlation coefficients

Tomorrow, we will continue with feature engineering and compare a couple of ML models. And we will see, that simple and advanced analysis can also be done in Azure ML.

Happy Advent of 2022! 

Compete set of code, documents, notebooks, and all of the materials will be available at the Github repository: https://github.com/tomaztk/Azure-Machine-Learning

Tagged with: , , , , , ,
Posted in Azure Machine Learning, Uncategorized
7 comments on “Advent of 2022, Day 18 – Statistical analysis, plotting graphs and feature engineering
  1. […] Dec 18: Statistical analysis, plotting graphs and feature engineering […]

    Like

  2. […] Tomaz Kastrun continues an advent of Azure ML. Day 18 takes us through feature exploration: […]

    Like

  3. […] Dec 18: Statistical analysis, plotting graphs and feature engineering […]

    Like

  4. […] Dec 18: Statistical analysis, plotting graphs and feature engineering […]

    Like

  5. […] Dec 18: Statistical analysis, plotting graphs and feature engineering […]

    Like

  6. […] Dec 18: Statistical analysis, plotting graphs and feature engineering […]

    Like

Leave a comment

Follow TomazTsql on WordPress.com
Programs I Use: SQL Search
Programs I Use: R Studio
Programs I Use: Plan Explorer
Rdeči Noski – Charity

Rdeči noski

100% of donations made here go to charity, no deductions, no fees. For CLOWNDOCTORS - encouraging more joy and happiness to children staying in hospitals (http://www.rednoses.eu/red-noses-organisations/slovenia/)

€2.00

Top SQL Server Bloggers 2018
TomazTsql

Tomaz doing BI and DEV with SQL Server and R, Python, Power BI, Azure and beyond

Discover WordPress

A daily selection of the best content published on WordPress, collected for you by humans who love to read.

Revolutions

Tomaz doing BI and DEV with SQL Server and R, Python, Power BI, Azure and beyond

tenbulls.co.uk

tenbulls.co.uk - attaining enlightenment with the Microsoft Data and Cloud Platforms with a sprinkling of Open Source and supporting technologies!

SQL DBA with A Beard

He's a SQL DBA and he has a beard

Reeves Smith's SQL & BI Blog

A blog about SQL Server and the Microsoft Business Intelligence stack with some random Non-Microsoft tools thrown in for good measure.

SQL Server

for Application Developers

Business Analytics 3.0

Data Driven Business Models

SQL Database Engine Blog

Tomaz doing BI and DEV with SQL Server and R, Python, Power BI, Azure and beyond

Search Msdn

Tomaz doing BI and DEV with SQL Server and R, Python, Power BI, Azure and beyond

R-bloggers

Tomaz doing BI and DEV with SQL Server and R, Python, Power BI, Azure and beyond

R-bloggers

R news and tutorials contributed by hundreds of R bloggers

Data Until I Die!

Data for Life :)

Paul Turley's SQL Server BI Blog

sharing my experiences with the Microsoft data platform, SQL Server BI, Data Modeling, SSAS Design, Power Pivot, Power BI, SSRS Advanced Design, Power BI, Dashboards & Visualization since 2009

Grant Fritchey

Intimidating Databases and Code

Madhivanan's SQL blog

A modern business theme

Alessandro Alpi's Blog

DevOps could be the disease you die with, but don’t die of.

Paul te Braak

Business Intelligence Blog

Sql Insane Asylum (A Blog by Pat Wright)

Information about SQL (PostgreSQL & SQL Server) from the Asylum.

Gareth's Blog

A blog about Life, SQL & Everything ...