Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
35 views64 pages

Tensorflow Lab Manual

TensorFlow is an open-source machine learning and deep learning framework developed by Google, released in 2015, that facilitates numerical computation and data flow for various applications such as image recognition and natural language processing. It operates using tensors and graphs to manage data flow and computations, and offers advantages like multi-CPU/GPU support and a large community. The document also outlines installation methods for TensorFlow on Windows, including using pip, Anaconda, and Jupyter Notebook, along with basic usage examples.

Uploaded by

haritha bwec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views64 pages

Tensorflow Lab Manual

TensorFlow is an open-source machine learning and deep learning framework developed by Google, released in 2015, that facilitates numerical computation and data flow for various applications such as image recognition and natural language processing. It operates using tensors and graphs to manage data flow and computations, and offers advantages like multi-CPU/GPU support and a large community. The document also outlines installation methods for TensorFlow on Windows, including using pip, Anaconda, and Jupyter Notebook, along with basic usage examples.

Uploaded by

haritha bwec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

TENSORFLOW

1. Introduction of Tensor flow


What is TensorFlow?

TensorFlow is a popular framework of machine learning and deep learning. It is a


free and open-source library which is released on 9 November 2015 and developed
by Google Brain Team. It is entirely based on Python programming language and use for
numerical computation and data flow, which makes machine learning faster and easier.

TensorFlow can train and run the deep neural networks for image recognition, handwritten
digit classification, recurrent neural network, word embedding, natural language
processing, video detection, and many more. TensorFlow is run on multiple CPUs or GPUs
and also mobile operating systems.

The word TensorFlow is made by two words, i.e., Tensor and Flow

1. Tensor is a multidimensional array


2. Flow is used to define the flow of data in operation.

TensorFlow is used to define the flow of data in operation on a multidimensional array or


Tensor.

History of TensorFlow

Many years ago, deep learning started to exceed all other machine learning algorithms when
giving extensive data. Google has seen it could use these deep neural networks to upgrade its
services:

o Google search engine


o Gmail
o Photo

BAPATLA WOMEN’S ENGINEERING COLLEGE 1


TENSORFLOW

They build a framework called TensorFlow to permit researchers and developers to work
together in an AI model. Once it approved and scaled, it allows lots of people to use it.

It was first released in 2015, while the first stable version was coming in 2017. It is an open-
source platform under Apache Open Source License. We can use it, modify it, and reorganize
the revised version for free without paying anything to Google.

Components of TensorFlow

1.Tensor

The name TensorFlow is derived from its core framework, "Tensor." A tensor is a vector or a
matrix of n-dimensional that represents all type of data. All values in a tensor hold similar
data type with a known shape. The shape of the data is the dimension of the matrix or an
array.

A tensor can be generated from the input data or the result of a computation. In
TensorFlow, all operations are conducted inside a graph. The group is a set of calculation that
takes place successively. Each transaction is called an op node are connected.

2.Graphs

TensorFlow makes use of a graph framework. The


chart gathers and describes all the computations done
during the training.

Advantages

o It was fixed to run on multiple CPUs or GPUs


and mobile operating systems.
o The portability of the graph allows to conserve
the computations for current or later use. The
graph can be saved because it can be executed
in the future.
o All the computation in the graph is done by connecting tensors together.

3.Session

A session can execute the operation from the graph. To feed the graph with the value of a
tensor, we need to open a session. Inside a session, we must run an operator to create an
output.

Why is TensorFlow popular?

TensorFlow is the better library for all because it is accessible to everyone. TensorFlow
library integrates different API to create a scale deep learning architecture like CNN
(Convolutional Neural Network) or RNN (Recurrent Neural Network).
BAPATLA WOMEN’S ENGINEERING COLLEGE 2
TENSORFLOW

TensorFlow is based on graph computation; it can allow the developer to create the
construction of the neural network with Tensorboard. This tool helps debug our program. It
runs on CPU (Central Processing Unit) and GPU (Graphical Processing Unit).

TensorFlow attracts the most considerable popularity on GitHub compare to the other deep
learning framework.

Use Cases/Applications of TensorFlow

TensorFlow provides amazing functionalities and services when compared to other popular
deep learning frameworks. TensorFlow is used to create a large-scale neural network with
many layers.

BAPATLA WOMEN’S ENGINEERING COLLEGE 3


TENSORFLOW

It is mainly used for deep learning or machine learning problems such


as Classification, Perception, Understanding, Discovering Prediction, and Creation.

1. Voice/Sound Recognition

Voice and sound recognition applications are the most-known use cases of deep-learning. If
the neural networks have proper input data feed, neural networks are capable of
understanding audio signals.

For example:

Voice recognition is used in the Internet of Things, automotive, security, and UX/UI.

Sentiment Analysis is mostly used in customer relationship management (CRM).

Flaw Detection (engine noise) is mostly used in automotive and Aviation.

Voice search is mostly used in customer relationship management (CRM)

2. Image Recognition

Image recognition is the first application that made deep learning and machine learning
popular. Telecom, Social Media, and handset manufacturers mostly use image recognition. It
is also used for face recognition, image search, motion detection, machine vision, and photo
clustering.

BAPATLA WOMEN’S ENGINEERING COLLEGE 4


TENSORFLOW

For example, image recognition is used to recognize and identify people and objects in from
of images. Image recognition is used to understand the context and content of any image.

For object recognition, TensorFlow helps to classify and identify arbitrary objects within
larger images.

This is also used in engineering application to identify shape for modeling purpose
(3d reconstruction from 2d image) and by Facebook for photo tagging.

For example, deep learning uses TensorFlow for analyzing thousands of photos of cats. So a
deep learning algorithm can learn to identify a cat because this algorithm is used to find
general features of objects, animals, or people.

3. Time Series

Deep learning is using Time Series algorithms for examining the time series data to extract
meaningful statistics. For example, it has used the time series to predict the stock market.

A recommendation is the most common use case for Time


Series. Amazon, Google, Facebook, and Netflix are using deep learning for the suggestion.
So, the deep learning algorithm is used to analyze customer activity and compare it to
millions of other users to determine what the customer may like to purchase or watch.

For example, it can be used to recommend us TV shows or movies that people like based on
TV shows or movies we already watched.

4. Video Detection

The deep learning algorithm is used for video detection. It is used for motion detection, real-
time threat detection in gaming, security, airports, and UI/UX field.

For example, NASA is developing a deep learning network for object clustering of asteroids
and orbit classification. So, it can classify and predict NEOs (Near Earth Objects).

5. Text-Based Applications

Text-based application is also a popular deep learning algorithm. Sentimental analysis, social
media, threat detection, and fraud detection, are the example of Text-based applications.

For example, Google Translate supports over 100 languages.

Some companies who are currently using TensorFlow are Google, AirBnb, eBay, Intel,
DropBox, Deep Mind, Airbus, CEVA, Snapchat, SAP, Uber, Twitter, Coca-Cola, and IBM.

Features of TensorFlow

TensorFlow has an interactive multiplatform programming interface which is scalable and


reliable compared to other deep learning libraries which are available.

These features of TensorFlow will tell us about the popularity of TensorFlow.

BAPATLA WOMEN’S ENGINEERING COLLEGE 5


