#### Latest posts by Prasad Kharkar (see all)

- PyCharm for Machine Learning - July 17, 2018
- Linear Discriminant Analysis using Python - April 30, 2018
- Principal Component Analysis using Python - April 30, 2018

Hello all, till now, we have learned about pca technique. Now, we will learn about linear discriminant analysis using python.

# Linear Discriminant Analysis using Python:

Suppose there are **n** independent variables in your dataset. Performing linear discriminant analysis using python creates **n** or less than **n** new independent variables by separating classes of dependent variables. As it uses dependent variables, it comes under supervised learning.

We will reduce dimensions of our dataset to 2 by linear discriminant analysis using python.

## Dataset:

Please download **LDA **dataset from superdatascience website. You will find **wines.csv** file in the folder. It contains 14 columns. First 13 columns i.e. independent variables are contents of wine. Last column is customer segment. It has 3 values. This is a classification problem. Our objective is to reduce 13 independent variables to 2 so that we can visualize results on graph.

## Data Preprocessing:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# Linear Discriminant Analysis # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Wine.csv') X = dataset.iloc[:, 0:13].values y = dataset.iloc[:, 13].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) |

- We imported dataset and created matrices of independent and dependent variables
- We split dataset into training set and test set.
- Performed feature scaling.

## Linear Discriminant Analysis using Python:

Note that we want only two new new independent features to plot a 2 dimensional graph.

1 2 3 4 5 |
# Applying Linear Discriminant Analysis from sklearn.discriminant_analysis import LinearDiscriminantAnalysis lda = LinearDiscriminantAnalysis(n_components = 2) X_train = lda.fit_transform(X_train, y_train) X_test = lda.transform(X_test) |

We have called **lda.fit_transform(X_train, y_train)** by passing **y_train** also because lda is supervised learning.

## Perform Classification:

1 2 3 4 5 6 7 |
# Fitting Logistic Regression to the Training set from sklearn.linear_model import LogisticRegression classifier = LogisticRegression(random_state = 0) classifier.fit(X_train, y_train) # Predicting the Test set results y_pred = classifier.predict(X_test) |

We simply perform a logistic regression classification with 2 independent variables and predict results for X_test. Execute above code and we can see confusion matrix.

Note that all diagonal results 6 + 7 + 5 = 18 are correct predictions and all non diagonal results are 0. It means we have received 100% correct predictions in linear discriminant analysis using python.

## Visualizing Results:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from matplotlib.colors import ListedColormap X_set, y_set = X_test, y_test aranged_pc1 = np.arange(start = X_set[:, 0].min(), stop = X_set[:, 0].max(), step = 0.01) aranged_pc2 = np.arange(start = X_set[:, 1].min(), stop = X_set[:, 1].max(), step = 0.01) X1, X2 = np.meshgrid(aranged_pc1, aranged_pc2) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.5, cmap = ListedColormap(('orange', 'blue', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green','blue'))(i), label = j) plt.title('Linear Discriminant Analysis') plt.xlabel('LD1') plt.ylabel('LD2') plt.legend() plt.show() |