The Pra-2 folder contains thirteen scripts and notebooks for advanced machine learning and data analysis tasks, covering classification, anomaly detection, clustering, and sequence modeling.
Description: This script generates synthetic images of circles, squares, and triangles, adds noise, and uses a KNN classifier to classify them.
Dependencies: numpy
, opencv-python
, scikit-learn
, matplotlib
Code Snippet:
import numpy as np import cv2 from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier def generate_shape(shape, size=32): img = np.zeros((size, size), dtype=np.uint8) if shape == "circle": cv2.circle(img, (16,16), 10, 255, -1) elif shape == "square": cv2.rectangle(img, (8,8), (24,24), 255, -1) elif shape == "triangle": pts = np.array([[16,4],[4,28],[28,28]], np.int32) cv2.drawContours(img, [pts], 0, 255, -1) return img def create_dataset(n=100): X, y, shapes = [], [], ["circle", "square", "triangle"] for idx, shape in enumerate(shapes): for _ in range(n): img = generate_shape(shape) noise = np.random.normal(0, 10, img.shape).astype(np.uint8) noisy_img = cv2.add(img, noise) X.append(noisy_img.flatten()) y.append(idx) return np.array(X), np.array(y), shapes