TENSORFLOW

1. Responsive Construct

We can visualize each part of the graph, which is not an option while
using Numpy or SciKit. To develop a deep learning application, firstly, there are two or three
components that are required to create a deep learning application and need a programming
language.

2. Flexible

It is one of the essential TensorFlow Features according to its operability. It has modularity
and parts of it which we want to make standalone.

3. Easily Trainable

It is easily trainable on CPU and for GPU in distributed computing.

4. Parallel Neural Network Training

TensorFlow offers to the pipeline in the sense that we can train multiple neural networks and
various GPUs, which makes the models very efficient on large-scale systems.

BAPATLA WOMEN’S ENGINEERING COLLEGE 6


TENSORFLOW

5. Large Community

Google has developed it, and there already is a large team of software engineers who work on
stability improvements continuously.

6. Open Source

The best thing about the machine learning library is that it is open source so anyone can use it
as much as they have internet connectivity. So, people can manipulate the library and come
up with a fantastic variety of useful products. And it has become another DIY community
which has a massive forum for people getting started with it and those who find it hard to use
it.

7. Feature Columns

TensorFlow has feature columns which could be thought of as intermediates between raw
data and estimators; accordingly, bridging input data with our model.

The feature below describes how the feature column is implemented.

BAPATLA WOMEN’S ENGINEERING COLLEGE 7


TENSORFLOW

8. Availability of Statistical Distributions

This library provides distributions functions including Bernoulli, Beta, Chi2, Uniform,
Gamma, which are essential, especially where considering probabilistic approaches such as
Bayesian models.

9. Layered Components

TensorFlow produces layered operations of weight and biases from the function such as
tf.contrib.layers and also provides batch normalization, convolution layer, and dropout layer.
So tf.contrib.layers.optimizers have optimizers such as Adagrad, SGD, Momentum which
are often used to solve optimization problems for numerical analysis.

10. Visualizer (With TensorBoard)

We can inspect a different representation of a model and make the changed necessary while
debugging it with the help of TensorBoard.

11.Event Logger (With TensorBoard)

It is just like UNIX, where we use tail - f to monitor the output of tasks at the cmd. It checks,
logging events and summaries from the graph and production with the TensorBoard.

BAPATLA WOMEN’S ENGINEERING COLLEGE 8


TENSORFLOW

2.Installation of TensorFlow
In this tutorial, we will describe that how to install TensorFlow in Windows
10.

We can download TensorFlow in our system in 3 ways:

1. Through pip (Python package library)


2. Through Anaconda Navigator (conda)
3. Through jupyter notebook

1. Installation of Tensorflow Through pip


So, firstly we have to install and set-up anaconda in our system through
pip.

The following are the requirement for TensorFlow to work on our


computer.

o TensorFlow has only supported 64-bit Python 3.5.x or


Python 3.6.x on Windows
o When we download the Python 3.5.x version, it comes with
the pip3 package manager. (Which is the program that we are
going to need for our users to install TensorFlow on Windows).

Step 1: Download Python from the below


link: https://www.python.org/downloads/release/python-352/

BAPATLA WOMEN’S ENGINEERING COLLEGE 9


TENSORFLOW

Step 3: We will be brought to another page, where we will need to select


either the x86-64 or amd64 installer to install Python.

We use here Windows x86-64 executable installer.

BAPATLA WOMEN’S ENGINEERING COLLEGE 10


TENSORFLOW

Now, Python is installing successfully.

Step 4: For this tutorial, I'll be choosing to Add Python 3.5 to PATH.

BAPATLA WOMEN’S ENGINEERING COLLEGE 11


TENSORFLOW

Step 5: Now, we will be able to see the message "Set-up was


successful." A way to confirm that it hs installed successfully is to open
your Command Prompt and check the version.

What is pip?
pip is known as a package management system which is used to
install and manage the software package, which is written in Python or
any other languages. pip is used to download, search, install, uninstall,
and manage the 3rd party python package. (pip3 is the latest version of it
which comes with new Python 3.5.x version that we had just downloaded)

Installing our TensorFlow


Once we have downloaded the latest version of Python, we can now put
our finishing touches by installing our TensorFlow.

Step 1: To install TensorFlow, start the terminal. Make sure that we run
the cmd as an administrator.

If we do not know how to run your cmd as an administrator

Here's how we can run in our cmd as an administrator.

Open the Start menu, search for cmd, and then right-click on it and Run
as an administrator.

BAPATLA WOMEN’S ENGINEERING COLLEGE 12


TENSORFLOW

Step 2: Once we are done with that, then we have to write the command
in command prompt for finish installing Tensorflow in our Windows.

Enter this command:

1. C:\pip3 install -upgrade tensorflow

BAPATLA WOMEN’S ENGINEERING COLLEGE 13


TENSORFLOW

Now, TensorFlow is successfully installed in our system.

BAPATLA WOMEN’S ENGINEERING COLLEGE 14


TENSORFLOW

Testing our TensorFlow


Here, we try and prove whether our new TensorFlow works smoothly
without any problems.

Below is an example that you can write to the test.

TensorFlow is successfully working now.

BAPATLA WOMEN’S ENGINEERING COLLEGE 15


TENSORFLOW

2. Installation of TensorFlow through conda


In our previous tutorial of TensorFlow, we learn how to install TensorFlow
through pip. In this tutorial, we understand that how to install TensorFlow
through Conda. Here, we need anaconda Navigator to set-up the platform.

These are the following steps which are given below:

Firstly, we have to open the official site of Anaconda and download


Anaconda from the below link: https://www.anaconda.com/distribution/

After that, we have to download Anaconda from below highlighted Python


2.7 version.

BAPATLA WOMEN’S ENGINEERING COLLEGE 16


TENSORFLOW

It will successfully be downloaded in our system. After that, we have to


install Anaconda in our system.

Click on "Next."

BAPATLA WOMEN’S ENGINEERING COLLEGE 17


TENSORFLOW

Click on "I Agree."

Again click on "Next."

BAPATLA WOMEN’S ENGINEERING COLLEGE 18


TENSORFLOW

Click on "Next" again.

Click on "Install."

BAPATLA WOMEN’S ENGINEERING COLLEGE 19


TENSORFLOW

Click on "Next."

Click on "Next."

BAPATLA WOMEN’S ENGINEERING COLLEGE 20


TENSORFLOW

Click on "Next."

After clicking on "finish."

It will successfully installed in our system.

BAPATLA WOMEN’S ENGINEERING COLLEGE 21


TENSORFLOW

After that, we have to run the given command to set-up the TensorFlow
and libraries.
1. Conda create -n tensorflow pip python

Here, we are downloading and installing the essential things which are
used in TensorFlow to work.

BAPATLA WOMEN’S ENGINEERING COLLEGE 22


TENSORFLOW

After that, we have to check that TensorFlow is working or not in our


system.

3. Installation of TensorFlow through jupyter Notebook:

After successful installation of tensorflow in anaconda,we can use in jupyter notebook.

For installation of tensorflow in jyputer notebook give the following commands:

pip install tensorflow

after successful installation,give the command

import tensorflow as tf

then we implement tensorflow programs in jupyter notebook.

