Docsity

Machine Learning lab record, Transcriptions of Machine Learning

Toggle sidebar
bg1
MACHINE LEARNING LABORATORY RECORD
Experiment 1: Central Tendency & Dispersion
1. Aim
To compute the mean, median, mode, variance, and standard deviation of a dataset.
2. Software Required
Python 3.x
IDE (Jupyter Notebook / IDLE)
Built-in
statistics
module
3. Theory
Statistical measures help summarize data. Central tendency (mean, median, mode) identifies the
center of a data distribution, while dispersion (variance, standard deviation) measures how spread
out the data is.
4. Algorithm (Step-wise Process)
1. Import the built-in
statistics
module.
2. Define a numeric dataset (list).
3. Compute metrics using
.mean()
,
.median()
,
.mode()
,
.variance()
, and
.stdev()
.
4. Print the formatted outputs.
5. Theoretical Analysis
For the input
[10, 20, 30, 40, 50]
, the center (mean and median) is exactly 30.
6. Procedure
1. Create a Python file.
2. Type the code and save it.
3. Run the script and verify the statistical values in the terminal.
7. Program
import statistics as st
data = [10, 20, 30, 40, 50]
print(f"""Dataset: {data}
Mean: {st.mean(data):.2f}
Median: {st.median(data):.2f}
Mode: {st.mode(data)}
Variance: {st.variance(data):.2f}
Standard Deviation: {st.stdev(data):.2f}""")
Machine Learning Laboratory Record Page 1 of 14
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Machine Learning lab record and more Transcriptions Machine Learning in PDF only on Docsity!

MACHINE LEARNING LABORATORY RECORD

Experiment 1: Central Tendency & Dispersion

1. Aim To compute the mean, median, mode, variance, and standard deviation of a dataset. 2. Software Required Python 3.x IDE (Jupyter Notebook / IDLE) Built-in statistics module 3. Theory Statistical measures help summarize data. Central tendency (mean, median, mode) identifies the center of a data distribution, while dispersion (variance, standard deviation) measures how spread out the data is. 4. Algorithm (Step-wise Process) 1. Import the built-in statistics module.

  1. Define a numeric dataset (list).
  2. Compute metrics using .mean(), .median(), .mode(), .variance(), and .stdev().
  3. Print the formatted outputs. 5. Theoretical Analysis For the input [10, 20, 30, 40, 50], the center (mean and median) is exactly 30. 6. Procedure
    1. Create a Python file.
  4. Type the code and save it.
  5. Run the script and verify the statistical values in the terminal. 7. Program

import statistics as st data = [10, 20, 30, 40, 50] print(f"""Dataset: {data} Mean: {st.mean(data):.2f} Median: {st.median(data):.2f} Mode: {st.mode(data)} Variance: {st.variance(data):.2f} Standard Deviation: {st.stdev(data):.2f}""")

8. Expected Outputs

Dataset: [10, 20, 30, 40, 50] Mean: 30. Median: 30. Mode: 10 Variance: 250. Standard Deviation: 15.

9. Result The central tendency and dispersion metrics were successfully calculated and displayed.

Experiment 2: Basic Libraries (Math, NumPy, SciPy)

1. Aim To perform basic scientific operations using built-in Math, NumPy, and SciPy libraries. 2. Software Required Python 3.x numpy, scipy 3. Theory Scientific libraries provide optimized functions for complex math. math handles scalar algebra, numpy manages multi-dimensional array operations, and scipy solves advanced calculus and optimization problems. 4. Algorithm (Step-wise Process) 1. Import math, numpy, and functions from scipy.

  1. Compute scalar math (square root, factorial, sine).
  2. Initialize 1D and 2D arrays using NumPy.
  3. Calculate function minimization and definite integrals using SciPy.
  4. Print all results. 5. Theoretical Analysis The math library correctly calculates 5! = 1 × 2 × 3 × 4 × 5 = 120. 6. Procedure
    1. Write the Python script.
  5. Execute the code.
  6. Observe the outputs for each library in the terminal.

4. Algorithm (Step-wise Process) 1. Import pandas and matplotlib.pyplot.

  1. Create a DataFrame from a dictionary and print it.
  2. Plot a line graph using X and y coordinates.
  3. Add axes labels, a title, and a legend.
  4. Display the visualization window. 5. Theoretical Analysis The Pandas dictionary format maps keys to column headers and lists to column values. 6. Procedure
    1. Run the script in the IDE.
  5. Check the terminal for the printed DataFrame.
  6. Check the pop-up window for the plotted graph. 7. Program

