Lesson 49 · Data Science Projects
Deep Learning for Wine Type Classification: Step-by-Step Model Training Guide
In this lesson, you will learn to predict wine types using a deep learning approach. Knowing how to classify wines from their features is helpful for…
- CourseData Science Projects
- Lesson49 of 33
- Video23 min
- FormatJupyter notebook · 16 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbPrediction of Wine Type using Deep Learning#
In this lesson, you will learn to predict wine types using a deep learning approach.
Knowing how to classify wines from their features is helpful for automating quality control and improving recommendations.
This hands-on notebook is great for beginners. You will see how a neural network works on a real dataset.
We will clean data, explore it visually, and build a deep learning model for classification.
No prior deep learning experience is required. Just follow along and type the code with me!
# Always suppress warnings for a cleaner output
import warnings
import numpy as np
np.random.seed(42)
warnings.filterwarnings("ignore")
Data setup#
- We will use the classic Wine Dataset from the UCI repository.
- Each row has measurements from a real wine.
- The goal is to predict the wine type (Class 1, 2, or 3) from these features.
- The dataset is small and perfect for learning deep learning basics.
# Download and load the classic wine classification dataset
import pandas as pd
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data'
cols = ['Class','Alcohol','Malic_acid','Ash','Alcalinity_of_ash','Magnesium','Total_phenols','Flavanoids','Nonflavanoid_phenols','Proanthocyanins','Color_intensity','Hue','OD280_OD315','Proline']
df = pd.read_csv(url, header=None, names=cols)
print(df.shape)
print(df.head(3))
Data Exploration#
- Before training, let us explore what the data looks like.
- We will look at summary statistics and see how many wines belong to each class.
- Data exploration is important to understand patterns and possible issues.
# Show statistics and distribution of classes
print(df.describe())
print("\nWine type counts:")
print(df['Class'].value_counts())
# Show correlation matrix to check feature relationships
corr = df.corr()
print(corr['Class'].sort_values(ascending=False))
# Visualize feature distributions for two classes
import seaborn as sns
import matplotlib.pyplot as plt
sns.histplot(df, x='Alcohol', hue='Class', bins=20, element='step')
plt.title('Alcohol content by wine type')
plt.show()
Data Preprocessing#
- Machine learning models work best when data is numeric and scaled properly.
- We will prepare the labels and scale the feature values to a similar range.
- This step is important for deep learning models to train correctly.
# Split data into features and labels, then scale features
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X = df.drop('Class', axis=1).values
y = df['Class'].values - 1 # classes 0,1,2
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape)
Introduction to Deep Learning Models#
- Deep learning is a special type of machine learning that uses neural networks.
- Neural networks try to learn complex patterns automatically instead of us writing rules.
- They contain layers of simple objects called neurons, connected like the brain.
- They perform extremely well when given enough data and the right settings.
# Build a simple neural network with Keras
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Dense(32, activation='relu', input_shape=(X_train.shape[1],)),
layers.Dense(16, activation='relu'),
layers.Dense(3, activation='softmax') # Output for 3 wine types
])
# Show model structure
model.summary()
# Compile the model to set up for training
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the neural network
history = model.fit(X_train, y_train, epochs=50, batch_size=16, validation_split=0.1, verbose=1)
# Plot training and validation accuracy over time
plt.plot(history.history['accuracy'], label='Train accuracy')
plt.plot(history.history['val_accuracy'], label='Validation accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.title('Training progress')
plt.legend()
plt.show()
# Evaluate the model on test data
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)
print(f"Test accuracy: {test_acc:.2f}")
Making Predictions#
- Let us try using our trained neural network to predict the class of a new wine.
- You will enter feature values, and the model will output the predicted wine type.
- This is what makes deep learning models useful for real world decision making.
# Get user input and predict wine class
import numpy as np
features = []
feature_names = list(df.columns[1:])
for f in feature_names:
val = float(input(f'Enter value for {f}: '))
features.append(val)
user_input = scaler.transform([features])
probs = model.predict(user_input)
pred_class = np.argmax(probs) + 1
print(f'Predicted wine class: {pred_class}')
# Confusion matrix for detailed accuracy
from sklearn.metrics import confusion_matrix
y_pred = np.argmax(model.predict(X_test), axis=1)
cm = confusion_matrix(y_test, y_pred)
print(cm)
# Try a mini project: Tune the model and see what happens
# Change epochs, batch size, or hidden sizes and retrain.
# For example, try increasing the first dense layer size to 64, or use 100 epochs.
# Rebuild and retrain if you want to practice more!
Next Steps & Stay Tuned!#
- Congratulations, you have just built your first deep learning classifier on real data!
- Practice by changing the model or trying other datasets listed in this channel.
- Make sure you subscribe and like the video for more deep learning lessons.
- Let me know in the comments what topics you want next!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