BAPATLA WOMEN’S ENGINEERING COLLEGE 23


TENSORFLOW

3.Basics of Tensorflow
In[1]:

import tensorflow as tf

# Check if eager execution is enabled


print(tf.executing_eagerly())
true

In[2]:

import tensorflow as tf

# Define a simple computation


a = tf.constant(2)
b = tf.constant(3)
c = tf.add(a, b)

# Directly execute the computation


result = c.numpy()

print("Result:", result)
5

In[3]:

import tensorflow as tf

# Create a TensorFlow session


with tf.compat.v1.Session() as sess:
# Your TensorFlow operations go here
pass
In[4]:

import tensorflow as tf

# Enable eager execution (enabled by default in TensorFlow 2.x)


tf.compat.v1.disable_eager_execution()

# Define a simple computation


a = tf.constant(2)
b = tf.constant(3)
c = tf.add(a, b)

# Create a TensorFlow session


with tf.compat.v1.Session() as sess:
# Run the computation graph by executing the session
result = sess.run(c)
print("Result:", result)
Result: 5

BAPATLA WOMEN’S ENGINEERING COLLEGE 24


TENSORFLOW

In[5]:

# importing tensorflow
import tensorflow as tf

# creating nodes in computation graph


node1 = tf.constant(3, dtype=tf.int32)
node2 = tf.constant(5, dtype=tf.int32)
node3 = tf.add(node1, node2)

# create tensorflow session object


sess = tf.compat.v1.Session()

# evaluating node3 and printing the result


print("sum of node1 and node2 is :",sess.run(node3))
# closing the session
sess.close()
Sum of node1 and node2 is : 8

In[6]:

tf.compat.v1.Session(
target='', graph=None, config=None
)
<tensorflow.python.client.session.Session at 0x1bc3daf37d0>
In[7]:

tf.compat.v1.disable_eager_execution() # need to disable eager in TF2.x


# Build a graph.
a = tf.constant(5.0)
b = tf.constant(6.0)
c=a*b
# Launch the graph in a session.
sess = tf.compat.v1.Session()
# Evaluate the tensor `c`.
print(sess.run(c)) # prints 30.0
30.0
In[8]:

# Launch the graph in a session that allows soft device placement and
# logs the placement decisions.
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(
allow_soft_placement=True,
log_device_placement=True))
Device mapping: no known devices.
In[9]:

devices = sess.list_devices()
for d in devices:
print(d.name)
/job:localhost/replica:0/task:0/device:CPU:0

BAPATLA WOMEN’S ENGINEERING COLLEGE 25


TENSORFLOW

In[10]:

import tensorflow as tf

# Assuming you have a list of sentences called 'text_corpus'


text_corpus = ["This is a sample sentence.", "Another sentence for example."]

# Create a Tokenizer object


tokenizer = tf.keras.preprocessing.text.Tokenizer()

# Fit the Tokenizer on your text corpus to build the vocabulary


tokenizer.fit_on_texts(text_corpus)

# Get the vocab_size (total number of unique words in the corpus)


vocab_size = len(tokenizer.word_index) + 1 # Adding 1 for the reserved index 0

print("Vocabulary Size:", vocab_size)


Vocabulary Size: 9
In[11]:

import tensorflow as tf

vocab_size = 10000 # Example vocabulary size


embedding_dim = 100 # Example embedding dimension
max_sequence_length = 100 # Example maximum sequence length

model = tf.keras.Sequential([
tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim,
input_length=max_sequence_length),
# Other layers of your model...
])

In[12]:

import tensorflow as tf

# Check TensorFlow version


print(tf.__version__)

# Simple TensorFlow program


a = tf.constant(2)
b = tf.constant(3)
c=a+b

# Start a TensorFlow session and run the computation


with tf.compat.v1.Session() as sess:
result = sess.run(c)
print("Result:", result)
2.12.0 Result: 5

BAPATLA WOMEN’S ENGINEERING COLLEGE 26


TENSORFLOW

4. Load a dataset
In[1]:

Pip install tensorflow_datasets

Requirement already satisfied: tensorflow_datasets in c:\users\91970\appdata\local\programs\


python\python311\lib\site-packages (4.9.2)
Requirement already satisfied: absl-py in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (1.4.0)
Requirement already satisfied: array-record in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (0.4.0)
Requirement already satisfied: click in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (8.1.3)
Requirement already satisfied: dm-tree in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (0.1.8)
Requirement already satisfied: etils[enp,epath]>=0.9.0 in c:\users\91970\appdata\local\
programs\python\python311\lib\site-packages (from tensorflow_datasets) (1.3.0)
Requirement already satisfied: numpy in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (1.23.5)
Requirement already satisfied: promise in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (2.3)
Requirement already satisfied: protobuf>=3.20 in c:\users\91970\appdata\local\programs\
python\python311\lib\site-packages (from tensorflow_datasets) (4.23.3)
Requirement already satisfied: psutil in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (5.9.5)
Requirement already satisfied: requests>=2.19.0 in c:\users\91970\appdata\local\programs\
python\python311\lib\site-packages (from tensorflow_datasets) (2.31.0)
Requirement already satisfied: tensorflow-metadata in c:\users\91970\appdata\local\
programs\python\python311\lib\site-packages (from tensorflow_datasets) (1.13.1)
Requirement already satisfied: termcolor in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (2.3.0)
Requirement already satisfied: toml in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (0.10.2)
Requirement already satisfied: tqdm in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (4.65.0)
Requirement already satisfied: wrapt in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from tensorflow_datasets) (1.14.1)
Requirement already satisfied: importlib_resources in c:\users\91970\appdata\local\programs\
python\python311\lib\site-packages (from etils[enp,epath]>=0.9.0->tensorflow_datasets)
(5.12.0)
Requirement already satisfied: typing_extensions in c:\users\91970\appdata\local\programs\
python\python311\lib\site-packages (from etils[enp,epath]>=0.9.0->tensorflow_datasets)
(4.6.3)
Requirement already satisfied: zipp in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from etils[enp,epath]>=0.9.0->tensorflow_datasets) (3.15.0)
Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\91970\appdata\local\
programs\python\python311\lib\site-packages (from requests>=2.19.0->tensorflow_datasets)
(3.1.0)
Requirement already satisfied: idna<4,>=2.5 in c:\users\91970\appdata\local\programs\
python\python311\lib\site-packages (from requests>=2.19.0->tensorflow_datasets) (3.4)
BAPATLA WOMEN’S ENGINEERING COLLEGE 27
TENSORFLOW

Requirement already satisfied: urllib3<3,>=1.21.1 in c:\users\91970\appdata\local\programs\


python\python311\lib\site-packages (from requests>=2.19.0->tensorflow_datasets) (1.26.16)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\91970\appdata\local\programs\
python\python311\lib\site-packages (from requests>=2.19.0->tensorflow_datasets) (2023.5.7)
Requirement already satisfied: colorama in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from click->tensorflow_datasets) (0.4.6)
Requirement already satisfied: six in c:\users\91970\appdata\local\programs\python\
python311\lib\site-packages (from promise->tensorflow_datasets) (1.16.0)
Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in c:\users\91970\
appdata\local\programs\python\python311\lib\site-packages (from tensorflow-metadata-
>tensorflow_datasets) (1.59.1)
Note: you may need to restart the kernel to use updated packages.
In[2]:

