tutorial - THE DATA SCIENCE LIBRARY https://sigmaquality.pl/tag/tutorial/ Wojciech Moszczyński Sat, 02 Mar 2019 19:38:00 +0000 pl-PL hourly 1 https://wordpress.org/?v=6.8.3 https://sigmaquality.pl/wp-content/uploads/2019/02/cropped-ryba-32x32.png tutorial - THE DATA SCIENCE LIBRARY https://sigmaquality.pl/tag/tutorial/ 32 32 Estimation of the result of the empirical research with machine learning tools (part 1) https://sigmaquality.pl/uncategorized/estimation-of-the-result-of-the-empirical-research-with-machine-learning-tools/ Sat, 02 Mar 2019 19:38:00 +0000 http://sigmaquality.pl/?p=5621 Machine learning tools Thanks using predictive and classification models for the area of machine learning tools is possible significant decrease cost of the verification laboratory [...]

Artykuł Estimation of the result of the empirical research with machine learning tools (part 1) pochodzi z serwisu THE DATA SCIENCE LIBRARY.

]]>

 Part one: preliminary graphical analysis to research of coefficients dependence 

Machine learning tools

Thanks using predictive and classification models for the area of machine learning tools is possible significant decrease cost of the verification laboratory research.

Costs of empirical verification are counted to the Technical cost of production. In production of some chemical active substantiation is necessary to lead laboratory empirical classification to allocate product to separated class of quality.

This research can turn out very expensive.  In the case of short runs of production, cost of this classification can make all production unprofitable.

With the help can come machine learning tools, who can replace expensive laboratory investigation by theoretical judgment.

Application of effective prediction model can decrease necessity of costly empirical research to the reasonable minimum.

Manual classification would be made in special situation where mode would be ineffective or in case of checking process by random testing.

Case study: laboratory classification of active chemical substance Poliaxid

We will now follow process of making model of machine learning based on the classification by the Random Forest method. Chemical plant produces small amounts expensive chemical substance named Poliaxid. This substance must meet very rigorous quality requirements. For each charge have to pass special laboratory verification. This empirical trials are expensive and long-lasting. Their cost significantly influence on the overall cost of production. Process of Poliaxid production is monitored by many gauges. Computer save eleven variables such trace contents of some chemical substances, acidity and density of the substance. There are remarked the level of some of the collected coefficients have relationship with result of the end quality classification. Cause of effect relationship drive to the conclusion — it is possible to create classification model to explain overall process. In this case study we use base, able to download from this address: source

This base contains results of 1593 trials and eleven coefficients saved during the process for each of the trial.

import pandas as pd
import numpy as np

df = pd.read_csv('c:/2/poliaxid.csv', index_col=0)
del df['nr.']
df.head(5)

In the last column named: “quality class” we can find results of the laboratory classification.

Classes 1 and 0 mean the best quality of the substance. Results 2, 3 and 4 means the worst quality.

Before we start make machine learning model we ought to look at the data. We do it thanks matrix plots. These plots show us which coefficient is good predictor, display overall dependencies between exogenic and endogenic ratios.

Graphical analysis to research of coefficients dependence

The action that should precede the construction of the model should be graphical overview.

In this way we obtain information whether model is possible to do.

First we ought to divide results from result column: “quality class” in to two categories: 'First' and 'Second'.

df['Qual_G'] = df['quality class'].apply(lambda x: 'First' if x < 2 else 'Second')
df.sample(3)

At the end of table appear new column: "Qual_G".

Now we create vector of correlation between independent coefficients and result factor in column: 'quality class'.

CORREL = df.corr().sort_values('quality class')
CORREL['quality class']

Correlation vector points significant influences exogenic factors on the results of empirical classification.

We chose most effective predictors among all eleven variables. We put this variables in to the matrix correlation plot.

This matrix plot contain two colors. Blue dots means firs quality. Thanks to this all dependencies is clearly displayed.

import seaborn as sns

sns.pairplot(data=df[['factorB', 'citric catoda','sulfur in nodinol', 'noracid', 'lacapon','Qual_G']], hue='Qual_G', dropna=True)

Matrix display clearly patterns of dependencies between variables. Easily see part of coefficients have significant impact on the classification the first or second quality class.

Dichotomic division is good to display dependencies. Let's see what happen when we use division for 5 class of quality. We use this classes that was made by laboratory. We took only two most effective predictors. Despite this plot is illegible.

In the next part of this letter we use machine learning tools to make theoretical classification.

Next part:

Estimation of the result of the empirical research with machine learning tools (part 2)

Artykuł Estimation of the result of the empirical research with machine learning tools (part 1) pochodzi z serwisu THE DATA SCIENCE LIBRARY.

]]>
Estimation of the result of the empirical research with machine learning tools (part 2) https://sigmaquality.pl/uncategorized/estimation-of-the-result-of-the-empirical-research-with-machine-learning-tools-part-2/ Sat, 02 Mar 2019 19:38:00 +0000 http://sigmaquality.pl/?p=5740 In first part of this publication described the problem of additional classification of the quality classes. Every charge of Poliaxid have to go through rigoristic, [...]

Artykuł Estimation of the result of the empirical research with machine learning tools (part 2) pochodzi z serwisu THE DATA SCIENCE LIBRARY.

]]>

 Artificial intelligence in process of classification 

In first part of this publication described the problem of additional classification of the quality classes. Every charge of Poliaxid have to go through rigoristic, expensive test to classification to the proper class of quality. [Source of data]

In last study we showed that some quantity factors associated with production have significant impact on the final quality of the substance.

 Existing correlation lead to the conclusion that it is possible effective model of artificial intelligence is applied 

