Practical - 2 Aim: Study of Various Machine Learning Libraries. (Scipy, Keras, Scikit-Learn, Pytorch, Tensorflow, Seaborn, Plotly)
Practical - 2 Aim: Study of Various Machine Learning Libraries. (Scipy, Keras, Scikit-Learn, Pytorch, Tensorflow, Seaborn, Plotly)
PRACTICAL - 2
Aim: Study of various Machine Learning libraries. [SciPy, Keras, SciKit-
Learn, PyTorch, TensorFlow, Seaborn,Plotly ].
Scipy:
SciPy is a collection of mathematical algorithms and convenience functions built on NumPy
. It adds significant power to Python by providing the user with high-level commands and
classes for manipulating and visualizing data.
image.png
from scipy import linalg, optimize, integrate
(1.6666666666666667, 1.8503717077085944e-14)
image.png
from scipy.integrate import dblquad
area = dblquad(lambda x, y: x*y, 0, 0.5, lambda x: 0, lambda x: 1-2*x)
area
(0.010416666666666668, 4.101620128472366e-16)
import numpy as np
from scipy.interpolate import CubicSpline, PchipInterpolator,
Akima1DInterpolator
x = np.array([1., 2., 3., 4., 4.5, 5., 6., 7., 8])
y = x**2
y[4] += 101
KERAS:
Keras is an open-source library that provides a Python interface for artificial neural
networks. Keras acts as an interface for the TensorFlow library. Designed to enable fast
experimentation with deep neural networks, Keras focuses on being user-friendly,
modular, and extensible.
import numpy as np
import os
os.environ["KERAS_BACKEND"] = "jax"
# Load the data and split it between train and test sets
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
#model parameters
num_classes = 10
input_shape = (28, 28, 1)
model = keras.Sequential(
[
keras.layers.Input(shape=input_shape),
keras.layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
keras.layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
keras.layers.MaxPooling2D(pool_size=(2, 2)),
keras.layers.Conv2D(128, kernel_size=(3, 3), activation="relu"),
keras.layers.Conv2D(128, kernel_size=(3, 3), activation="relu"),
keras.layers.GlobalAveragePooling2D(),
keras.layers.Dropout(0.5),
keras.layers.Dense(num_classes, activation="softmax"),
]
)
model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_4 (Conv2D) (None, 26, 26, 64) 640
=================================================================
Total params: 260298 (1016.79 KB)
Trainable params: 260298 (1016.79 KB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(),
optimizer=keras.optimizers.Adam(learning_rate=1e-3),
metrics=[
keras.metrics.SparseCategoricalAccuracy(name="acc"),
],
)
batch_size = 128
epochs = 2
callbacks = [
keras.callbacks.ModelCheckpoint(filepath="model_at_epoch_{epoch}.keras"),
keras.callbacks.EarlyStopping(monitor="val_loss", patience=2),
]
model.fit(
x_train,
y_train,
batch_size=batch_size,
epochs=epochs,
validation_split=0.15,
callbacks=callbacks,
)
score = model.evaluate(x_test, y_test, verbose=0)
Epoch 1/2
399/399 [==============================] - 298s 741ms/step - loss: 0.1371 -
acc: 0.9601 - val_loss: 0.0545 - val_acc: 0.9839
Epoch 2/2
399/399 [==============================] - 290s 727ms/step - loss: 0.1095 -
acc: 0.9681 - val_loss: 0.0444 - val_acc: 0.9888
model.save("final_model.keras")
model = keras.saving.load_model("final_model.keras")
predictions = model.predict(x_test)
predictions
SciKit-Learn:
Scikit-Learn is a machine learning library for the Python programming language. It has a
large number of algorithms that can be readily deployed by programmers and data
scientists in machine learning models. Built on NumPy, SciPy, and Matplotlib.
from sklearn import datasets
iris = datasets.load_iris()
digits = datasets.load_digits()
iris.data
print(digits.data)
digits.target
[[ 0. 0. 5. ... 0. 0. 0.]
[ 0. 0. 0. ... 10. 0. 0.]
[ 0. 0. 0. ... 16. 9. 0.]
...
[ 0. 0. 1. ... 6. 0. 0.]
[ 0. 0. 2. ... 12. 0. 0.]
[ 0. 0. 10. ... 12. 1. 0.]]
clf.fit(digits.data[:-1], digits.target[:-1])
SVC(C=100.0, gamma=0.001)
clf.predict(digits.data[-1:])
array([8])
IU2141230089 DSC(CE0630) 6CSE - B1
PyTorch:
PyTorch is a machine learning framework based on the Torch library, used for applications
such as computer vision and natural language processing, originally developed by Meta AI
and now part of the Linux Foundation umbrella. It is free and open-source software.
import torch
x = torch.rand(5, 3)
print(x)
torch.is_tensor(x)
True
a = torch.randn(4)
print(a)
torch.acos(a)
a = torch.randn(4)
print(f"a = {a}")
torch.add(a, 20)
b = torch.randn(4)
print(f"b = {b}")
c = torch.randn(4, 1)
print(f"c = {c}")
torch.add(b, c, alpha=10)
torch.arange(13).chunk(6)
(tensor([0, 1, 2]),
tensor([3, 4, 5]),
tensor([6, 7, 8]),
tensor([ 9, 10, 11]),
tensor([12]))
x = torch.randn(2, 3)
print(f"x = {x}")
torch.transpose(x, 0, 1)
tensor([[-1.4354, 0.4503],
[ 0.3738, 0.9296],
[-0.7075, -0.5431]])
Tensorflow:
TensorFlow is an end-to-end open source platform for machine learning. It has a
comprehensive, flexible ecosystem of tools, libraries, and community resources that lets
researchers push the state-of-the-art in ML, and gives developers the ability to easily build
and deploy ML-powered applications.
import tensorflow as tf
# Import seaborn
import seaborn as sns
# Create a visualization
sns.relplot(
data=tips,
x="total_bill", y="tip", col="time",
hue="smoker", style="smoker", size="size",
)
<seaborn.axisgrid.FacetGrid at 0x7b3d85e55120>
dots = sns.load_dataset("dots")
sns.relplot(
data=dots, kind="line",
x="time", y="firing_rate", col="align",
hue="choice", size="coherence", style="choice",
facet_kws=dict(sharex=False),
)
<seaborn.axisgrid.FacetGrid at 0x7b3d86febbb0>
IU2141230089 DSC(CE0630) 6CSE - B1
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="time")
g.map(sns.histplot, "tip")
<seaborn.axisgrid.FacetGrid at 0x7b3d89247cd0>
<seaborn.axisgrid.FacetGrid at 0x7b3d890ed570>
IU2141230089 DSC(CE0630) 6CSE - B1
Plotly:
The plotly Python library is an interactive, open-source plotting library that supports over
40 unique chart types covering a wide range of statistical, financial, geographic, scientific,
and 3-dimensional use-cases.
Built on top of the Plotly JavaScript library (plotly.js), plotly enables Python users to create
beautiful interactive web-based visualizations that can be displayed in Jupyter notebooks,
saved to standalone HTML files, or served as part of pure Python-built web applications
using Dash. The plotly Python library is sometimes referred to as "plotly.py" to differentiate
it from the JavaScript library.
import plotly.express as px
fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])
fig.show()
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
size='petal_length', hover_data=['petal_width'])
fig.show()
IU2141230089 DSC(CE0630) 6CSE - B1
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker",
facet_col="sex", facet_row="time")
fig.show()
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")
fig.show()