import tensorflow as tf
import tensorflow_datasets as tfds
import pandas as pd
tfds.list_builders()
ds=tfds.load('mnist',split='train',shuffle_files=True)
assert isinstance(ds,tf.data.Dataset)
print(ds)

<_PrefetchDataset element_spec={'image': TensorSpec(shape=(28, 28, 1), dtype=tf.uint8,


name=None), 'label': TensorSpec(shape=(), dtype=tf.int64, name=None)}>

BAPATLA WOMEN’S ENGINEERING COLLEGE 28


TENSORFLOW

5. Build a machine learning model


AIM: Build a machine learning model

2D MODEL:

SOURCE CODE:

# Import necessary libraries


from sklearn.datasets import make_circles
import matplotlib.pyplot as plt

# Generate 2d classification dataset


X, y = make_circles(n_samples=200, shuffle=True,
noise=0.1, random_state=42)
# Plot the generated datasets
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.show()

OUTPUT:

BAPATLA WOMEN’S ENGINEERING COLLEGE 29


TENSORFLOW

3D MODEL:

SOURCE CODE:

import matplotlib.pyplot as plt


from mpl_toolkits.mplot3d import Axes3D

def visualize_3d(X, y):


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X['x'], X['y'], X['z'], c=y)
plt.show()

# Now you can call the visualize_3d function


X1 = pd.DataFrame(X1, columns=['x', 'y', 'z'])
y1 = pd.Series(y1)
visualize_3d(X1, y1)

OUTPUT:

BAPATLA WOMEN’S ENGINEERING COLLEGE 30


TENSORFLOW

2D & 3D MODEL:

SOURCE CODE:

import matplotlib.pyplot as plt


import seaborn as sns
from sklearn.datasets import make_classification
import pandas as pd

# Generate synthetic data


X, y = make_classification(n_samples=10000, n_features=2, n_informative=2,
n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=1, class_sep=2, flip_y=0.2,
weights=[0.5, 0.5], random_state=17)

f, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(20, 8))

# Use sns.scatterplot with the data parameter and column names for x and y
sns.scatterplot(data=pd.DataFrame({'X0': X[:, 0], 'X1': X[:, 1], 'y': y}), x='X0', y='X1',
hue='y', ax=ax1)
ax1.set_title("No Noise")

# Continue with your code here...

# Create another scatterplot for the noisy data


sns.scatterplot(data=pd.DataFrame({'X0': X[:, 0], 'X1': X[:, 1], 'y': y}), x='X0', y='X1',
hue='y', ax=ax2)
ax2.set_title("With Noise")

plt.show()

OUTPUT:

BAPATLA WOMEN’S ENGINEERING COLLEGE 31


TENSORFLOW

import matplotlib.pyplot as plt


from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import numpy as np

def visualize_3d(X, y):


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Create a colormap for coloring the points based on 'y'


cmap = plt.get_cmap('viridis') # You can choose a different colormap

# Normalize 'y' values to use them as colors


norm = plt.Normalize(y.min(), y.max())

# Scatter plot with colors based on 'y'


sc = ax.scatter(X['x'], X['y'], X['z'], c=y, cmap=cmap, norm=norm)

# Add color bar for reference


cb = plt.colorbar(sc)
cb.set_label('Label Value')

plt.show()

# Example data (replace with your actual data)


X1 = pd.DataFrame({'x': np.random.rand(100), 'y': np.random.rand(100), 'z': np.random.rand(100)})
y1 = np.random.randint(0, 2, size=100)

# Create DataFrames
X = pd.DataFrame(X1, columns=['x', 'y', 'z'])
y = pd.Series(y1)

# Now you can call the visualize_3d function


visualize_3d(X, y)
SOURCE CODE:

OUTPUT:

BAPATLA WOMEN’S ENGINEERING COLLEGE 32


TENSORFLOW

6. Detecting spam usting Tensorflow.


Detecting spam messages wing Tensorflow on Kaggle typically involves some coding or
Script execution,

Kaggle es a Primarily competitions and to use Tensorflow or any other machine learning! a
platform for datascience and machine learning you generally need to write code or use pre-
existing code scripts. 30- Prameute

However, you are looking for a more wer-friendly way to Perform spam detection without
writing code, you can expore kaggle's "Kernels feature, Kaggle kernels allocos you for Tun
code scripts shared by others without writing code yourself, as so long as some one has
created and shared a Kernel for the specific task you want to accomplish.

Here are the woogle general steps to perform spam detection using TensorFlow on Kaggle:
have a kaggle account, Sign up fo

1. Login to kaggle: If you don't one your need an account to aready access kaggle's resources.

2. find a Dataset: Search for a Dataset on kaggle that contains text message abelled as spam
or not spam Cham). you can use kaggle's dataset Search feature to find relevant data sets.

3. Create a kaggle Notebook:

• Go to Kaggle and click on "Notebooks" in the top menu.

• click on "New Notebook" to create ar nelo Notebook.

• choose a python crufɣonment (e.g.., Tensorflow) for your Notebook.

4. Load and explore the Dataset In your kaggle notebook, you can use Python code to load
and explore the data.

for example:

Python

import pandas as ed data = fd Yead. csv C'path_to-your- dataset.csv')

5. Data preprocessing:

- Preprocess the text data by clearing and to Renizing it. you may need to remove
punctuation, convert text to lowercase, and tokenize the tex words or subwords.

6 Data splitting:

-split your dataset into your training, validation and test sets. This is import -ant for Elarining
and evaluating your machine learning model.

7. Text vectorization:

BAPATLA WOMEN’S ENGINEERING COLLEGE 33


TENSORFLOW

convert the text data into numerical format wing techniques like TP-DDF (Term Requency-
Inverse Document Frequency) or woord embedding like word 2 Vec by Glove.

8. Build a spam Detection model!

Create a TensorFloco model for spam detection. you can use various architectures such as
Recurrent Neural Network (RNNs), convolution Neural Network

(CNNs) or Transformer Models. -ation metrics. Define the model layers, compile it, and set
up evalu

9. Training:

•Train your Tensorflow model on the Training uting validation data to avoid overfitting. 10-
Evaluation: data. Monitor training performance

-Evaluate the model's performance on the test dataset. common metrics for text classification
tasks include accuracy, precision, recall, and fi-score

11. Turing and optimization:

-Experiment with different model architectures, hyper parameters, and preprocessing


techniques to optimize your spam detection model.

12. Deployment:

-If you want to use the ad trofined model for real-word Spam detection, you can deploy it as a
web service or integrate it into your application. Kaggle provid resources for deploying
models, or you can explore other deployment platforms like Flask or Tensorflow serving.

13. Share your work?

-If you've achieved good results, consider sharing your kaggle notebook with the community
to help others learn and improve their spam detection models.

KAGGLE DATASET LINK:

https://www.kaggle.com/code/akanksha496/spam-detection-using-tensorflow/input

In[1]:

import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences

BAPATLA WOMEN’S ENGINEERING COLLEGE 34


TENSORFLOW

In[2]:

