Skip to main content

Mms

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

# Given dataset
data = np.array([
    [1.0, 2.0],
    [1.5, 1.8],
    [5.0, 8.0],
    [8.0, 8.0],
    [1.0, 0.6],
    [9.0, 11.0],
    [8.0, 2.0],
    [10.0, 2.0],
    [9.0, 3.0]
])

# Perform K-Means clustering with 3 clusters
kmeans = KMeans(n_clusters=3, random_state=42)
kmeans.fit(data)
labels = kmeans.labels_
centroids = kmeans.cluster_centers_

# Visualize the clustered data points and centroids
plt.figure(figsize=(8, 6))
colors = ['red', 'blue', 'green']

# Plot data points with cluster colors
for i in range(len(data)):
    plt.scatter(data[i, 0], data[i, 1], color=colors[labels[i]], s=100)

# Plot centroids
plt.scatter(centroids[:, 0], centroids[:, 1], marker='X', s=200, color='black', linewidths=2)

# Add labels and title
plt.title('K-Means Clustering Results', fontsize=14)
plt.xlabel('X-axis', fontsize=12)
plt.ylabel('Y-axis', fontsize=12)

# Add grid and show plot
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()

# Print cluster assignments and centroids
print("Cluster assignments:")
for i, point in enumerate(data):
    print(f"Point {point} belongs to Cluster {labels[i]}")

print("\nCentroids:")
for i, centroid in enumerate(centroids):
    print(f"Cluster {i} centroid: {centroid}")



2:


import numpy as np

# Create ndarrays of different data types
print("Creating ndarrays with different data types:")
# Integer array
int_array = np.array([1, 2, 3, 4, 5], dtype=np.int32)
print(f"Integer array: {int_array}, dtype: {int_array.dtype}")

# Float array
float_array = np.array([1.1, 2.2, 3.3, 4.4, 5.5], dtype=np.float64)
print(f"Float array: {float_array}, dtype: {float_array.dtype}")

# Boolean array
bool_array = np.array([True, False, True, False], dtype=np.bool_)
print(f"Boolean array: {bool_array}, dtype: {bool_array.dtype}")

# String array
str_array = np.array(['apple', 'banana', 'cherry'], dtype=np.str_)
print(f"String array: {str_array}, dtype: {str_array.dtype}\n")

# Create a 2D array for demonstration
matrix = np.array([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
])
print("Original 2D array:")
print(matrix)

# Basic indexing
print("\nBasic indexing examples:")
print("Element at row 1, column 2:", matrix[1, 2]) # Returns 7
print("Entire row 0:", matrix[0]) # Returns [1, 2, 3, 4]
print("Entire column 1:", matrix[:, 1]) # Returns [2, 6, 10]

# Slicing examples
print("\nSlicing examples:")
print("First two rows:")
print(matrix[:2]) # Returns rows 0 and 1

print("\nLast two columns:")
print(matrix[:, -2:]) # Returns last two columns

print("\nSub-matrix (rows 1-2, columns 1-3):")
print(matrix[1:3, 1:3]) # Returns [[6, 7], [10, 11]]

# Fancy indexing
print("\nFancy indexing (selecting specific rows and columns):")
print("Rows 0 and 2, columns 1 and 3:")
print(matrix[[0, 2]][:, [1, 3]]) # Returns [[2, 4], [10, 12]]

# Boolean indexing
print("\nBoolean indexing (elements greater than 5):")
print(matrix[matrix > 5]) # Returns [6, 7, 8, 9, 10, 11, 12]



,,,




import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

# 1. Sample data
data = np.array([
    [1.0, 2.0], [1.5, 1.8], [5.0, 8.0],
    [8.0, 8.0], [1.0, 0.6], [9.0, 11.0],
    [8.0, 2.0], [10.0, 2.0], [9.0, 3.0]
])

# 2. Apply KMeans
kmeans = KMeans(n_clusters=3, random_state=0).fit(data)
labels = kmeans.labels_
centroids = kmeans.cluster_centers_

# 3. Plot clusters and centroids
plt.scatter(data[:, 0], data[:, 1], c=labels, s=100, cmap='viridis', label='Points')
plt.scatter(centroids[:, 0], centroids[:, 1], c='black', s=200, marker='X', label='Centroids')
plt.title('K-Means Clustering')
plt.legend()
plt.grid(True)
plt.show()

# 4. Print results
for i, point in enumerate(data):
    print(f"Point {point} → Cluster {labels[i]}")

print("\nCentroids:")
for i, c in enumerate(centroids):
    print(f"Cluster {i}: {c}")



import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA

# Step 1: Create a custom 3D dataset
data = np.array([
    [2.5, 2.4, 1.2],
    [0.5, 0.7, 0.4],
    [2.2, 2.9, 1.5],
    [1.9, 2.2, 1.1],
    [3.1, 3.0, 1.8],
    [2.3, 2.7, 1.4],
    [2.0, 1.6, 0.9],
    [1.0, 1.1, 0.3],
    [1.5, 1.6, 0.7],
    [1.1, 0.9, 0.2]
])

# Step 2: Apply PCA (3D to 2D)
pca = PCA(n_components=2)
reduced_data = pca.fit_transform(data)

# Step 3: Visualize the 2D result
plt.figure(figsize=(8, 6))
plt.scatter(reduced_data[:, 0], reduced_data[:, 1], color='teal', s=100)
plt.title("PCA - Dimensionality Reduction (3D to 2D)", fontsize=14)
plt.xlabel("Principal Component 1", fontsize=12)
plt.ylabel("Principal Component 2", fontsize=12)
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()

# Step 4: Print details
print("Explained Variance Ratio:", pca.explained_variance_ratio_)
print("\nReduced Data:\n", reduced_data)

Comments