Testing ML
Quick launch into Variables, Functions, Arrays, Classes, HTML.
import os
import certifi
import tensorflow as tf
from PIL import Image
from tensorflow.keras.applications import VGG16
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Set the paths to your dataset and tags
dataset_path = '/Users/poonam/Desktop/imgdata'
tags = ['animals', 'food', 'people'] # Replace with your own tags
# Define the parameters for training the model
image_size = (224, 224)
batch_size = 32
num_epochs = 10
# Create data generators for training and validation
data_generator = ImageDataGenerator(rescale=1.0/255.0, validation_split=0.2)
train_generator = data_generator.flow_from_directory(dataset_path, target_size=image_size, batch_size=batch_size, subset='training')
validation_generator = data_generator.flow_from_directory(dataset_path, target_size=image_size, batch_size=batch_size, subset='validation')
# Set the SSL certificate file environment variable
os.environ['SSL_CERT_FILE'] = certifi.where()
# Load the pre-trained VGG16 model without the top classification layer
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(image_size[0], image_size[1], 3))
# Add a global average pooling layer and a dense layer for classification
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(len(tags), activation='softmax')(x)
# Create the model with the VGG16 base and the classification layers
model = Model(inputs=base_model.input, outputs=predictions)
# Freeze the weights of the pre-trained layers
for layer in base_model.layers:
layer.trainable = False
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(train_generator, epochs=num_epochs, validation_data=validation_generator)
# Save the trained model
model.save('image_tagging_model.h5')
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import load_model
import numpy as np
# Load the saved model
model = load_model('image_tagging_model.h5')
# Load and preprocess the input image
image_path = '/Users/poonam/Downloads/dwayne.jpeg' # Replace with the path to your input image
person = Image.open(image_path)
img = image.load_img(image_path, target_size=(224, 224))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
img = img / 255.0 # Normalize the image
# Make predictions
predictions = model.predict(img)
predicted_class = np.argmax(predictions[0]) # Get the index of the highest probability class
# Print the predicted class and corresponding tag
tags = ['animals', 'food', 'people'] # Replace with your own tags
predicted_tag = tags[predicted_class]
print("Image")
person.show()
print("Predicted class:", predicted_class)
print("Predicted tag:", predicted_tag)