Unit - II ML Python Libraries

 

Python Libraries for Machine Learning 

Introduction to Machine Learning Libraries

Machine Learning (ML) is a field of Artificial Intelligence that enables computers to learn patterns from data and make predictions or decisions without being explicitly programmed.

Python is the most popular language for ML because it has many powerful libraries. The most important ones are:

  1. NumPy – for numerical computing

  2. Pandas – for data handling and analysis

  3. Matplotlib – for data visualization

  4. Scikit-learn (sklearn) – for building ML models


1. NumPy (Numerical Python)

What is NumPy?

NumPy is a Python library used for working with arrays and numerical data.
It is faster and more efficient than Python lists.

NumPy is mainly used for:

  • Mathematical operations

  • Linear algebra

  • Handling large datasets

Importing NumPy

import numpy as np

Creating Array: array()

An array is a collection of elements of the same type.

import numpy as np arr = np.array([10, 20, 30, 40]) print(arr)

Output:

[10 20 30 40]

2D Array:

mat = np.array([[1,2,3],[4,5,6]]) print(mat)

Accessing Array (Indexing)

Index starts from 0.

arr = np.array([10, 20, 30]) print(arr[0]) # 10 print(arr[2]) # 30

For 2D array:

mat = np.array([[1,2,3],[4,5,6]]) print(mat[0][1]) # 2

Stacking & Splitting

stack()

Used to join arrays.

a = np.array([1,2]) b = np.array([3,4]) c = np.stack((a,b)) print(c)

array_split()

Used to split arrays.

arr = np.array([1,2,3,4,5,6]) newarr = np.array_split(arr, 3) print(newarr)

Math Functions

a = np.array([10,20,30]) b = np.array([1,2,3]) print(np.add(a,b)) # addition print(np.subtract(a,b)) # subtraction print(np.multiply(a,b)) # multiplication print(np.divide(a,b)) # division print(np.power(a,2)) # power print(np.mod(a,b)) # modulus

Statistics Functions

arr = np.array([10,20,30,40]) print(np.amin(arr)) # minimum print(np.amax(arr)) # maximum print(np.mean(arr)) # mean print(np.median(arr)) # median print(np.std(arr)) # standard deviation print(np.var(arr)) # variance print(np.average(arr)) # average print(np.ptp(arr)) # range (max-min)

2. Pandas

What is Pandas?

Pandas is used for data manipulation and analysis.
It works with structured data like tables (rows and columns).

Two main structures:

  • Series (1D)

  • DataFrame (2D)

Import Pandas:

import pandas as pd

Series: Series()

A Series is a one-dimensional labeled array.

s = pd.Series([10,20,30]) print(s)

DataFrame: DataFrame()

A DataFrame is like an Excel table.

data = { "Name": ["Amit","Ravi","Neha"], "Marks": [85, 90, 88] } df = pd.DataFrame(data) print(df)

Read CSV File: read_csv()

CSV = Comma Separated Values.

df = pd.read_csv("student.csv") print(df)

Cleaning Empty Cells: dropna()

Removes rows with missing values.

df = df.dropna()

Cleaning Wrong Data: drop()

Used to remove specific rows or columns.

df = df.drop(2) # removes row with index 2

Removing Duplicates: duplicated()

print(df.duplicated()) df = df.drop_duplicates()

Pandas Plotting: plot()

df["Marks"].plot()

3. Matplotlib

What is Matplotlib?

Matplotlib is used for data visualization (graphs and charts).

Import:

import matplotlib.pyplot as plt

Line Plot: plot()

x = [1,2,3,4] y = [10,20,30,40] plt.plot(x,y) plt.show()

Labels: xlabel(), ylabel()

plt.xlabel("X Axis") plt.ylabel("Y Axis")

Grid: grid()

plt.grid()

Bar Chart: bar()

plt.bar(x,y) plt.show()

Histogram: hist()

marks = [50,60,70,80,90,85,75] plt.hist(marks) plt.show()

Subplot: subplot()

plt.subplot(1,2,1) plt.plot(x,y) plt.subplot(1,2,2) plt.bar(x,y) plt.show()

Pie Chart: pie()

data = [40,30,20,10] plt.pie(data) plt.show()

Save Plot as PDF: savefig()

plt.plot(x,y) plt.savefig("graph.pdf")

4. Scikit-learn (sklearn)

What is Scikit-learn?

Scikit-learn is the most popular library for Machine Learning algorithms.

It provides:

  • Classification

  • Regression

  • Clustering

  • Model evaluation


Key Concepts in Sklearn

  1. Dataset – Collection of data

  2. Features – Input variables

  3. Target – Output variable

  4. Model – Algorithm used for learning

  5. Training – Teaching model with data

  6. Testing – Checking model performance

  7. Prediction – Output of the model


Steps to Build a Model in Sklearn

Step 1: Load Dataset

import pandas as pd data = pd.read_csv("data.csv")

Step 2: Separate Features and Target

X = data[["age","salary"]] # input y = data["purchased"] # output

Step 3: Split Data

train_test_split()

from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2 )

80% → training
20% → testing


Step 4: Choose Model

Example: Linear Regression

from sklearn.linear_model import LinearRegression model = LinearRegression()

Step 5: Train Model

model.fit(X_train, y_train)

Step 6: Make Prediction

pred = model.predict(X_test) print(pred)

Summary Table

LibraryPurpose
NumPyNumerical operations
PandasData handling
MatplotlibData visualization
SklearnMachine learning models

Comments

Popular posts from this blog

Unit - 1 Introduction to machine learning

Practical for IML