








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









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.
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.
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.
4. Algorithm (Step-wise Process) 1. Import pandas and matplotlib.pyplot.
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.
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.
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.
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.
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.
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.
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.
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.
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.
4. Algorithm (Step-wise Process) 1. Load the wine dataset and split into train/test subsets.
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.