mllab-programs 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.4
2
+ Name: mllab-programs
3
+ Version: 0.1.0
4
+ Summary: 8 machine-learning lab programs, viewable and loadable inside Jupyter
5
+ License: MIT
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+
9
+ # mllab-programs
10
+
11
+ ```python
12
+ import mllab
13
+ mllab.list() # list all 8 programs
14
+ mllab.show(1) # display program 1
15
+ mllab.load(1) # put program 1 into the next Jupyter cell
16
+ mllab.show_all() # display everything
17
+ ```
@@ -0,0 +1,9 @@
1
+ # mllab-programs
2
+
3
+ ```python
4
+ import mllab
5
+ mllab.list() # list all 8 programs
6
+ mllab.show(1) # display program 1
7
+ mllab.load(1) # put program 1 into the next Jupyter cell
8
+ mllab.show_all() # display everything
9
+ ```
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mllab-programs"
7
+ version = "0.1.0"
8
+ description = "8 machine-learning lab programs, viewable and loadable inside Jupyter"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = {text = "MIT"}
12
+
13
+ [tool.setuptools.packages.find]
14
+ where = ["src"]
15
+
16
+ [tool.setuptools.package-data]
17
+ mllab = ["programs/*.txt"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,38 @@
1
+ from importlib import resources
2
+
3
+ _N = range(1, 9)
4
+
5
+
6
+ def _code(n):
7
+ if n not in _N:
8
+ raise ValueError("program number must be 1-8")
9
+ return (resources.files("mllab") / "programs" / f"{n}.txt").read_text(encoding="utf-8")
10
+
11
+
12
+ def list():
13
+ for n in _N:
14
+ print(n, "-", _code(n).splitlines()[0].lstrip("# ").strip())
15
+
16
+
17
+ def show(n):
18
+ code = _code(n)
19
+ try:
20
+ from IPython.display import Code, display
21
+ display(Code(code, language="python"))
22
+ except ImportError:
23
+ print(code)
24
+
25
+
26
+ def show_all():
27
+ for n in _N:
28
+ show(n)
29
+
30
+
31
+ def load(n):
32
+ """Put program n into the next Jupyter cell (falls back to show)."""
33
+ try:
34
+ from IPython import get_ipython
35
+ ip = get_ipython()
36
+ ip.set_next_input(_code(n))
37
+ except Exception:
38
+ show(n)
@@ -0,0 +1,53 @@
1
+ # Program 1: Data Exploration and Visualization
2
+
3
+ import pandas as pd
4
+ import seaborn as sns
5
+ import matplotlib.pyplot as plt
6
+ from sklearn.datasets import load_iris
7
+
8
+ # Load dataset
9
+ iris = load_iris()
10
+ df = pd.DataFrame(iris.data, columns=iris.feature_names)
11
+ df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
12
+
13
+ # Basic Data Exploration
14
+
15
+ print("\n--- First 5 rows ---")
16
+ print(df.head())
17
+
18
+ print("\n--- Data Types & Missing Values ---")
19
+ print(df.info())
20
+
21
+ print("\nMissing values:\n", df.isnull().sum())
22
+
23
+ print("\n--- Summary Statistics ---")
24
+ print(df.describe(include='all'))
25
+
26
+ print("\n--- Class Distribution ---")
27
+ print(df['species'].value_counts())
28
+
29
+ # Data Visualization
30
+
31
+ # Histogram
32
+ df.hist(figsize=(8, 6))
33
+ plt.suptitle("Histograms of Iris Features", fontsize=14)
34
+ plt.show()
35
+
36
+ # Boxplot
37
+ plt.figure(figsize=(8, 6))
38
+ sns.boxplot(data=df, orient="h")
39
+ plt.title("Boxplots of Iris Features")
40
+ plt.show()
41
+
42
+ # Pairplot
43
+ sns.pairplot(df, hue="species", diag_kind="hist")
44
+ plt.suptitle("Pairwise Scatter Plots of Iris Features", y=1.02)
45
+ plt.show()
46
+
47
+ # Scatter Plot
48
+ plt.figure(figsize=(7, 5))
49
+ sns.scatterplot(x="sepal length (cm)",
50
+ y="sepal width (cm)",
51
+ hue="species", data=df, s=70)
52
+ plt.title("Sepal Length vs Sepal Width")
53
+ plt.show()
@@ -0,0 +1,61 @@
1
+ # Program 2: Simple Linear Regression on Boston Housing
2
+
3
+ import pandas as pd
4
+ import numpy as np
5
+ import matplotlib.pyplot as plt
6
+
7
+ from sklearn.linear_model import LinearRegression
8
+ from sklearn.metrics import mean_squared_error, r2_score
9
+
10
+ # Load the dataset
11
+ df = pd.read_csv("BostonHousing.csv")
12
+
13
+ print("\n--- First 5 rows ---")
14
+ print(df.head())
15
+
16
+ print("\n--- Data Info ---")
17
+ print(df.info())
18
+
19
+ print("\n--- Summary Statistics ---")
20
+ print(df.describe())
21
+
22
+ # Select input and target
23
+ X = df[['rm']]
24
+ y = df['medv']
25
+
26
+ # Train the Linear Regression model
27
+ model = LinearRegression()
28
+ model.fit(X, y)
29
+
30
+ print("\nIntercept (b0):", model.intercept_)
31
+ print("Slope (b1):", model.coef_[0])
32
+
33
+ # Predictions
34
+ y_pred = model.predict(X)
35
+
36
+ # Model Performance
37
+ print("\nMean Squared Error:", mean_squared_error(y, y_pred))
38
+ print("R2 Score:", r2_score(y, y_pred))
39
+
40
+ # Regression Line Plot
41
+ plt.figure(figsize=(8, 6))
42
+ plt.scatter(X, y, color='blue', alpha=0.6, label='Actual')
43
+ plt.plot(X, y_pred, color='red', linewidth=2, label='Regression line')
44
+
45
+ plt.xlabel("Average number of rooms per dwelling (RM)")
46
+ plt.ylabel("Median home value (MEDV)")
47
+ plt.title("Simple Linear Regression: RM vs MEDV")
48
+ plt.legend()
49
+ plt.show()
50
+
51
+ # Residuals Plot
52
+ residuals = y - y_pred
53
+
54
+ plt.figure(figsize=(8, 6))
55
+ plt.scatter(y_pred, residuals, color='purple', alpha=0.6)
56
+ plt.axhline(y=0, color='black', linestyle='--')
57
+
58
+ plt.xlabel("Predicted values")
59
+ plt.ylabel("Residuals (Actual - Predicted)")
60
+ plt.title("Residuals Plot")
61
+ plt.show()
@@ -0,0 +1,75 @@
1
+ # Program 3: Logistic Regression with Confusion Matrix Plot
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import matplotlib.pyplot as plt
6
+ import seaborn as sns
7
+
8
+ from sklearn.datasets import load_breast_cancer
9
+ from sklearn.model_selection import train_test_split
10
+ from sklearn.linear_model import LogisticRegression
11
+
12
+ from sklearn.metrics import (
13
+ accuracy_score,
14
+ precision_score,
15
+ recall_score,
16
+ confusion_matrix,
17
+ classification_report
18
+ )
19
+
20
+ # Load dataset
21
+ data = load_breast_cancer()
22
+
23
+ X = data.data
24
+ y = data.target
25
+
26
+ # Split dataset into training and testing sets
27
+ X_train, X_test, y_train, y_test = train_test_split(
28
+ X, y, test_size=0.2, random_state=42, stratify=y
29
+ )
30
+
31
+ # Create Logistic Regression model
32
+ model = LogisticRegression(max_iter=10000)
33
+ model.fit(X_train, y_train)
34
+
35
+ # Make predictions
36
+ y_pred = model.predict(X_test)
37
+
38
+ # Evaluate the model
39
+ accuracy = accuracy_score(y_test, y_pred)
40
+ precision = precision_score(y_test, y_pred)
41
+ recall = recall_score(y_test, y_pred)
42
+
43
+ conf_matrix = confusion_matrix(y_test, y_pred)
44
+
45
+ # Print results
46
+ print("Logistic Regression Model Evaluation:")
47
+ print(f"Accuracy: {accuracy:.4f}")
48
+ print(f"Precision: {precision:.4f}")
49
+ print(f"Recall: {recall:.4f}")
50
+
51
+ print("\nConfusion Matrix:")
52
+ print(conf_matrix)
53
+
54
+ print("\nClassification Report:")
55
+ print(classification_report(
56
+ y_test, y_pred,
57
+ target_names=data.target_names
58
+ ))
59
+
60
+ # Plot Confusion Matrix
61
+ plt.figure(figsize=(6, 4))
62
+
63
+ sns.heatmap(
64
+ conf_matrix,
65
+ annot=True,
66
+ fmt="d",
67
+ cmap="Blues",
68
+ xticklabels=data.target_names,
69
+ yticklabels=data.target_names
70
+ )
71
+
72
+ plt.xlabel("Predicted")
73
+ plt.ylabel("Actual")
74
+ plt.title("Confusion Matrix - Logistic Regression")
75
+ plt.show()
@@ -0,0 +1,74 @@
1
+ # K-NN Classification using Iris Dataset
2
+
3
+ # Step 1: Import libraries
4
+ import numpy as np
5
+ import matplotlib.pyplot as plt
6
+ from sklearn.datasets import load_iris
7
+ from sklearn.neighbors import KNeighborsClassifier
8
+
9
+ # Step 2: Load Iris dataset
10
+ iris = load_iris()
11
+
12
+ print(type(iris.data))
13
+ print(iris.data.shape)
14
+ print(iris.target.shape)
15
+ print(iris.data[0:20, 0:2])
16
+ print(iris.target[0:20])
17
+
18
+ # Use only 2 features for visualization
19
+ X = iris.data[:, [0, 2]] # Sepal Length and Petal Length
20
+ XX = iris.data[:, :2] # First two features
21
+ y = iris.target
22
+
23
+ # Step 3: Try different values of K
24
+ k_values = [1, 3, 5, 10]
25
+
26
+ for k in k_values:
27
+
28
+ # Create and train K-NN model
29
+ model = KNeighborsClassifier(n_neighbors=k)
30
+ model.fit(X, y)
31
+
32
+ # Calculate accuracy
33
+ accuracy = model.score(X, y)
34
+ print("k =", k, " Accuracy =", accuracy)
35
+
36
+ # Step 4: Create a grid for decision boundary
37
+ x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
38
+ y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
39
+
40
+ print("X[:, 0].min():", X[:, 0].min())
41
+ print("X[:, 0].max():", X[:, 0].max())
42
+ print("X[:, 1].min():", X[:, 1].min())
43
+ print("X[:, 1].max():", X[:, 1].max())
44
+
45
+ print("x_min:", x_min)
46
+ print("x_max:", x_max)
47
+ print("y_min:", y_min)
48
+ print("y_max:", y_max)
49
+
50
+ xx, yy = np.meshgrid(
51
+ np.arange(x_min, x_max, 0.02),
52
+ np.arange(y_min, y_max, 0.02)
53
+ )
54
+
55
+ print("xx", xx)
56
+ print("yy", yy)
57
+
58
+ # Predict class for every point in the grid
59
+ Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
60
+ Z = Z.reshape(xx.shape)
61
+
62
+ # Plot decision boundary
63
+ plt.figure(figsize=(5, 3))
64
+ plt.contourf(xx, yy, Z, alpha=0.3)
65
+
66
+ # Plot actual data points
67
+ plt.scatter(X[:, 0], X[:, 1], c=y, edgecolor='k')
68
+
69
+ plt.xlabel("Sepal Length")
70
+ plt.ylabel("Petal Length")
71
+
72
+ plt.title("K-NN Decision Boundary (k = " + str(k) + ")")
73
+
74
+ plt.show()
@@ -0,0 +1,48 @@
1
+ 5)
2
+ import pandas as pd
3
+ from sklearn.datasets import load_iris
4
+ from sklearn.tree import DecisionTreeClassifier, plot_tree, export_text
5
+ from sklearn.model_selection import train_test_split
6
+ from sklearn.metrics import accuracy_score, classification_report
7
+ import matplotlib.pyplot as plt
8
+
9
+ iris = load_iris()
10
+
11
+ X = pd.DataFrame(iris.data, columns=iris.feature_names)
12
+ y = pd.Series(iris.target, name='target')
13
+
14
+ X_train, X_test, y_train, y_test = train_test_split(
15
+ X, y, test_size=0.3, random_state=42
16
+ )
17
+
18
+ model = DecisionTreeClassifier(
19
+ criterion='entropy',
20
+ max_depth=3,
21
+ random_state=42
22
+ )
23
+
24
+ model.fit(X_train, y_train)
25
+
26
+ y_pred = model.predict(X_test)
27
+
28
+ print("Decision Tree Classifier Accuracy:",
29
+ accuracy_score(y_test, y_pred))
30
+ print("\nClassification Report:\n",
31
+ classification_report(
32
+ y_test, y_pred,
33
+ target_names=iris.target_names
34
+ ))
35
+
36
+ plt.figure(figsize=(12, 8))
37
+ plot_tree(
38
+ model,
39
+ feature_names=iris.feature_names,
40
+ class_names=iris.target_names,
41
+ filled=True,
42
+ rounded=True,
43
+ fontsize=10
44
+ )
45
+
46
+ plt.title("Decision Tree Visualization - Iris Dataset")
47
+
48
+ plt.show()
@@ -0,0 +1,92 @@
1
+ # Program 6: K-Means Clustering on Iris Dataset
2
+
3
+ # Step 1: Import required libraries
4
+ import pandas as pd
5
+ import numpy as np
6
+ from sklearn import datasets
7
+ from sklearn.cluster import KMeans
8
+ import matplotlib.pyplot as plt
9
+ from sklearn.preprocessing import StandardScaler
10
+
11
+ # Step 2: Load the Iris dataset
12
+ iris = datasets.load_iris()
13
+ X = iris.data
14
+
15
+ print(X[0:5])
16
+
17
+ # Step 3: Standardize the features
18
+ scaler = StandardScaler()
19
+ X_scaled = scaler.fit_transform(X)
20
+
21
+ print(X_scaled[0:5])
22
+
23
+ # Step 4: Apply K-Means clustering
24
+ kmeans = KMeans(n_clusters=3, random_state=42)
25
+ kmeans.fit(X_scaled)
26
+
27
+ # Step 5: Get cluster labels and centroids
28
+ labels = kmeans.labels_
29
+ centroids = kmeans.cluster_centers_
30
+
31
+ # Step 6: Visualize the clusters
32
+ plt.figure(figsize=(8, 6))
33
+
34
+ plt.scatter(
35
+ X_scaled[:, 0],
36
+ X_scaled[:, 1],
37
+ c=labels,
38
+ cmap='viridis',
39
+ s=50
40
+ )
41
+
42
+ plt.scatter(
43
+ centroids[:, 0],
44
+ centroids[:, 1],
45
+ c='red',
46
+ s=200,
47
+ marker='X',
48
+ label='Centroids'
49
+ )
50
+
51
+ plt.title("K-Means Clustering on Iris Dataset")
52
+ plt.xlabel("Feature 1 (standardized)")
53
+ plt.ylabel("Feature 2 (standardized)")
54
+ plt.legend()
55
+ plt.show()
56
+
57
+ # Step 7: Print cluster centers
58
+ print("Cluster Centers (Standardized Feature Space):\n", centroids)
59
+
60
+ # Step 8: Compare predicted clusters with actual labels
61
+ y_true = iris.target
62
+
63
+ print("\nActual Labels (0=setosa, 1=versicolor, 2=virginica):")
64
+ print(y_true[:10])
65
+
66
+ print("Predicted Cluster Labels:")
67
+ print(labels[:10])
68
+
69
+ # Additional visualization
70
+ plt.figure(figsize=(8, 6))
71
+
72
+ plt.scatter(
73
+ X_scaled[:, 2],
74
+ X_scaled[:, 3],
75
+ c=labels,
76
+ cmap='viridis',
77
+ s=50
78
+ )
79
+
80
+ plt.scatter(
81
+ centroids[:, 2],
82
+ centroids[:, 3],
83
+ c='red',
84
+ s=200,
85
+ marker='X',
86
+ label='Centroids'
87
+ )
88
+
89
+ plt.xlabel("Petal length (standardized)")
90
+ plt.ylabel("Petal width (standardized)")
91
+ plt.legend()
92
+ plt.show()
@@ -0,0 +1,78 @@
1
+ # Program 7: Support Vector Machine (SVM)
2
+
3
+ # Step 1: Import required libraries
4
+ from sklearn import datasets
5
+ from sklearn.model_selection import train_test_split
6
+ from sklearn.preprocessing import StandardScaler
7
+ from sklearn.svm import SVC
8
+ from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
9
+ import matplotlib.pyplot as plt
10
+
11
+ # Step 2: Load MNIST dataset (Digits dataset)
12
+ digits = datasets.load_digits()
13
+
14
+ # Display basic information
15
+ print("Image Data Shape:", digits.data.shape)
16
+ print("Label Data Shape:", digits.target.shape)
17
+
18
+ print(type(digits.target))
19
+ print(digits.data)
20
+ print(digits.target)
21
+
22
+ print(digits.data[0])
23
+ print(digits.target[0])
24
+
25
+ plt.figure(figsize=(8, 4))
26
+ plt.imshow(digits.data[0].reshape(8, 8), cmap=plt.cm.gray)
27
+ plt.show()
28
+
29
+ # Visualize some samples
30
+ plt.figure(figsize=(8, 4))
31
+
32
+ for index, (image, label) in enumerate(
33
+ zip(digits.data[0:8], digits.target[0:8])
34
+ ):
35
+ plt.subplot(2, 4, index + 1)
36
+ plt.imshow(image.reshape(8, 8), cmap=plt.cm.gray)
37
+ plt.title(f'Target: {label}')
38
+
39
+ plt.show()
40
+
41
+ # Step 3: Split dataset into training and testing sets
42
+ X_train, X_test, y_train, y_test = train_test_split(
43
+ digits.data,
44
+ digits.target,
45
+ test_size=0.3,
46
+ random_state=42
47
+ )
48
+
49
+ # Step 4: Feature scaling
50
+ scaler = StandardScaler()
51
+
52
+ X_train = scaler.fit_transform(X_train)
53
+ X_test = scaler.transform(X_test)
54
+
55
+ # Step 5: Train SVM classifier
56
+ svm_clf = SVC(kernel='rbf', gamma=0.05, C=10)
57
+ svm_clf.fit(X_train, y_train)
58
+
59
+ # Step 6: Predict test data
60
+ y_pred = svm_clf.predict(X_test)
61
+
62
+ # Step 7: Evaluate performance
63
+ print("\nConfusion Matrix:\n", confusion_matrix(y_test, y_pred))
64
+
65
+ print("\nClassification Report:\n",
66
+ classification_report(y_test, y_pred))
67
+
68
+ print("Accuracy:", accuracy_score(y_test, y_pred))
69
+
70
+ # Step 8: Visualize some predictions
71
+ plt.figure(figsize=(8, 4))
72
+
73
+ for i in range(8):
74
+ plt.subplot(2, 4, i + 1)
75
+ plt.imshow(X_test[i].reshape(8, 8), cmap=plt.cm.gray)
76
+ plt.title(f'Pred: {y_pred[i]} | True: {y_test[i]}')
77
+
78
+ plt.show()
@@ -0,0 +1,49 @@
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ from sklearn.datasets import fetch_openml
4
+ from sklearn.decomposition import PCA
5
+ from sklearn.preprocessing import StandardScaler
6
+ import pandas as pd
7
+
8
+ print("Loading MNIST dataset...")
9
+ mnist = pd.read_csv("MNIST.csv")
10
+
11
+ X = mnist.drop(columns=["label"]).values
12
+ y = mnist["label"].astype(int).values
13
+
14
+ print("Dataset loaded successfully!")
15
+ print("Feature shape:", X.shape)
16
+ print("Label shape:", y.shape)
17
+
18
+ print("Standardizing data...")
19
+ scaler = StandardScaler()
20
+ X_scaled = scaler.fit_transform(X)
21
+
22
+ pca = PCA(n_components=50)
23
+ X_pca = pca.fit_transform(X_scaled)
24
+ print("Reduced dataset shape:", X_pca.shape)
25
+
26
+ plt.figure(figsize=(8, 5))
27
+ plt.plot(
28
+ np.cumsum(pca.explained_variance_ratio_),
29
+ marker='o'
30
+ )
31
+ plt.title('Explained Variance by Principal Components')
32
+ plt.xlabel('Number of Components')
33
+ plt.ylabel('Cumulative Explained Variance')
34
+ plt.grid(True)
35
+ plt.show()
36
+
37
+ plt.figure(figsize=(8, 6))
38
+ plt.scatter(
39
+ X_pca[:10000, 0],
40
+ X_pca[:10000, 1],
41
+ c=y[:10000],
42
+ cmap='tab10',
43
+ s=10
44
+ )
45
+ plt.colorbar(label='Digit Label')
46
+ plt.title('MNIST data projected onto first 2 Principal Components')
47
+ plt.xlabel('Principal Component 1')
48
+ plt.ylabel('Principal Component 2')
49
+ plt.show()
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.4
2
+ Name: mllab-programs
3
+ Version: 0.1.0
4
+ Summary: 8 machine-learning lab programs, viewable and loadable inside Jupyter
5
+ License: MIT
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+
9
+ # mllab-programs
10
+
11
+ ```python
12
+ import mllab
13
+ mllab.list() # list all 8 programs
14
+ mllab.show(1) # display program 1
15
+ mllab.load(1) # put program 1 into the next Jupyter cell
16
+ mllab.show_all() # display everything
17
+ ```
@@ -0,0 +1,15 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/mllab/__init__.py
4
+ src/mllab/programs/1.txt
5
+ src/mllab/programs/2.txt
6
+ src/mllab/programs/3.txt
7
+ src/mllab/programs/4.txt
8
+ src/mllab/programs/5.txt
9
+ src/mllab/programs/6.txt
10
+ src/mllab/programs/7.txt
11
+ src/mllab/programs/8.txt
12
+ src/mllab_programs.egg-info/PKG-INFO
13
+ src/mllab_programs.egg-info/SOURCES.txt
14
+ src/mllab_programs.egg-info/dependency_links.txt
15
+ src/mllab_programs.egg-info/top_level.txt