0% found this document useful (0 votes)
4 views6 pages

629 ML Assignment

ml assignment

Uploaded by

02-Abhishek A
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

629 ML Assignment

ml assignment

Uploaded by

02-Abhishek A
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Assignment unit 3

- Dhaneshwaran S(RA2211003011629)

Q1) Code:

import numpy as np

from sklearn.cluster import KMeans

import matplotlib.pyplot as plt

# Generate sample data

np.random.seed(42)

X = np.random.randn(300, 2)

# Perform K-means clustering

kmeans = KMeans(n_clusters=3, random_state=42)

kmeans.fit(X)

# Get cluster centers and labels

centers = kmeans.cluster_centers_

labels = kmeans.labels_

# Plot the results

plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis')

plt.scatter(centers[:, 0], centers[:, 1], c='red', marker='x', s=200,

linewidths=3)

plt.title('K-means Clustering')

plt.show()

# Function to predict cluster for new data points

def predict_cluster(new_data):

return kmeans.predict(new_data)

# Example usage
new_point = np.array([[0.5, 0.5]])

predicted_cluster = predict_cluster(new_point)

print(f"Predicted cluster for {new_point}: {predicted_cluster}")


Output:

Q2) Code:

import numpy as np

import matplotlib.pyplot as plt

from sklearn.decomposition import PCA

from sklearn.datasets import load_iris

from mpl_toolkits.mplot3d import Axes3D

# Load the Iris dataset

iris = load_iris()

X = iris.data # Features

y = iris.target # Target labels (classes)


# Perform PCA to reduce the data from 4 dimensions to 2 dimensions

pca = PCA(n_components=2)

X_pca = pca.fit_transform(X)

# Explained variance

explained_variance = pca.explained_variance_ratio_

# Plotting the 2D PCA result

plt.figure(figsize=(8, 6))

plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap='viridis', edgecolor='k', s=100)

plt.title('PCA on Iris Dataset (2 Components)')

plt.xlabel(f'Principal Component 1 ({explained_variance[0]:.2f} variance)')

plt.ylabel(f'Principal Component 2 ({explained_variance[1]:.2f} variance)')

plt.colorbar()

plt.grid(True)

plt.show()

# Optional: Performing PCA to reduce the data to 3 components for 3D visualization

pca_3d = PCA(n_components=3)

X_pca_3d = pca_3d.fit_transform(X)

# Plotting the 3D PCA result

fig = plt.figure(figsize=(8, 6))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(X_pca_3d[:, 0], X_pca_3d[:, 1], X_pca_3d[:, 2], c=y, cmap='viridis', edgecolor='k', s=100)
ax.set_title('PCA on Iris Dataset (3 Components)')

ax.set_xlabel(f'PC 1 ({pca_3d.explained_variance_ratio_[0]:.2f})')

ax.set_ylabel(f'PC 2 ({pca_3d.explained_variance_ratio_[1]:.2f})')

ax.set_zlabel(f'PC 3 ({pca_3d.explained_variance_ratio_[2]:.2f})')

plt.show()

# Print explained variance ratio for each principal component

print("Explained variance ratio of each component:\n", pca.explained_variance_ratio_)

Output:

You might also like