import matplotlib.pyplot as plt import pandas as pd print(pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 22]})) plt.plot([1, 2, 3, 4], [10, 15, 7, 20], marker='o', label='Sales') plt.xlabel('Month') plt.ylabel('Revenue') plt.title('Monthly Sales') plt.legend() plt.show()

8. Expected Outputs

Name Age 0 Alice 25 1 Bob 30 2 Charlie 22

(A graph window will also appear showing a line plot of Monthly Sales).

9. Result Successfully utilized Pandas for tabular data creation and Matplotlib for graphical visualization.

Experiment 4: Simple Linear Regression

1. Aim To implement Simple Linear Regression using scikit-learn. 2. Software Required Python 3.x sklearn, numpy, matplotlib

3. Theory Simple Linear Regression predicts a dependent variable (y) based on one independent variable (X) by fitting a straight line (y = mx + c) that minimizes the sum of squared errors. 4. Algorithm (Step-wise Process) 1. Define feature matrix X and target array y.

  1. Train a LinearRegression model.
  2. Extract and print the slope and intercept.
  3. Predict a new output for X=6.
  4. Plot the scatter data points and the red regression line. 5. Theoretical Analysis For slope m=0.80 and intercept c=2.60, evaluating at X=6 yields y = (0.80 × 6) + 2.60 = 7.40. 6. Procedure
    1. Execute the code.
  5. Record the slope and intercept from the console.
  6. Observe the regression line fitting the data on the graph. 7. Program

import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import LinearRegression X, y = np.array([[1], [2], [3], [4], [5]]), np.array([2, 4, 5, 4, 6]) reg = LinearRegression().fit(X, y) print(f"""Slope (coefficient): {reg.coef_[0]:.2f} Intercept: {reg.intercept_:.2f} Predicted value for X=6: {reg.predict([[6]])[0]:.2f}""") plt.scatter(X, y, color='blue', label='Data points') plt.plot(X, reg.predict(X), color='red', label='Regression line') plt.xlabel('X') plt.ylabel('y') plt.title('Simple Linear Regression') plt.legend() plt.show()

8. Expected Outputs

Slope (coefficient): 0. Intercept: 2. Predicted value for X=6: 7.

(Graph shows blue scatter points and a red best-fit line).

9. Result The Simple Linear Regression model was successfully trained, evaluated, and plotted.

8. Expected Outputs

mean_squared_error: 12. mean_absolute_error: 3.

9. Result The Multiple Linear Regression model successfully learned from multiple features and calculated validation error metrics.

Experiment 6: Decision Tree

1. Aim To implement a Decision Tree classifier and perform parameter tuning. 2. Software Required Python 3.x sklearn, matplotlib, seaborn 3. Theory A Decision Tree is a supervised learning method that splits data iteratively based on feature values, forming a tree-like model of decisions to classify inputs. 4. Algorithm (Step-wise Process) 1. Load the iris dataset.

  1. Split the data into 70% training and 30% testing.
  2. Train DecisionTreeClassifier with parameter tuning (max_depth=3).
  3. Generate a plot of the decision tree structure.
  4. Predict test data and plot a confusion matrix heatmap. 5. Theoretical Analysis Restricting max_depth to 3 prunes the tree, preventing it from over-learning the training data (overfitting). 6. Procedure
    1. Execute the code in the IDE.
  5. Observe the tree node conditions in the first visual window.
  6. Observe the classification performance in the heatmap window.

7. Program

import matplotlib.pyplot as plt import seaborn as sns from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier, plot_tree from sklearn.metrics import confusion_matrix iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=93) dtc = DecisionTreeClassifier(max_depth=3, random_state=93) dtc.fit(X_train, y_train) plt.figure(figsize=(12, 6)) plot_tree(dtc, feature_names=iris.feature_names, class_names=iris.target_names, filled=True, rounded=True) plt.show() y_pred = dtc.predict(X_test) cm = confusion_matrix(y_test, y_pred) sns.heatmap(cm, annot=True, fmt="d", cmap="magma", xticklabels=iris.target_names, yticklabels=iris.target_names) plt.xlabel("Predicted Values") plt.ylabel("True Labels") plt.title("Confusion Matrix") plt.show()

8. Expected Outputs (Two visual windows appear: A plotted Decision Tree structure diagram, followed by a heatmap visualization of the Confusion Matrix). 9. Result Successfully implemented, tuned, and visualized the Decision Tree classifier.

