Sure! Below is a comprehensive Python Jupyter Notebook that demonstrates how to train and evaluate a multi-class classifier using a dense neural network on a mobile phone sales dataset. This notebook includes data loading, preprocessing, model building, training, and evaluation with corresponding outputs.
# Mobile Phone Price Range Classification using Dense Neural Network
Bob has started his own mobile company and aims to compete with big players like Apple and Samsung. To effectively estimate the price ranges of mobile phones based on various features, we'll build a multi-class classifier using a dense neural network.
In this notebook, we will:
1. **Load and Explore the Dataset**
2. **Preprocess the Data**
3. **Build the Dense Neural Network Model**
4. **Train the Model**
5. **Evaluate the Model**
6. **Visualize Results**
Let's get started!
# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import confusion_matrix, accuracy_score, classification_report
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.callbacks import ModelCheckpoint
# Check TensorFlow version
print(f"TensorFlow Version: {tf.__version__}")
# Load the dataset
# Assuming the dataset is named 'mobile_price_range.csv' and is in the current directory
# If your dataset is named differently or located elsewhere, adjust the path accordingly
data = pd.read_csv('mobile_price_range.csv')
# Display the first few rows
data.head()
# Explore the dataset
print("Dataset Shape:", data.shape)
print("\nDataset Information:")
data.info()
# Check for missing values
print("\nMissing Values:")
print(data.isnull().sum())
# Statistical summary
data.describe()
# Encode the target variable if it's categorical
# Assuming the target variable is named 'price_range' and is already numerical
# If it's categorical, uncomment the following lines:
# label_encoder = LabelEncoder()
# data['price_range'] = label_encoder.fit_transform(data['price_range'])
# Check unique classes
print("\nUnique Price Ranges:", data['price_range'].unique())
# Define features and target
X = data.drop(['price_range', 'id'], axis=1) # Drop 'id' if it's not a useful feature
y = data['price_range']
# Feature names
print("\nFeature Names:", X.columns.tolist())
# Split the data into training and testing sets
# Using 80% for training and 20% for testing
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2,
random_state=42,
stratify=y)
print("Training Set Shape:", X_train.shape)
print("Testing Set Shape:", X_test.shape)
# Feature Scaling
scaler = StandardScaler()
# Fit on training data
X_train_scaled = scaler.fit_transform(X_train)
# Transform testing data
X_test_scaled = scaler.transform(X_test)
# Convert data to TensorFlow tensors (optional, as Keras can handle numpy arrays)
# X_train_scaled = tf.convert_to_tensor(X_train_scaled, dtype=tf.float32)
# X_test_scaled = tf.convert_to_tensor(X_test_scaled, dtype=tf.float32)
# Build the Dense Neural Network Model
model = Sequential([
Dense(128, activation='relu', input_shape=(X_train_scaled.shape[1],)),
Dropout(0.3),
Dense(64, activation='relu'),
Dropout(0.3),
Dense(32, activation='relu'),
Dropout(0.3),
Dense(len(y.unique()), activation='softmax') # Output layer for multi-class classification
])
# Display the model architecture
model.summary()
# Compile the model
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Set up model checkpoint to save the best model based on validation accuracy
checkpoint_cb = ModelCheckpoint("best_model.h5",
save_best_only=True,
monitor='val_accuracy',
mode='max',
verbose=1)
# Train the model
history = model.fit(
X_train_scaled, y_train,
epochs=50,
batch_size=32,
validation_split=0.1,
callbacks=[checkpoint_cb],
verbose=1
)
# Load the best model
best_model = tf.keras.models.load_model("best_model.h5")
# Plot training & validation accuracy and loss values
plt.figure(figsize=(14, 5))
# Accuracy plot
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train Accuracy', color='blue')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy', color='orange')
plt.title('Model Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
# Loss plot
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss', color='blue')
plt.plot(history.history['val_loss'], label='Validation Loss', color='orange')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
# Evaluate the model on the test set
test_loss, test_accuracy = best_model.evaluate(X_test_scaled, y_test, verbose=0)
print(f"\nTest Accuracy: {test_accuracy:.4f}")
print(f"Test Loss: {test_loss:.4f}")
# Predict on the test set
y_pred_probs = best_model.predict(X_test_scaled)
y_pred = np.argmax(y_pred_probs, axis=1)
# Compare with true labels
print("\nTrue Labels vs Predicted Labels:")
comparison_df = pd.DataFrame({'True': y_test, 'Predicted': y_pred})
print(comparison_df.head(10))
# Calculate overall accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"\nOverall Accuracy: {accuracy:.4f}")
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(8,6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=sorted(y.unique()),
yticklabels=sorted(y.unique()))
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.title('Confusion Matrix')
plt.show()
# Classification Report
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
# Bonus: Visualize some predictions
import random
# Select 10 random samples from the test set
random_indices = random.sample(range(X_test_scaled.shape[0]), 10)
sample_data = X_test_scaled[random_indices]
sample_true = y_test.iloc[random_indices]
sample_pred_probs = best_model.predict(sample_data)
sample_pred = np.argmax(sample_pred_probs, axis=1)
# Create a DataFrame for visualization
vis_df = pd.DataFrame(sample_data, columns=X.columns)
vis_df['True Label'] = sample_true.values
vis_df['Predicted Label'] = sample_pred
print("\nSample Predictions:")
print(vis_df[['True Label', 'Predicted Label']])
Explanation of the Notebook
-
Import Libraries: We start by importing all necessary libraries, including TensorFlow and Keras for building the neural network, Pandas and NumPy for data manipulation, and Scikit-learn for preprocessing and evaluation.
-
Load the Dataset: The dataset is loaded using pd.read_csv. Ensure that the CSV file (mobile_price_range.csv) is in the working directory or provide the correct path.
-
Explore the Dataset: We examine the dataset's shape, information, missing values, and statistical summary to understand the data better.
-
Preprocess the Data:
- Handling Missing Values: If there are any missing values, handle them appropriately (e.g., imputation or removal). In this notebook, we assume there are no missing values.
- Encoding Target Variable: If the target variable (
price_range) is categorical, encode it using LabelEncoder. In this case, it’s assumed to be numerical.
- Feature and Target Separation: Separate the dataset into features (
X) and target (y).
- Train-Test Split: Split the data into training and testing sets using an 80-20 split.
- Feature Scaling: Scale the features using
StandardScaler to normalize the data, which helps in faster convergence during training.
-
Build the Model: A Sequential model is built with multiple Dense layers. Dropout layers are added to prevent overfitting by randomly disabling neurons during training.
-
Compile the Model: The model is compiled with the Adam optimizer and sparse_categorical_crossentropy loss function suitable for multi-class classification.
-
Train the Model: The model is trained for 50 epochs with a batch size of 32. A ModelCheckpoint callback saves the best model based on validation accuracy.
-
Visualize Training History: Plot the training and validation accuracy and loss to observe the training process and check for overfitting.
-
Evaluate the Model: Load the best saved model and evaluate its performance on the test set, reporting accuracy and loss.
-
Predictions and Comparison: Make predictions on the test set and compare them with the true labels.
Output
Since this is a static representation, running the notebook in your local environment will produce the actual outputs, including model summaries, training progress, plots, and evaluation metrics.
Notes
-
Data File: Ensure that the mobile_price_range.csv file is available in your working directory. If it's located elsewhere, provide the correct path in the pd.read_csv() function.
-
Dependencies: Make sure all the required libraries are installed. You can install any missing libraries using pip. For example:
pip install pandas numpy matplotlib seaborn scikit-learn tensorflow
-
Model Performance: The number of epochs, batch size, and network architecture can be adjusted based on the dataset size and complexity to achieve better performance.
-
Overfitting: Monitor the training and validation metrics to ensure the model is not overfitting. Techniques like Dropout, regularization, or gathering more data can help mitigate overfitting.
-
Further Improvements: You can experiment with different architectures, hyperparameters, and preprocessing techniques to enhance model performance.
Conclusion
This notebook provides a complete workflow for building a multi-class classifier using a dense neural network to predict mobile phone price ranges based on various features. By following these steps, you can adapt the model to similar classification problems and further enhance its performance through experimentation and optimization.