How to classify wine using sklearn tree model in ML in python

This recipe helps you classify wine using sklearn tree model in ML in python

Recipe Objective

Have you ever tried to use Ensemble models like Bagging Classifier, Extra Tree Classifier and Random Forest Classifier for Analysis. In this we will using both for different dataset.

So this recipe is a short example of how we can classify "wine" using sklearn tree model - Multiclass Classification.

Access Text Classification using Naive Bayes Python Code

Step 1 - Import the library

from sklearn import datasets from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn import tree

Here we have imported various modules like datasets, mertics, tree and test_train_split from differnt libraries. We will understand the use of these later while using it in the in the code snipet.
For now just have a look on these imports.

Step 2 - Setup the Data

Here we have used datasets to load the inbuilt wine dataset and we have created objects X and y to store the data and the target value respectively. dataset = datasets.load_wine() X = dataset.data y = dataset.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

Step 3 - Model and its Score

Here, we are using Decision Tree Classifier as a Machine Learning model to fit the data. model = tree.DecisionTreeClassifier() model.fit(X_train, y_train) print(model) Now we have predicted the output by passing X_test and also stored real target in expected_y. expected_y = y_test predicted_y = model.predict(X_test) Here we have printed classification report and confusion matrix for the classifier. print(metrics.classification_report(expected_y, predicted_y, target_names=dataset.target_names)) print(metrics.confusion_matrix(expected_y, predicted_y))

Step 4 - Model and its Score

Here, we are using Extra Tree Classifier as a Machine Learning model to fit the data. model = tree.ExtraTreesClassifier() model.fit(X_train, y_train) print(model) Now we have predicted the output by passing X_test and also stored real target in expected_y. expected_y = y_test predicted_y = model.predict(X_test) Here we have printed classification report and confusion matrix for the Classifier. print(metrics.classification_report(expected_y, predicted_y, target_names=dataset.target_names)) print(metrics.confusion_matrix(expected_y, predicted_y)) As an output we get:

DecisionTreeClassifier(class_weight=None, criterion="gini", max_depth=None,
            max_features=None, max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter="best")

tree.DecisionTreeClassifier(): 

              precision    recall  f1-score   support

     class_0       0.92      0.86      0.89        14
     class_1       0.88      0.78      0.82        18
     class_2       0.75      0.92      0.83        13

   micro avg       0.84      0.84      0.84        45
   macro avg       0.85      0.85      0.85        45
weighted avg       0.85      0.84      0.85        45


[[12  1  1]
 [ 1 14  3]
 [ 0  1 12]]

ExtraTreeClassifier(class_weight=None, criterion="gini", max_depth=None,
          max_features="auto", max_leaf_nodes=None,
          min_impurity_decrease=0.0, min_impurity_split=None,
          min_samples_leaf=1, min_samples_split=2,
          min_weight_fraction_leaf=0.0, random_state=None,
          splitter="random")

tree.ExtraTreeClassifier(): 

              precision    recall  f1-score   support

     class_0       0.80      0.86      0.83        14
     class_1       0.75      0.83      0.79        18
     class_2       1.00      0.77      0.87        13

   micro avg       0.82      0.82      0.82        45
   macro avg       0.85      0.82      0.83        45
weighted avg       0.84      0.82      0.82        45


[[12  2  0]
 [ 3 15  0]
 [ 0  3 10]]

Download Materials

What Users are saying..

profile image

Abhinav Agarwal

Graduate Student at Northwestern University
linkedin profile url

I come from Northwestern University, which is ranked 9th in the US. Although the high-quality academics at school taught me all the basics I needed, obtaining practical experience was a challenge.... Read More

Relevant Projects

Learn Hyperparameter Tuning for Neural Networks with PyTorch
In this Deep Learning Project, you will learn how to optimally tune the hyperparameters (learning rate, epochs, dropout, early stopping) of a neural network model in PyTorch to improve model performance.

MLOps Project to Build Search Relevancy Algorithm with SBERT
In this MLOps SBERT project you will learn to build and deploy an accurate and scalable search algorithm on AWS using SBERT and ANNOY to enhance search relevancy in news articles.

Many-to-One LSTM for Sentiment Analysis and Text Generation
In this LSTM Project , you will build develop a sentiment detection model using many-to-one LSTMs for accurate prediction of sentiment labels in airline text reviews. Additionally, we will also train many-to-one LSTMs on 'Alice's Adventures in Wonderland' to generate contextually relevant text.

Word2Vec and FastText Word Embedding with Gensim in Python
In this NLP Project, you will learn how to use the popular topic modelling library Gensim for implementing two state-of-the-art word embedding methods Word2Vec and FastText models.

End-to-End Snowflake Healthcare Analytics Project on AWS-2
In this AWS Snowflake project, you will build an end to end retraining pipeline by checking Data and Model Drift and learn how to redeploy the model if needed

Linear Regression Model Project in Python for Beginners Part 2
Machine Learning Linear Regression Project for Beginners in Python to Build a Multiple Linear Regression Model on Soccer Player Dataset.

Credit Card Default Prediction using Machine learning techniques
In this data science project, you will predict borrowers chance of defaulting on credit loans by building a credit score prediction model.

AWS MLOps Project to Deploy Multiple Linear Regression Model
Build and Deploy a Multiple Linear Regression Model in Python on AWS

MLOps AWS Project on Topic Modeling using Gunicorn Flask
In this project we will see the end-to-end machine learning development process to design, build and manage reproducible, testable, and evolvable machine learning models by using AWS

Stock Price Prediction Project using LSTM and RNN
Learn how to predict stock prices using RNN and LSTM models. Understand deep learning concepts and apply them to real-world financial data for accurate forecasting.