Experiment 7: K-Nearest Neighbors (KNN)

1. Aim To implement the K-Nearest Neighbors algorithm using sklearn. 2. Software Required Python 3.x sklearn, matplotlib 3. Theory KNN is a non-parametric classifier that assigns a label to a data point based on the majority class among its 'K' closest neighbors in the feature space.

8. Expected Outputs

2: Training Score = 0.96, Test Score = 0. 3: Training Score = 0.96, Test Score = 0. ...

(Graph opens showing accuracy trends for K values).

9. Result Successfully implemented KNN and identified accuracy trends across varying K values.

Experiment 8: Logistic Regression

1. Aim To implement Logistic Regression using sklearn for binary classification. 2. Software Required Python 3.x sklearn 3. Theory Logistic Regression uses a sigmoid function to model the probability of a discrete binary outcome ( or 1) based on independent feature variables. 4. Algorithm (Step-wise Process) 1. Load the breast_cancer dataset.

  1. Split data into training and test sets (70/30).
  2. Initialize the LogisticRegression model with max_iter=5000.
  3. Train the model and predict outcomes on the test set.
  4. Print the overall accuracy and classification report. 5. Theoretical Analysis Increasing max_iter allows the gradient descent solver enough iterations to correctly converge on the optimal weights. 6. Procedure
    1. Run the Python file.
  5. Check the terminal for the precision, recall, and f1-score tables.

7. Program

from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, classification_report data = load_breast_cancer() X, y = data.data, data.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) model = LogisticRegression(max_iter=5000) model.fit(X_train, y_train) y_pred = model.predict(X_test) print(f"Accuracy: {accuracy_score(y_test, y_pred):.2f}") print(classification_report(y_test, y_pred))

8. Expected Outputs

Accuracy: 0. precision recall f1-score support 0 0.97 0.95 0.96 63 1 0.97 0.98 0.98 108 ...

9. Result Logistic Regression model was successfully implemented and generated high classification accuracy.

Experiment 9: K-Means Clustering

1. Aim To implement the K-Means Clustering algorithm. 2. Software Required Python 3.x sklearn, matplotlib 3. Theory K-Means is an unsupervised learning algorithm that assigns unlabeled data points into exactly K distinct, non-overlapping clusters based on their distance to cluster centers (centroids). 4. Algorithm (Step-wise Process) 1. Load the first two features of the iris dataset.

  1. Initialize KMeans with K=3.
  2. Fit the model to find centroids and label the data.
  3. Extract the centroid coordinates.
  4. Scatter plot the clustered data and overlay the centroids as black 'X' marks.

4. Algorithm (Step-wise Process) 1. Load the wine dataset and split into train/test subsets.

  1. Standardize data using StandardScaler.
  2. Initialize a dictionary of five classification models.
  3. Iterate over the dictionary to fit and predict for each model.
  4. Print the accuracy report and plot the confusion matrix for each. 5. Theoretical Analysis Standardizing feature variance ensures distance-based classifiers (KNN, SVM) perform optimally. 6. Procedure
    1. Execute the code in the IDE.
  5. Wait for each heatmap plot to render, close it to process the next model, and review the sequential console outputs.

7. Program

import matplotlib.pyplot as plt import seaborn as sns from sklearn.datasets import load_wine from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, classification_report, confusion_matrix from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier data = load_wine() X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) classifiers = { "Logistic Regression": LogisticRegression(), "K-Nearest Neighbors": KNeighborsClassifier(), "Support Vector Machine": SVC(), "Decision Tree": DecisionTreeClassifier(), "Random Forest": RandomForestClassifier() } for name, model in classifiers.items(): model.fit(X_train, y_train) y_pred = model.predict(X_test) print(f"--- {name} ---") print(f"Accuracy: {accuracy_score(y_test, y_pred):.2f}") print(classification_report(y_test, y_pred)) cm = confusion_matrix(y_test, y_pred) plt.figure(figsize=(4, 3)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues') plt.title(f'Confusion Matrix - {name}') plt.xlabel('Predicted') plt.ylabel('Actual') plt.show()

8. Expected Outputs

--- Logistic Regression --- Accuracy: 0. ... --- K-Nearest Neighbors --- Accuracy: 0. ...

(Loops sequentially through 5 distinct Confusion Matrix heatmaps).

9. Result Successfully evaluated, visualized, and compared the classification performance of five distinct Machine Learning algorithms.