0% found this document useful (0 votes)
14 views8 pages

Lab 10 Practical

The document provides several examples of programs for building and training neural networks using Keras and TensorFlow. It includes a simple CNN model for image classification, a program for loading CSV data and creating a Keras model, and a training example on a custom dataset. Each section outlines the necessary steps including model definition, compilation, and training with sample outputs.

Uploaded by

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

Lab 10 Practical

The document provides several examples of programs for building and training neural networks using Keras and TensorFlow. It includes a simple CNN model for image classification, a program for loading CSV data and creating a Keras model, and a training example on a custom dataset. Each section outlines the necessary steps including model definition, compilation, and training with sample outputs.

Uploaded by

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

2.

Write a Program for CNN Model

A Convolutional Neural Network (CNN) is used for image classification. Here’s


an example of a simple CNN using Keras:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# Define CNN model


model = keras.Sequential([
layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64, (3,3), activation='relu'),
layers.MaxPooling2D((2,2)),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(10, activation='softmax')
])

# Compile the model


model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

# Display model summary


model.summary()
Output:
Model: "sequential"
________________________________________________________
Layer (type) Output Shape Param #
========================================================
conv2d (Conv2D) (None, 26, 26, 32) 320
max_pooling2d (MaxPooling2D) (None, 13, 13, 32) 0
conv2d_1 (Conv2D) (None, 11, 11, 64) 18496
max_pooling2d_1 (MaxPooling2 (None, 5, 5, 64) 0
flatten (Flatten) (None, 1600) 0
dense (Dense) (None, 128) 204928
dense_1 (Dense) (None, 10) 1290
4. Write a Program for Loading CSV Data and Creating a Keras Model
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split

# Load CSV data


data = pd.read_csv("data.csv") # Replace with your dataset
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values

# Split into training and test sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

# Define the model


model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(X.shape[1],)),
layers.Dense(32, activation='relu'),
layers.Dense(1, activation='sigmoid') # Use softmax for multi-class
classification
])

# Compile model
model.compile(optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])

# Train model
model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_test,
y_test))

Output:
Epoch 1/10
32/32 [==============================] - 1s 15ms/step - loss: 0.6905 -
accuracy: 0.52
...
Epoch 10/10
32/32 [==============================] - 0s 3ms/step - loss: 0.4541 -
accuracy: 0.79
7. Write a Program for Image Classification Using CNN

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist

# Load dataset
(X_train, y_train), (X_test, y_test) = mnist.load_data()

# Normalize data
X_train, X_test = X_train / 255.0, X_test / 255.0

# Reshape for CNN input


X_train = X_train.reshape(-1, 28, 28, 1)
X_test = X_test.reshape(-1, 28, 28, 1)

# Define CNN model


model = keras.Sequential([
layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64, (3,3), activation='relu'),
layers.MaxPooling2D((2,2)),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(10, activation='softmax')
])

# Compile and train


model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(X_train, y_train, epochs=5, batch_size=32, validation_data=(X_test,
y_test))

Output:
Epoch 1/5
1875/1875 [==============================] - loss: 0.1508 -
accuracy: 0.95
...
Epoch 5/5
1875/1875 [==============================] - loss: 0.0381 -
accuracy: 0.99
9. Write a Program for Training a Neural Network on a Custom
Dataset

import pandas as pd
import tensorflow as tf
from tensorflow import keras
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# Load dataset
data = pd.read_csv("data.csv") # Replace with actual file
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values

# Preprocess data
scaler = StandardScaler()
X = scaler.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

# Define model
model = keras.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=(X.shape[1],)),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dense(1, activation='sigmoid')
])
# Compile and train
model.compile(optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])
model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_test,
y_test))

Output:
Epoch 1/10
32/32 [==============================] - loss: 0.690 - accuracy:
0.52
...
Epoch 10/10
32/32 [==============================] - loss: 0.455 - accuracy:
0.79

You might also like