It leads to the two conclusions:

  • Laborious method of classification could be replaced by theoretical model.
  • Persons who monitor production process could be informed by the model about probability of final quality of the substance.

Machine learning procedure allows us make try to build such model.

We open the base in Python.

import pandas as pd
import numpy as np

df = pd.read_csv('c:/2/poliaxid.csv', index_col=0)
df.head(5)

We divide set of data in to the independent variables X and dependent variable y, the result of the process.

X = df.drop('quality class', axis=1) 
y = df['quality class']    

Now we divide database into the training and test underset.

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=123,stratify=y)

Pipeline merge standardization and estimation. We took as the estimation method of Random Forest.

from sklearn.pipeline import make_pipeline
from sklearn import preprocessing
from sklearn.ensemble import RandomForestRegressor

pipeline = make_pipeline(preprocessing.StandardScaler(),
    RandomForestRegressor(n_estimators=100))

Hyperparameters of the random forest regression are declared.

hyperparameters = {'randomforestregressor__max_features': ['auto', 'sqrt', 'log2'],
                   'randomforestregressor__max_depth': [None, 5, 3, 1]}

Tune model using cross-validation pipeline.

from sklearn.model_selection import GridSearchCV
clf = GridSearchCV(pipeline, hyperparameters, cv=10)
clf.fit(X_train, y_train)

Random forest is the popular method using regression engine to obtain result.

Many scientists think that this is incorrect. Andrew Ng, in Machine Learning course at Coursers, explains why this is a bad idea - see his Lecture 6.1 - Logistic Regression | Classification at YouTubee. https://www.youtube.com/watch?v=-la3q9d7AKQ&t=0s&list=PLLssT5z_DsK-h9vYZkQkYNWcItqhlRJLN&index=33

I, as an apprentice, will lead this model to the end. Without this rounding Confusion Matrix would be impossible to use because y from the test set has discrete form but predicted y would be in format continuous.

Here we have array with the result of prediction our model. You can see continuous form of result.

y_pred

Empirical result has discrete form.

y.value_counts()

We make rounding continuous data to the discrete form.

y_pred = clf.predict(X_test)
y_pred = np.round(y_pred, decimals=0)

Typical regression equation should not be used to the classification, but logistic regression seems to can make classification.

This is occasion to compare linear regression, logistic regression and typical tool used to classification Support Vector Machine.

Now we make evaluation of the model. We use confusion matrix.

from sklearn.metrics import classification_report, confusion_matrix
from sklearn import metrics

co_matrix = metrics.confusion_matrix(y_test, y_pred)
co_matrix

print(classification_report(y_test, y_pred))

Regression Random Forest with a temporary adaptation to discrete results seems to be good!

According to the f1-score ratio, model of artificial intelligence can good classify for these classes which have many occurrences.

For example 0 class has 13 occurrence and model can't judge this class. In opposite to the class 0 is class 1. There are 136 test values and model can properly judge classes in  78

In next part of this investigation we will test models of artificial intelligence intended to the make classification.

Next part:

Estimation of the result of the empirical research with machine learning tools. Classification with SVM Support Vector Machine (part 3)

Artykuł Estimation of the result of the empirical research with machine learning tools (part 2) pochodzi z serwisu THE DATA SCIENCE LIBRARY.

]]>
Estimation of the result of the empirical research with machine learning tools. Classification with SVM Support Vector Machine (part 3) https://sigmaquality.pl/uncategorized/estimation-of-the-result-of-the-empirical-research-with-machine-learning-tools-part-three-classification-with-svm-support-vector-machine/ Sat, 02 Mar 2019 19:38:00 +0000 http://sigmaquality.pl/?p=5751 SVM Support Vector Machine

Artykuł Estimation of the result of the empirical research with machine learning tools. Classification with SVM Support Vector Machine (part 3) pochodzi z serwisu THE DATA SCIENCE LIBRARY.

]]>

This time we use model which is designed to classification application.

The SVM Support Vector Machine algorithm is included among the learning machine estimators based on the classification and regression analysis processes.

The SVM classifier uses an optimization algorithm based on maximizing the margin of the hyperplan. The SVM algorithm is designed to conduct the best possible classification of results. Vectors separating hyperspace can be linear or (thanks to the SVC function) non-linear.

In our model, we will use the linear SVM Support Vector Machine classifier.

We download all needed libraries and database file.

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt
import seaborn as sns
import pprint

from sklearn.pipeline import Pipeline
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.externals import joblib

df = pd.read_csv('c:/2/poliaxid.csv', index_col=0)
del df['nr.']
df.head(3)

Next we point the column y with the result of the calculations, and columns with independent variables X.

X=df.drop(['quality class'],axis=1)
Y=df['quality class']

Pipeline put together standardization and classification.

ew = [('scaler', StandardScaler()), ('SVM', SVC())]
pipeline = Pipeline(ew)
parameteres = {'SVM__C':[0.001,0.1,10,100,10e5], 'SVM__gamma':[0.1,0.01]}
X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=0.2, random_state=30, stratify=Y)
grid = GridSearchCV(pipeline, param_grid=parameteres, cv=5)
grid.fit(X_train, y_train)
print("score = 

I can see which superparamiters was chosen by the grid as the best.

pparam=pprint.PrettyPrinter(indent=2)
print(grid.best_params_)

y_pred = grid.predict(X_test)

Classificator is evaluation by confusion matrix.

from sklearn.metrics import classification_report, confusion_matrix
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred)) 

The SVM Support Vector Machine is not better clasificator than not adapted to such a role Random Forest regression.

Artykuł Estimation of the result of the empirical research with machine learning tools. Classification with SVM Support Vector Machine (part 3) pochodzi z serwisu THE DATA SCIENCE LIBRARY.

]]>