data = pd.read_csv('C:/Users/91970/Documents/MAHE/OneDrive/Desktop/SPAM text


message 20170820 - Data.csv')

In[3]:

data.head()

Category Message

0 ham Go until jurong point, crazy.. Available only ...

1 ham Ok lar... Joking wif u oni...

2 spam Free entry in 2 a wkly comp to win FA Cup fina...

3 ham U dun say so early hor... U c already then say...

4 ham Nah I don't think he goes to usf, he lives aro..


In[4]:

data.groupby('Category').describe().T

In[5]:

import seaborn as sns


import matplotlib.pyplot as plt

plt.figure(figsize=(12, 14))
sns.countplot(data=data, x='Category')
plt.show()

BAPATLA WOMEN’S ENGINEERING COLLEGE 35


TENSORFLOW

In[6]:

ham_msg = data[data.Category =='ham']


spam_msg = data[data.Category=='spam']

In[7]:

#randomly taking data from ham_ msg


ham_msg=ham_msg.sample(n=len(spam_msg),random_state=42)

In[8]:

print(ham_msg.shape,spam_msg.shape)
(747, 2) (747, 2)

In[9]:

# Assuming you have two DataFrames, ham_msg and spam_msg

# Concatenate the DataFrames vertically


balanced_data = pd.concat([ham_msg, spam_msg]).reset_index(drop=True)

# Create the count plot


plt.figure(figsize=(8, 6))
sns.countplot(data=balanced_data, x='Category')
BAPATLA WOMEN’S ENGINEERING COLLEGE 36
TENSORFLOW

plt.title('Distribution of ham and spam email messages (after downsampling)')


plt.show()

In[10]:

balanced_data.head()

In[11]:

balanced_data['label']=balanced_data['Category'].map({'ham':0,'spam':1})
In[12]:

train_msg, test_msg, train_labels,


test_labels=train_test_split(balanced_data['Message'],balanced_data['label'],test_size=0.2,ran
dom_state=434)
In[13]:

vocab_size=500
oov_tok='<OOV>'
max_len=50
BAPATLA WOMEN’S ENGINEERING COLLEGE 37
TENSORFLOW

In[14]:

#preprocessing making tokens out of text


token=Tokenizer(num_words=vocab_size,oov_token=oov_tok)
token.fit_on_texts(train_msg)
In[15]:

word_index=token.word_index
word_index
{'<OOV>': 1,
'to': 2,
'you': 3,
'a': 4,
'i': 5,
'call': 6,
'the': 7,
'your': 8,
'u': 9,
'for': 10,
'2': 11,
'and': 12,
'is': 13,
'now': 14,
'free': 15,
'or': 16,
'in': 17,
'on': 18,
'have': 19,
'ur': 20,
'of': 21,
'txt': 22,
'4': 23,
'me': 24,
'are': 25,
'with': 26,
'from': 27,
'text': 28,
'this': 29,
'my': 30,
'get': 31,
'stop': 32,
'mobile': 33,
'just': 34,
'no': 35,
'it': 36,
'will': 37,
'reply': 38,
'only': 39,
'be': 40,
'that': 41,
'claim': 42,
'www': 43,
'not': 44,
'out': 45,
BAPATLA WOMEN’S ENGINEERING COLLEGE 38
TENSORFLOW

'do': 46,
'send': 47,
'new': 48,
'so': 49,
'our': 50,
'we': 51,
'but': 52,
'at': 53,
'prize': 54,
'can': 55,
'cash': 56,
'all': 57,
'if': 58,
"i'm": 59,
'who': 60,
'150p': 61,
'uk': 62,
'go': 63,
'1': 64,
'nokia': 65,
'please': 66,
'win': 67,
't': 68,
'tone': 69,
'won': 70,
'week': 71,
'com': 72,
'msg': 73,
'50': 74,
'was': 75,
'day': 76,
'up': 77,
'phone': 78,
'by': 79,
'been': 80,
'what': 81,
'want': 82,
'service': 83,
'know': 84,
'urgent': 85,
'lt': 86,
'gt': 87,
'contact': 88,
'when': 89,
'co': 90,
'has': 91,
'18': 92,
'16': 93,
'min': 94,
'message': 95,
'r': 96,
'customer': 97,
'good': 98,
'per': 99,
'how': 100,
'guaranteed': 101,
'time': 102,
BAPATLA WOMEN’S ENGINEERING COLLEGE 39
TENSORFLOW

'as': 103,
'love': 104,
'like': 105,
'then': 106,
'line': 107,
'c': 108,
'any': 109,
'cs': 110,
'number': 111,
'3': 112,
'find': 113,
'chat': 114,
'back': 115,
'got': 116,
'draw': 117,
'its': 118,
'am': 119,
'awarded': 120,
'ü': 121,
'camera': 122,
'today': 123,
'dont': 124,
"don't": 125,
'ok': 126,
'more': 127,
'every': 128,
'need': 129,
'sorry': 130,
'£1': 131,
'there': 132,
'£1000': 133,
'about': 134,
'mins': 135,
'wk': 136,
'had': 137,
'great': 138,
'hi': 139,
'receive': 140,
"i'll": 141,
'pls': 142,
'sms': 143,
'holiday': 144,
'po': 145,
'latest': 146,
'tell': 147,
'n': 148,
'rate': 149,
'yes': 150,
'see': 151,
'they': 152,
'video': 153,
'box': 154,
'hey': 155,
'come': 156,
'chance': 157,
'shows': 158,
'dear': 159,
BAPATLA WOMEN’S ENGINEERING COLLEGE 40
TENSORFLOW

'apply': 160,
'thanks': 161,
'award': 162,
'150ppm': 163,
'landline': 164,
'tones': 165,
'an': 166,
's': 167,
'code': 168,
'1st': 169,
'still': 170,
'live': 171,
'special': 172,
'network': 173,
'ringtone': 174,
'make': 175,
'give': 176,
'orange': 177,
'take': 178,
'e': 179,
'b': 180,
'selected': 181,
'collect': 182,
'next': 183,
'miss': 184,
'da': 185,
'weekly': 186,
'best': 187,
'cost': 188,
'500': 189,
'£100': 190,
'valid': 191,
'music': 192,
'mob': 193,
'10p': 194,
'play': 195,
'offer': 196,
'name': 197,
'over': 198,
'her': 199,
'entry': 200,
'hope': 201,
'life': 202,
'one': 203,
'8007': 204,
'national': 205,
'going': 206,
'last': 207,
'some': 208,
'home': 209,
"it's": 210,
'collection': 211,
'well': 212,
'he': 213,
'vouchers': 214,
'd': 215,
'000': 216,
BAPATLA WOMEN’S ENGINEERING COLLEGE 41
TENSORFLOW

'later': 217,
'think': 218,
'why': 219,
'real': 220,
'texts': 221,
'end': 222,
'oh': 223,
'where': 224,
'games': 225,
'club': 226,
'trying': 227,
'£500': 228,
'help': 229,
'work': 230,
'lor': 231,
'http': 232,
'tomorrow': 233,
'poly': 234,
'5': 235,
'should': 236,
'after': 237,
'delivery': 238,
'10': 239,
'86688': 240,
'happy': 241,
'join': 242,
'night': 243,
'todays': 244,
'price': 245,
'waiting': 246,
'someone': 247,
'sae': 248,
'word': 249,
'update': 250,
'morning': 251,
"c's": 252,
'im': 253,
'bonus': 254,
'keep': 255,
'land': 256,
'gift': 257,
'bt': 258,
'x': 259,
'g': 260,
'guess': 261,
'enjoy': 262,
'sent': 263,
'£2000': 264,
'speak': 265,
'opt': 266,
'she': 267,
'voucher': 268,
'dating': 269,
'6': 270,
'await': 271,
'double': 272,
'colour': 273,
BAPATLA WOMEN’S ENGINEERING COLLEGE 42
TENSORFLOW

'£3': 274,
'sexy': 275,
'operator': 276,
'£5000': 277,
'100': 278,
'services': 279,
'7': 280,
'friend': 281,
'first': 282,
'top': 283,
'12hrs': 284,
'xmas': 285,
'k': 286,
'750': 287,
'use': 288,
'yours': 289,
'here': 290,
'attempt': 291,
'which': 292,
'babe': 293,
'cos': 294,
'mobileupd8': 295,
'hot': 296,
'being': 297,
'let': 298,
'quiz': 299,
"can't": 300,
'08000930705': 301,
'account': 302,
'order': 303,
'private': 304,
'much': 305,
'soon': 306,
'content': 307,
'part': 308,
'£350': 309,
'half': 310,
'unsubscribe': 311,
'talk': 312,
'wat': 313,
'ltd': 314,
'fun': 315,
'tried': 316,
'way': 317,
'row': 318,
'friends': 319,
'could': 320,
'pic': 321,
'2nd': 322,
'days': 323,
'gud': 324,
'£250': 325,
'off': 326,
'doing': 327,
'hello': 328,
'ask': 329,
'camcorder': 330,
BAPATLA WOMEN’S ENGINEERING COLLEGE 43
TENSORFLOW

'charged': 331,

'meet': 332,
'yeah': 333,
'm': 334,
'worth': 335,
'too': 336,
'us': 337,
'congratulations': 338,
'wkly': 339,
'87066': 340,
'them': 341,
'reveal': 342,
'cant': 343,
'cool': 344,
'weekend': 345,
'rental': 346,
'try': 347,
'auction': 348,
'freemsg': 349,
'pounds': 350,
'mates': 351,
'suite342': 352,
'2lands': 353,
'did': 354,
'class': 355,
'month': 356,
'08000839402': 357,
'care': 358,
'phones': 359,
'amp': 360,
'statement': 361,
'points': 362,
'identifier': 363,
'expires': 364,
'final': 365,
'tv': 366,
'check': 367,
'wap': 368,
'really': 369,
'each': 370,
'wish': 371,
'secret': 372,
'info': 373,
'£2': 374,
'easy': 375,
'winner': 376,
'mobiles': 377,
'feel': 378,
'start': 379,
'nice': 380,
'sure': 381,
'date': 382,
'money': 383,
'pics': 384,
'xxx': 385,
BAPATLA WOMEN’S ENGINEERING COLLEGE 44
TENSORFLOW

'0800': 386,
'him': 387,
'year': 388,
'ringtones': 389,
'would': 390,
'custcare': 391,
'rates': 392,
'between': 393,
'looking': 394,
'thing': 395,
'were': 396,
'other': 397,
'his': 398,
'question': 399,
'2003': 400,
'800': 401,
'savamob': 402,
'offers': 403,
'place': 404,
'f': 405,
'eg': 406,
'late': 407,
'admirer': 408,
'thinks': 409,
'right': 410,
'reward': 411,
'net': 412,
'tc': 413,
'direct': 414,
'calls': 415,
'already': 416,
'valued': 417,
'important': 418,
'txts': 419,
'same': 420,
'say': 421,
'messages': 422,
'call2optout': 423,
'around': 424,
'shop': 425,
'anything': 426,
'buy': 427,
'caller': 428,
'03': 429,
'std': 430,
'again': 431,
'minutes': 432,
'un': 433,
'redeemed': 434,
'does': 435,
'charge': 436,
'pick': 437,
'numbers': 438,
'said': 439,
'anytime': 440,
'busy': 441,
'job': 442,
BAPATLA WOMEN’S ENGINEERING COLLEGE 45
TENSORFLOW

're': 443,
'gr8': 444,
'went': 445,
'shopping': 446,
'may': 447,
'meeting': 448,
'pobox': 449,
'things': 450,
'w1j6hl': 451,
'very': 452,
'lol': 453,
'also': 454,
'fancy': 455,
'ntt': 456,
'true': 457,
'player': 458,
'balance': 459,
'currently': 460,
'never': 461,
'thk': 462,
'asked': 463,
'sex': 464,
'game': 465,
'congrats': 466,
'either': 467,
'house': 468,
'ts': 469,
'complimentary': 470,
'charity': 471,
'missing': 472,
'many': 473,
'even': 474,
'yr': 475,
'sir': 476,
'look': 477,
'matches': 478,
'comp': 479,
'ipod': 480,
'having': 481,
'visit': 482,
'ac': 483,
'while': 484,
'04': 485,
'£150': 486,
'discount': 487,
'getzed': 488,
'long': 489,
'ldew': 490,
'luv': 491,
'ready': 492,
'weeks': 493,
'these': 494,
"that's": 495,
'ending': 496,
'wanna': 497,
'before': 498,
'inc': 499,
BAPATLA WOMEN’S ENGINEERING COLLEGE 46
TENSORFLOW

'must': 500,
'plus': 501,
'digital': 502,
'dogging': 503,
'11': 504,
'ldn': 505,
'down': 506,
'told': 507,
'always': 508,
'age': 509,
"i've": 510,
'hg': 511,
'age16': 512,
'post': 513,
'answer': 514,
'area': 515,
'08712460324': 516,
'terms': 517,
"t's": 518,
'england': 519,
'v': 520,
'87077': 521,
'ip4': 522,
'5we': 523,
'man': 524,
'guys': 525,
'id': 526,
'motorola': 527,
'ya': 528,
'saturday': 529,
'20p': 530,
'polys': 531,
'choose': 532,
'representative': 533,
'match': 534,
'details': 535,
'msgs': 536,
'credit': 537,
'xx': 538,
'00': 539,
'mind': 540,
'eat': 541,
'£800': 542,
'cd': 543,
'welcome': 544,
'away': 545,
"you're": 546,
'enough': 547,
'y': 548,
'little': 549,
'haha': 550,
'nyt': 551,
'specially': 552,
'£10': 553,
'enter': 554,
'getting': 555,
'pm': 556,
BAPATLA WOMEN’S ENGINEERING COLLEGE 47
TENSORFLOW

'txting': 557,
'big': 558,
'user': 559,
'lucky': 560,
'log': 561,
"there's": 562,
'into': 563,
'maybe': 564,
'150': 565,
'years': 566,
'coming': 567,
'£200': 568,
'store': 569,
'hmv': 570,
'del': 571,
'within': 572,
'correct': 573,
'dude': 574,
'den': 575,
'wan': 576,
'two': 577,
'wait': 578,
'made': 579,
'flag': 580,
'eve': 581,
'news': 582,
'bluetooth': 583,
'hear': 584,
'bx420': 585,
'50p': 586,
'sony': 587,
'sunshine': 588,
'0870': 589,
'called': 590,
'girl': 591,
'summer': 592,
'dream': 593,
'trip': 594,
'rcvd': 595,
'08718720201': 596,
'pa': 597,
'birthday': 598,
'freephone': 599,
'local': 600,
'office': 601,
'arrive': 602,
'bid': 603,
'girls': 604,
'bout': 605,
'85023': 606,
'pobox84': 607,
'2004': 608,
'06': 609,
'sleep': 610,
'wants': 611,
'tncs': 612,
'brings': 613,
BAPATLA WOMEN’S ENGINEERING COLLEGE 48
TENSORFLOW

'minute': 614,
'vodafone': 615,
'since': 616,
'information': 617,
'room': 618,
'08712300220': 619,
'standard': 620,
'credits': 621,
'flights': 622,
'biz': 623,
'tickets': 624,
'book': 625,
'sub': 626,
'luck': 627,
'3030': 628,
'no1': 629,
'invited': 630,
'onto': 631,
'fantastic': 632,
'awaiting': 633,
'access': 634,
'dad': 635,
'o2': 636,
'replying': 637,
'vary': 638,
'ill': 639,
'spree': 640,
'nothing': 641,
'address': 642,
'maximize': 643,
'until': 644,
'people': 645,
'sipix': 646,
'pc': 647,
'gay': 648,
'done': 649,
'costa': 650,
'sol': 651,
'sk38xh': 652,
'something': 653,
'pay': 654,
'hit': 655,
'bit': 656,
'calling': 657,
'few': 658,
'email': 659,
'20': 660,
'ans': 661,
'02': 662,
'thought': 663,
'yo': 664,
'zed': 665,
'bad': 666,
'pass': 667,
'150pm': 668,
'hour': 669,
'horny': 670,
BAPATLA WOMEN’S ENGINEERING COLLEGE 49
TENSORFLOW

'25p': 671,
'sp': 672,
'yet': 673,
'holder': 674,
'god': 675,
'1327': 676,
'croydon': 677,
'cr9': 678,
'5wb': 679,
'link': 680,
'ring': 681,
'fri': 682,
'reach': 683,
'logo': 684,
'leh': 685,
'arcade': 686,
'st': 687,
'cum': 688,
'till': 689,
'asap': 690,
'sky': 691,
'11mths': 692,
'partner': 693,
'wont': 694,
'3510i': 695,
'full': 696,
'dvd': 697,
'greet': 698,
'member': 699,
'singles': 700,
'frnd': 701,
'62468': 702,
'themob': 703,
'sport': 704,
'crazy': 705,
'princess': 706,
'voda': 707,
'quoting': 708,
'goto': 709,
'comuk': 710,
'extra': 711,
'hours': 712,
'computer': 713,
'picked': 714,
'2optout': 715,
'txtauction': 716,
'fine': 717,
'watching': 718,
'guy': 719,
'unsub': 720,
"we're": 721,
'tonight': 722,
'36504': 723,
"u've": 724,
'xchat': 725,
'following': 726,
'urawinner': 727,
BAPATLA WOMEN’S ENGINEERING COLLEGE 50
TENSORFLOW

'surprise': 728,
'than': 729,
'via': 730,
'supposed': 731,
'loan': 732,
'10am': 733,
'hurt': 734,
'stay': 735,
'pound': 736,
'contacted': 737,
'entered': 738,
'unlimited': 739,
'8': 740,
'cc': 741,
'28': 742,
'better': 743,
'loyalty': 744,
'anyway': 745,
'conditions': 746,
"uk's": 747,
'aight': 748,
'09050090044': 749,
'toclaim': 750,
'pobox334': 751,
'stockport': 752,
'cost£1': 753,
'max10mins': 754,
'okay': 755,
'1x150p': 756,
'ho': 757,
'optout': 758,
'linerental': 759,
'another': 760,
'online': 761,
'took': 762,
'announcement': 763,
'etc': 764,
'heart': 765,
'park': 766,
"won't": 767,
'subscription': 768,
'believe': 769,
'revealed': 770,
'show': 771,
'12': 772,
'starts': 773,
'82277': 774,
'80062': 775,
'fantasies': 776,
'08707509020': 777,
'close': 778,
'immediately': 779,
'leave': 780,
"what's": 781,
'takes': 782,
'car': 783,
'3g': 784,
BAPATLA WOMEN’S ENGINEERING COLLEGE 51
TENSORFLOW

'click': 785,
'stuff': 786,
'wid': 787,
'fantasy': 788,
'once': 789,
'though': 790,
'll': 791,
'bed': 792,
'remember': 793,
'card': 794,
'huh': 795,
'40gb': 796,
'entitled': 797,
'download': 798,
'83600': 799,
'fone': 800,
'original': 801,
'3gbp': 802,
'action': 803,
'ever': 804,
'300': 805,
'hoping': 806,
'break': 807,
"we'll": 808,
'reference': 809,
'red': 810,
'everyone': 811,
'gone': 812,
'wife': 813,
'24': 814,
'm263uz': 815,
'town': 816,
'adult': 817,
'tuition': 818,
'flower': 819,
'inviting': 820,
'eerie': 821,
'4u': 822,
'rply': 823,
'pobox36504w45wq': 824,
'selection': 825,
'440': 826,
'cds': 827,
'com1win150ppmx3age16': 828,
'evening': 829,
'lots': 830,
'2nite': 831,
"you've": 832,
'months': 833,
'sept': 834,
'king': 835,
'b4': 836,
'£400': 837,
'w1': 838,
'finish': 839,
'bath': 840,
'movie': 841,
BAPATLA WOMEN’S ENGINEERING COLLEGE 52
TENSORFLOW

'found': 842,
'boys': 843,
'vip': 844,
'jamster': 845,
'laid': 846,
'locations': 847,
'ec2a': 848,
'everything': 849,
'seems': 850,
'7pm': 851,
'dun': 852,
'w45wq': 853,
'norm150p': 854,
'sign': 855,
'msgrcvdhg': 856,
'review': 857,
'driving': 858,
'fixed': 859,
'85': 860,
'left': 861,
'87239': 862,
'flirt': 863,
'recd': 864,
'sell': 865,
'lar': 866,
'alert': 867,
'hurry': 868,
'bored': 869,
'87131': 870,
'sale': 871,
'refused': 872,
"'help'": 873,
'starting': 874,
'250': 875,
'questions': 876,
'9': 877,
'simple': 878,
'09061221066': 879,
'fromm': 880,
'60p': 881,
'says': 882,
'confirm': 883,
'early': 884,
'okie': 885,
'liao': 886,
'w': 887,
'quite': 888,
'wif': 889,
'jay': 890,
'missed': 891,
'cause': 892,
'official': 893,
'alright': 894,
'santa': 895,
'team': 896,
'second': 897,
'goes': 898,
BAPATLA WOMEN’S ENGINEERING COLLEGE 53
TENSORFLOW

'blue': 899,
'support': 900,
'person': 901,
'08715705022': 902,
'bahamas': 903,
'cheap': 904,
'lot': 905,
"god's": 906,
'cust': 907,
'problem': 908,
'listen': 909,
'choice': 910,
'tariffs': 911,
'86021': 912,
'porn': 913,
'wanted': 914,
'…': 915,
'oso': 916,
'mths': 917,
'ordered': 918,
'oredi': 919,
'came': 920,
'0': 921,
'08712405020': 922,
'pub': 923,
'comes': 924,
'£4': 925,
'polyphonic': 926,
'hl': 927,
'weekends': 928,
'yup': 929,
'leaving': 930,
'semester': 931,
'noe': 932,
'bloomberg': 933,
'due': 934,
'o': 935,
'wil': 936,
'q': 937,
'sending': 938,
'short': 939,
'30': 940,
'wen': 941,
'forwarded': 942,
'til': 943,
'videophones': 944,
'videochat': 945,
'java': 946,
'dload': 947,
'noline': 948,
'rentl': 949,
'children': 950,
'chikku': 951,
'cancel': 952,
'netcollex': 953,
'app': 954,
'working': 955,
BAPATLA WOMEN’S ENGINEERING COLLEGE 54
TENSORFLOW

'available': 956,
'2day': 957,
'calls£1': 958,
"haven't": 959,
'press': 960,
'smth': 961,
'ppm': 962,
'kick': 963,
'tel': 964,
'mid': 965,
'spook': 966,
'goin': 967,
'pg': 968,
'ntwk': 969,
'08001950382': 970,
'tenerife': 971,
'£900': 972,
'8552': 973,
'textpod': 974,
'ha': 975,
'1000s': 976,
'80082': 977,
'valentines': 978,
'dnt': 979,
'forget': 980,
'0808': 981,
'145': 982,
'4742': 983,
'9am': 984,
'11pm': 985,
'pod': 986,
'beyond': 987,
'deliveredtomorrow': 988,
'whats': 989,
'80488': 990,
'together': 991,
'befor': 992,
'kind': 993,
'cheers': 994,
'th': 995,
'subs': 996,
'05': 997,
'train': 998,
'exciting': 999,
'84025': 1000,
...}

In[16]:

padding_type='post'
truncate_type='post'
Trainning_seq=token.texts_to_sequences(train_msg)
Trainning_pad=pad_sequences(Trainning_seq,maxlen=50,padding=padding_type,truncating
=truncate_type)

BAPATLA WOMEN’S ENGINEERING COLLEGE 55


TENSORFLOW

In[17]:

import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences

data = pd.read_csv('C:/Users/91970/Documents/MAHE/OneDrive/Desktop/SPAM text


message 20170820 - Data.csv')

data.head()

data.groupby('Category').describe().T

import seaborn as sns


import matplotlib.pyplot as plt

plt.figure(figsize=(12, 14))
sns.countplot(data=data, x='Category')
plt.show()

BAPATLA WOMEN’S ENGINEERING COLLEGE 56


TENSORFLOW

7. Image classification using Tensorflow


AIM: Image classification using Tensorflow

SOURCE CODE:

In[1]:
import tensorflow as tf

# Helper libraries

import numpy as np

import matplotlib.pyplot as plt

In[2]:

fashion_mnist = tf.keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

Output:

Downloading data from https://storage.googleapis.com/tensorflow/tf-


keras-datasets/train-labels-idx1-ubyte.gz
29515/29515 [==============================] - 0s 4us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-
keras-datasets/train-images-idx3-ubyte.gz
26421880/26421880 [==============================] - 23s 1us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-
keras-datasets/t10k-labels-idx1-ubyte.gz
5148/5148 [==============================] - 0s 0s/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-
keras-datasets/t10k-images-idx3-ubyte.gz
4422102/4422102 [==============================] - 2s 1us/step
In[3]:

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',

'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

In[4]:

train_images.shape

OUTPUT:
(60000, 28, 28)
In[5]:

len(train_labels)

OUTPUT:

BAPATLA WOMEN’S ENGINEERING COLLEGE 57


TENSORFLOW

60000
In[6]:

train_labels

OUTPUT:
array([9, 0, 0, ..., 3, 0, 5], dtype=uint8)
In[7]:

len(test_labels)

OUTPUT:
10000
In[8]:

plt.figure()

plt.imshow(train_images[0])

plt.colorbar()

plt.grid(False)

plt.show()

OUTPUT:

\
BAPATLA WOMEN’S ENGINEERING COLLEGE 58
TENSORFLOW

In[9]:

train_images = train_images / 255.0

test_images = test_images / 255.0

In[10]:

plt.figure(figsize=(10,10))

for i in range(25):

plt.subplot(5,5,i+1)

plt.xticks([])

plt.yticks([])

plt.grid(False)

plt.imshow(train_images[i], cmap=plt.cm.binary)

plt.xlabel(class_names[train_labels[i]])

plt.show()

BAPATLA WOMEN’S ENGINEERING COLLEGE 59


TENSORFLOW

OUTPUT:

BAPATLA WOMEN’S ENGINEERING COLLEGE 60


TENSORFLOW

8. FACE RECOGNITION USING TENSORFLOW

AIM: Face Recognition using Tensorflow

SOURCE CODE:

KAGGLE DATASET

https://www.kaggle.com/code/yk7283/facial-recognition-with-deep-learning/input

In[1]:

import tensorflow as tf

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split

In[2]:

import numpy as np

# Replace 'YourUsername' with your actual username

file_path = r'C:/Users/91970/Documents/MAHE/OneDrive/Desktop/ORL_faces.npz'

data = np.load(file_path)

In[3]:

data_img= pd.DataFrame.from_dict({item: data[item] for item in data.files}, orient='index')

data_img

BAPATLA WOMEN’S ENGINEERING COLLEGE 61


TENSORFLOW

In[4]:

# Normalizing training data

X_train = np.array(data['trainX'],dtype='float32')/255

X_train

OUTPUT:

In[5]:

X_train.shape

OUTPUT:
(240, 10304)
In[6]:

# Normalizing testing data

X_test = np.array(data['testX'],dtype='float32')/255

X_test

BAPATLA WOMEN’S ENGINEERING COLLEGE 62


TENSORFLOW

In[7]:

X_test.shape

OUTPUT:
(160, 10304)
In[8]:

y_train= np.array(data['trainY'])

y_test= np.array(data['testY'])

In[9]:

print('Training dataset X_train, has', X_train.shape[0], 'rows and', X_train.shape[1], 'columns')

print('Testing dataset X_test, has', X_test.shape[0], 'rows and', X_test.shape[1], 'columns')

OUTPUT:
Training dataset X_train, has 240 rows and 10304 columns
Testing dataset X_test, has 160 rows and 10304 columns

In[10]:

img_rows=112

img_cols=92

batch_size=512

img_shape=(img_rows, img_cols, 1)

In[11]:

X_train.shape

BAPATLA WOMEN’S ENGINEERING COLLEGE 63


TENSORFLOW

OUTPUT:
(240, 10304)

In[12]:

X_train.dtype

OUTPUT:
dtype('float32')

In[13]:

X_test.shape

OUTPUT:
(160, 10304)

BAPATLA WOMEN’S ENGINEERING COLLEGE 64

You might also like