0% found this document useful (0 votes)
41 views

RESNET - Dynamometer - Ipynb - Colaboratory

This document configures a TensorFlow model to perform transfer learning on an image classification task. It loads pre-trained ResNet50 weights, adds classification layers, compiles the model for training, loads image data from directories, trains the model for 7 epochs, and plots the loss and accuracy curves. The model is trained to classify images into 15 categories and achieves over 99% validation accuracy after 7 epochs of training.

Uploaded by

Ankit Patel
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)
41 views

RESNET - Dynamometer - Ipynb - Colaboratory

This document configures a TensorFlow model to perform transfer learning on an image classification task. It loads pre-trained ResNet50 weights, adds classification layers, compiles the model for training, loads image data from directories, trains the model for 7 epochs, and plots the loss and accuracy curves. The model is trained to classify images into 15 categories and achieves over 99% validation accuracy after 7 epochs of training.

Uploaded by

Ankit Patel
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/ 6

from 

tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession

config = ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.5
config.gpu_options.allow_growth = True
session = InteractiveSession(config=config)

from tensorflow.keras.layers import Input, Lambda, Dense, Flatten

from tensorflow.keras.models import Model

from tensorflow.keras.applications.resnet50 import ResNet50

#from keras.applications.vgg16 import VGG16

from tensorflow.keras.applications.resnet50 import preprocess_input

from tensorflow.keras.preprocessing import image

from tensorflow.keras.preprocessing.image import ImageDataGenerator,load_img

from tensorflow.keras.models import Sequential

import numpy as np

from glob import glob

import PIL

import matplotlib.pyplot as plt

import tensorflow as tf

from google.colab import drive

drive.mount('/content/drive')

Mounted at /content/drive

# re-size all the images to this

IMAGE_SIZE = [224, 224]

train_path = '/content/drive/MyDrive/DYNOCARD_DATA/Train'

valid_path = '/content/drive/MyDrive/DYNOCARD_DATA/Test'

train_ds = tf.keras.preprocessing.image_dataset_from_directory(train_path)

Found 1050 files belonging to 15 classes.

class_names = train_ds.class_names

print(class_names)

['ANCHORED BUT NOT SET', 'ASPHALTENES IN PUMP', 'BAD TAIL BEARING', 'DEEP WELL', 'FLU

#plt.figure(figsize=(20,20))

#for images, labels in train_ds.take(1):

#for i in range(2):

 # ax = plt.subplot(2,2, i + 1)

 # plt.imshow(images[i].numpy().astype("uint8"))

  #plt.title(class_names[labels[i]])

  #plt.axis("off")

import tensorflow

resnet50 =tensorflow.keras.applications.ResNet152V2(input_shape=IMAGE_SIZE + [3], weights=

Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/re


234553344/234545216 [==============================] - 1s 0us/step

234561536/234545216 [==============================] - 1s 0us/step

# don't train existing weights

for layer in resnet50.layers:

    layer.trainable = False

# useful for getting number of output classes

folders = glob('/content/drive/MyDrive/DYNOCARD_DATA/Train/*')

# our layers - you can add more if you want

x = Flatten()(resnet50.output)

prediction = Dense(len(folders), activation='softmax')(x)

# create a model object

model = Model(inputs=resnet50.input, outputs=prediction)

model.summary()

# tell the model what cost and optimization method to use

model.compile(

  loss='categorical_crossentropy',

  optimizer='adam',

  metrics=['accuracy']

# Use the Image Data Generator to import the images from the dataset

from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,

                                   shear_range = 0.1,

                                   zoom_range = 0.1,

                                   horizontal_flip = False)

test_datagen = ImageDataGenerator(rescale = 1./255)

# Make sure you provide the same target size as initialied for the image size

training_set = train_datagen.flow_from_directory('/content/drive/MyDrive/DYNOCARD_DATA/Tra
                                                 target_size = (224, 224),

                                                 batch_size = 32,

                                                 class_mode = 'categorical')

Found 1050 images belonging to 15 classes.

test_set = test_datagen.flow_from_directory('/content/drive/MyDrive/DYNOCARD_DATA/Test',

                                            target_size = (224, 224),

                                            batch_size = 32,

                                            class_mode = 'categorical')

Found 448 images belonging to 15 classes.

#fluidpound = list(train_path.glob('fluidpound/*'))

#print(fluidpound[0])

#PIL.Image.open(str(fluidpound[0]))

import matplotlib.pyplot as plt

# fit the model

# Run the cell. It will take some time to execute

r = model.fit_generator(

  training_set,

  validation_data=test_set,

  epochs=7,

  steps_per_epoch=len(training_set),

  validation_steps=len(test_set)

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:8: UserWarning: `Model.f


Epoch 1/7

33/33 [==============================] - 920s 28s/step - loss: 0.6901 - accuracy: 0.8


Epoch 2/7

33/33 [==============================] - 30s 927ms/step - loss: 0.0050 - accuracy: 0


Epoch 3/7

33/33 [==============================] - 27s 824ms/step - loss: 0.0112 - accuracy: 0


Epoch 4/7

33/33 [==============================] - 27s 833ms/step - loss: 0.0023 - accuracy: 0


Epoch 5/7

33/33 [==============================] - 28s 838ms/step - loss: 8.5169e-04 - accuracy


Epoch 6/7

33/33 [==============================] - 28s 838ms/step - loss: 5.7457e-04 - accuracy


Epoch 7/7

33/33 [==============================] - 28s 840ms/step - loss: 1.3858e-04 - accuracy

import matplotlib.pyplot as plt
# plot the loss
plt.plot(r.history['loss'], label='train loss')
plt.plot(r.history['val_loss'], label='val loss')
plt.ylabel("Percentage",
               fontweight ='bold',fontsize=20, c = "r")
plt.xlabel("No of EPOCHS",
               fontweight ='bold', c = "green",fontsize=16)
plt.title("RESNET Model Losses", fontsize=22, fontweight = "bold", loc="center", c="yellow
plt.grid(color = 'black', linestyle = '--', linewidth = 0.35)
plt.legend(["Training Loss", "Validation Loss"], loc ="upper right")
plt.show()
#plt.savfig('LossVal_loss')
print('')
# plot the accuracy
plt.plot(r.history['accuracy'], label='train acc')
plt.plot(r.history['val_accuracy'], label='val acc')
plt.ylabel("Percentage",
               fontweight ='bold',fontsize=20, c = "r")
plt.xlabel("No of EPOCHS",
               fontweight ='bold', c = "green",fontsize=16)
plt.title("RESNET Model Accuracy", fontsize=22, fontweight = "bold", loc="center", c="yell
plt.grid(color = 'black', linestyle = '--', linewidth = 0.35)
plt.legend(["Training Accuracy", "Validation Accuracy"], loc ="lower right")
plt.show()

You might also like