Solution and implementation for Q1 from Machine Learning (ml).
A. To use PCA Algorithm for dimensionality reduction. You have a dataset that includes measurements for different variables on wine (alcohol, ash, magnesium, and so on). Apply PCA algorithm & transform this data so that most variations in the measurements of the variables are captured by a small number of principal components so that it is easier to distinguish between red and white wine by inspecting these principal components. Dataset Link: https://media.geeksforgeeks.org/wp-content/uploads/Wine.csv
# Import required libraries import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA
# Load the wine dataset
# Keep Wine.csv in the same folder as this notebook
df = pd.read_csv("Wine.csv")
print("Dataset shape:", df.shape)
df.head()# Separate input features and class labels
X = df.drop("Customer_Segment", axis=1)
y = df["Customer_Segment"]
print("Number of features:", X.shape[1])
print("Wine classes:", sorted(y.unique()))# Standardize the features scaler = StandardScaler() X_scaled = scaler.fit_transform(X)
# Reduce the features to two principal components
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
pca_df = pd.DataFrame(X_pca, columns=["PC1", "PC2"])
pca_df["Wine_Class"] = y.values
# Show how much variance each component captures
print("Explained variance ratio:", pca.explained_variance_ratio_)
print("Total variance captured:", round(pca.explained_variance_ratio_.sum() * 100, 2), "%")
pca_df.head()# Plot the two principal components by wine class
plt.figure(figsize=(8, 6))
for wine_class in sorted(pca_df["Wine_Class"].unique()):
data = pca_df[pca_df["Wine_Class"] == wine_class]
plt.scatter(data["PC1"], data["PC2"], label=f"Class {wine_class}", alpha=0.8)
plt.xlabel("First Principal Component (PC1)")
plt.ylabel("Second Principal Component (PC2)")
plt.title("PCA of Wine Dataset")
plt.legend()
plt.grid(True)
plt.show()# 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()# 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)
# 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))# 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])# 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()