Solution and implementation for Q1 from Machine Learning (ml).
Apply Principal Component Analysis (PCA) for dimensionality reduction on the Wine dataset to distinguish between customer segments using principal components.
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA# Load dataset
df = pd.read_csv("Wine.csv")
print("Dataset Shape:", df.shape)
print("\nFirst 5 rows:")
print(df.head())Dataset Shape: (178, 14) First 5 rows: Alcohol Malic_Acid Ash ... OD280 Proline Customer_Segment 0 14.23 1.71 2.43 ... 3.92 1065 1 1 13.20 1.78 2.14 ... 3.40 1050 1 2 13.16 2.36 2.67 ... 3.17 1185 1 3 14.37 1.95 2.50 ... 3.45 1480 1 4 13.24 2.59 2.87 ... 2.93 735 1 [5 rows x 14 columns]
# Separate Features and Target
X = df.drop("Customer_Segment", axis=1)
y = df["Customer_Segment"]
print("Features count:", X.shape[1])
print("Target classes:", y.unique())Features count: 13 Target classes: [1 2 3]
# Scale the data
X_scaled = StandardScaler().fit_transform(X)
print("Data standardized (mean ~ 0, variance ~ 1).")Data standardized (mean ~ 0, variance ~ 1).
# Apply PCA
pca = PCA(n_components=2)
result = pca.fit_transform(X_scaled)
print("PCA Result (first 5 samples):\\n", result[:5])
print("\\nExplained Variance Ratio:", pca.explained_variance_ratio_)
print("Total Variance Explained:", sum(pca.explained_variance_ratio_))
print("Original Features:", X.shape[1])
print("Reduced Features:", result.shape[1])PCA Result (first 5 samples):\n [[ 3.31675081 1.44346263] [ 2.20946492 -0.33339289] [ 2.51674015 1.0311513 ] [ 3.75706561 2.75637191] [ 1.00890849 0.86983082]] \nExplained Variance Ratio: [0.36198848 0.1920749 ] Total Variance Explained: 0.5540633835693527 Original Features: 13 Reduced Features: 2
# Plot the results
plt.figure(figsize=(8, 6))
scatter = plt.scatter(result[:, 0], result[:, 1], c=y, cmap="viridis", edgecolors="black", s=60, alpha=0.85)
plt.xlabel("PC1 (First Principal Component)", fontsize=11)
plt.ylabel("PC2 (Second Principal Component)", fontsize=11)
plt.title("PCA on Wine Dataset (2D Projection)", fontsize=13, fontweight="bold")
plt.colorbar(scatter, label="Customer Segment")
plt.grid(True, linestyle="--", alpha=0.5)
plt.tight_layout()
plt.show()<Figure size ...>
# Import required libraries
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.metrics import accuracy_score, classification_report# Load the Iris dataset
data = pd.read_csv("Iris.csv")
data.head()Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species 0 1 5.1 3.5 1.4 0.2 Iris-setosa 1 2 4.9 3.0 1.4 0.2 Iris-setosa 2 3 4.7 3.2 1.3 0.2 Iris-setosa 3 4 4.6 3.1 1.5 0.2 Iris-setosa 4 5 5.0 3.6 1.4 0.2 Iris-setosa
# Separate features and species labels
X = data.drop(columns=["Id", "Species"])
y = data["Species"]# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)# Standardize the feature values
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)# Train the LDA classifier
lda = LinearDiscriminantAnalysis()
lda.fit(X_train_scaled, y_train)LinearDiscriminantAnalysis()
# Predict species and display model accuracy
y_pred = lda.predict(X_test_scaled)
print("Accuracy:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))Accuracy: 1.0
precision recall f1-score support
Iris-setosa 1.00 1.00 1.00 10
Iris-versicolor 1.00 1.00 1.00 10
Iris-virginica 1.00 1.00 1.00 10
accuracy 1.00 30
macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30
# Predict the species of a new flower using measurements in centimeters
new_flower = pd.DataFrame(
[[5.1, 3.5, 1.4, 0.2]],
columns=["SepalLengthCm", "SepalWidthCm", "PetalLengthCm", "PetalWidthCm"]
)
new_flower_scaled = scaler.transform(new_flower)
print("Predicted species:", lda.predict(new_flower_scaled)[0])Predicted species: Iris-setosa
# Plot the flowers using the two LDA components
X_scaled = scaler.transform(X)
X_lda = lda.transform(X_scaled)
plt.figure(figsize=(8, 6))
for species in sorted(y.unique()):
rows = y == species
plt.scatter(X_lda[rows, 0], X_lda[rows, 1], label=species)
plt.xlabel("Linear Discriminant 1")
plt.ylabel("Linear Discriminant 2")
plt.title("LDA on Iris Dataset")
plt.legend()
plt.grid(True)
plt.show()<Figure size 800x600 with 1 Axes>