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

Project Notes

The document contains Python code for two main tasks: image recoloring using KMeans clustering and a machine learning model for classifying animal images using a neural network. It includes data preprocessing, model training, evaluation, and visualization of results. Additionally, it demonstrates the use of libraries such as OpenCV, TensorFlow, and scikit-learn for image processing and machine learning tasks.

Uploaded by

SHRIGAYATHRI S
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)
3 views

Project Notes

The document contains Python code for two main tasks: image recoloring using KMeans clustering and a machine learning model for classifying animal images using a neural network. It includes data preprocessing, model training, evaluation, and visualization of results. Additionally, it demonstrates the use of libraries such as OpenCV, TensorFlow, and scikit-learn for image processing and machine learning tasks.

Uploaded by

SHRIGAYATHRI S
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/ 2

1. import numpy as np 2.

import numpy as np
import cv2 import pandas as pd
from sklearn.cluster import KMeans import matplotlib.pyplot as plt
import matplotlib.pyplot as plt from sklearn.datasets import fetch_california_housing
def vectorize_image(image_path, k=5): from sklearn.model_selection import train_test_split
image = cv2.imread(image_path) from sklearn.preprocessing import StandardScaler
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) from sklearn.linear_model import LinearRegression
pixels = image.reshape((-1, 3)) from sklearn.metrics import mean_squared_error, r2_score
kmeans = KMeans(n_clusters=k, random_state=42, housing = fetch_california_housing()
n_init=10) df = pd.DataFrame(housing.data,
kmeans.fit(pixels) columns=housing.feature_names)
recolored_pixels = df['PRICE'] = housing.target
kmeans.cluster_centers_[kmeans.labels_] X = df.drop(columns=['PRICE']) y = df['PRICE']
recolored_image = X_train, X_test, y_train, y_test = train_test_split(X, y,
recolored_pixels.reshape(image.shape).astype(np.uint8) test_size=0.2, random_state=42)
return image, recolored_image scaler = StandardScaler()
def display_images(original, recolored): X_train = scaler.fit_transform(X_train)
fig, ax = plt.subplots(1, 2, figsize=(10, 5)) X_test = scaler.transform(X_test)
ax[0].imshow(original) model = LinearRegression()
ax[0].set_title("Original Image") model.fit(X_train, y_train)
ax[0].axis("off") y_pred = model.predict(X_test)
ax[1].imshow(recolored) mse = mean_squared_error(y_test, y_pred)
ax[1].set_title("Recolored Image") r2 = r2_score(y_test, y_pred)
ax[1].axis("off") print(f"Mean Squared Error: {mse}")
plt.show() print(f"R^2 Score: {r2}")
image_path = "p1.webp" plt.scatter(y_test, y_pred, alpha=0.7)
original, recolored = vectorize_image(image_path, k=5) plt.xlabel("Actual Prices")
display_images(original, recolored) plt.ylabel("Predicted Prices")
plt.title("Actual vs Predicted House Prices") plt.show()

3. import tensorflow as tf 4 . import tensorflow as tf


from tensorflow.keras.models import Sequential from tensorflow import keras
from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist from tensorflow.keras.applications import ResNet50
import matplotlib.pyplot as plt import numpy as np
import numpy as np import matplotlib.pyplot as plt
(x_train, y_train), (x_test, y_test) = mnist.load_data() (x_train, y_train), (x_test, y_test) =
x_train, x_test = x_train / 255.0, x_test / 255.0 keras.datasets.cifar10.load_data()
model = Sequential([Flatten(input_shape=(28, 28)), labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog',
Dense(128, activation='relu'),Dense(64, activation='relu'), 'frog', 'horse', 'ship', 'truck']
Dense(10, activation='softmax')]) animals = [2, 3, 4, 5, 6, 7]
model.compile(optimizer='adam', mask = lambda data, classes: np.isin(data, classes).flatten()
loss='sparse_categorical_crossentropy', x_train, y_train = x_train[mask(y_train, animals)],
metrics=['accuracy']) y_train[mask(y_train, animals)]
model.fit(x_train, y_train, epochs=10, x_test, y_test = x_test[mask(y_test, animals)],
validation_data=(x_test, y_test)) y_test[mask(y_test, animals)]
test_loss, test_acc = model.evaluate(x_test, y_test) x_train, x_test = x_train / 255.0, x_test / 255.0
print(f"Test accuracy: {test_acc:.4f}") num_classes = len(animals)
predictions = model.predict(x_test) y_train = keras.utils.to_categorical([animals.index(y) for y
def display_predictions(images, labels, predictions, in y_train], num_classes)
num=5):plt.figure(figsize=(10, 5)) y_test = keras.utils.to_categorical([animals.index(y) for y
for i in range(num): plt.subplot(1, num, i+1) in y_test], num_classes)
plt.imshow(images[i], cmap='gray') datagen = keras.preprocessing.image.ImageDataGenerator(
plt.axis('off') rotation_range=20, width_shift_range=0.2,
predicted_label = np.argmax(predictions[i]) height_shift_range=0.2,
actual_label = labels[i] horizontal_flip=True, zoom_range=0.2)
plt.title(f"Pred: {predicted_label}\nActual: datagen.fit(x_train)
{actual_label}")plt.show() model = models.Sequential([
display_predictions(x_test, y_test, predictions) ResNet50(weights='imagenet', include_top=False,
input_shape=(32, 32, 3), trainable=False),
layers.GlobalAveragePooling2D(),
layers.Dense(256, activation='relu'),
layers.BatchNormalization(),
layers.Dropout(0.4),
layers.Dense(num_classes, activation='softmax')
])
model.compile(optimizer=keras.optimizers.Adam(learning
_rate=1e-4),
loss='categorical_crossentropy',
metrics=['accuracy'])
lr_scheduler =
keras.callbacks.ReduceLROnPlateau(monitor='val_loss',
factor=0.5, patience=3, verbose=1)
model.fit(datagen.flow(x_train, y_train, batch_size=64),
validation_data=(x_test, y_test), epochs=40,
callbacks=[lr_scheduler])
loss, acc = model.evaluate(x_test, y_test, verbose=2)
print(f"Test Accuracy: {acc * 100:.2f}%")
model.save("optimized_animal_classifier.keras")
pred = np.argmax(model.predict(x_test), axis=1)
actual = np.argmax(y_test, axis=1)
correct_indices = np.where(pred == actual)[0][:4]
def display_correct_preds(images, actual, pred, labels,
indices):
plt.figure(figsize=(10, 5))
for i, idx in enumerate(indices):
plt.subplot(1, 4, i + 1)
plt.imshow(images[idx])
plt.axis('off')
plt.title(f"Predicted: {labels[animals[actual[idx]]]}",
color='green')
plt.show()
display_correct_preds(x_test, actual, pred, labels,
correct_indices)

You might also like