629 ML Assignment
629 ML Assignment
- Dhaneshwaran S(RA2211003011629)
Q1) Code:
import numpy as np
np.random.seed(42)
X = np.random.randn(300, 2)
kmeans.fit(X)
centers = kmeans.cluster_centers_
labels = kmeans.labels_
linewidths=3)
plt.title('K-means Clustering')
plt.show()
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)
Q2) Code:
import numpy as np
iris = load_iris()
X = iris.data # Features
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)
# Explained variance
explained_variance = pca.explained_variance_ratio_
plt.figure(figsize=(8, 6))
plt.colorbar()
plt.grid(True)
plt.show()
pca_3d = PCA(n_components=3)
X_pca_3d = pca_3d.fit_transform(X)
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()
Output: