Integrated Systems Lab BEI657A
Experiments
1. Regression Analysis
Steps in Regression Analysis
1. Define the Problem:
○ Identify the dependent and independent variables.
2. Collect Data:
○ Ensure data is clean, complete, and relevant.
3. Choose the Model:
○ Select the appropriate type of regression based on the data and problem.
4. Fit the Model:
○ Use software (e.g., Python, R, Excel) to estimate the coefficients.
5. Evaluate the Model:
○ Check R2,, adjusted R2, residuals, and other diagnostics.
6. Validate the Model:
○ Test the model on new data to ensure it generalizes well.
7. Interpret Results:
○ Draw conclusions about the relationships and make predictions.
Applications of Regression Analysis
● Economics: Predicting GDP, inflation, or consumer behavior.
● Finance: Forecasting stock prices or risk assessment.
● Healthcare: Analyzing the impact of treatments or predicting patient outcomes.
● Marketing: Understanding customer behavior and sales trends.
● Engineering: Modeling relationships in physical systems.
Experiment a): Python Code for Simple Linear Regression
# Import necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
Step 1: Create a synthetic dataset
np.random.seed(42) # For reproducibility
X = 2 * np.random.rand(100, 1) # 100 random values for the independent variable
y = 4 + 3 * X + np.random.randn(100, 1) # Linear relationship with some noise
data = pd.DataFrame({'X_Value': X.flatten(), 'Y_Value': y.flatten()}) #Flatten the numpy arrays
# Save the dataset
data.to_csv('Random_Values.csv', index=False)
print(data.head()) #To verify the data created.
Step 2: Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Step 3: Create and train the linear regression model
model = LinearRegression()
model.fit(X_train, y_train) # Fit the model to the training data
Step 4: Make predictions on the test set
y_pred = model.predict(X_test)
Step 5: Evaluate the model
mse = mean_squared_error(y_test, y_pred) # Mean Squared Error
r2 = r2_score(y_test, y_pred) # R-squared value
print(f"Intercept (B₀): {model.intercept_}")
print(f"Slope (B₁): {model.coef_}")
print(f"Mean Squared Error (MSE): {mse}")
print(f"R-squared (R²): {r2}")
Step 6: Visualize the results
plt.scatter(X_test, y_test, color='blue', label='Actual Data') # Plot actual data points
plt.plot(X_test, y_pred, color='red', label='Regression Line') # Plot regression line
plt.xlabel('Independent Variable (X)')
plt.ylabel('Dependent Variable (y)')
plt.title('Simple Linear Regression')
plt.legend()
plt.show()
Experiment b): Predicting House Prices Using Simple Linear Regression.
Predict house prices based on the size of the house using a simple linear regression model.
Tools and Libraries
● Python with the following libraries:
○ NumPy and Pandas (for data handling).
○ Matplotlib (for visualization).
○ Scikit-learn (for regression modeling and evaluation).
Step 1: Generate Synthetic Dataset
Create a synthetic dataset where house prices depend on the size of the house.
python
import numpy as np
import pandas as pd
Step 1: Generate synthetic data
np.random.seed(42) # For reproducibility
house_sizes = np.random.randint(1000, 5000, 100) # House sizes in square feet
house_prices = 50 * house_sizes + np.random.normal(0, 20000, 100) # Prices in dollars
# Create a DataFrame
data = pd.DataFrame({ 'HouseSize': house_sizes, 'HousePrice': house_prices})
# Save the dataset
data.to_csv('house_prices.csv', index=False)
print(data.head())
Step 2: Visualize the Data
Plot the relationship between house size and house price.
import matplotlib.pyplot as plt
# Scatter plot of house size vs. house price
plt.scatter(data['HouseSize'], data['HousePrice'], color='blue')
plt.title('House Size vs. House Price')
plt.xlabel('House Size (sq. ft.)')
plt.ylabel('House Price ($)')
plt.show()
Step 3: Preprocess the Data
Split the data into training and testing sets.
from sklearn.model_selection import train_test_split
# Split features (X) and target (y)
X = data[['HouseSize']]
y = data['HousePrice']
# Split into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Step 4: Train the Linear Regression Model
Use scikit-learn to create and train a simple linear regression model.
from sklearn.linear_model import LinearRegression
# Create and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Print the model coefficients
print(f"Intercept (β₀): {model.intercept_}")
print(f"Slope (β₁): {model.coef_[0]}")
Step 5: Make Predictions
Use the trained model to predict house prices for the test set.
# Predict house prices for the test set
y_pred = model.predict(X_test)
# Add predictions to the test data
results = X_test.copy()
results['ActualPrice'] = y_test
results['PredictedPrice'] = y_pred
print(results.head())
Step 6: Evaluate the Model
Evaluate the model using metrics like Mean Squared Error (MSE) and R-squared.
from sklearn.metrics import mean_squared_error, r2_score
# Calculate evaluation metrics
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"Mean Squared Error (MSE): {mse}")
print(f"R-squared (R²): {r2}")
Step 7: Visualize the Regression Line
Plot the regression line along with the actual data points.
# Plot the regression line
plt.scatter(X_test, y_test, color='blue', label='Actual Prices')
plt.plot(X_test, y_pred, color='red', label='Regression Line')
plt.title('House Size vs. House Price (with Regression Line)')
plt.xlabel('House Size (sq. ft.)')
plt.ylabel('House Price ($)')
plt.legend()
plt.show()
Step 8: Test the Model with New Data
Test the model with new house sizes to predict prices.
# New house sizes (in sq. ft.)
new_house_sizes = np.array([[1500], [2500], [3500]])
# Predict prices for new house sizes
predicted_prices = model.predict(new_house_sizes)
# Display predictions
for size, price in zip(new_house_sizes, predicted_prices):
print(f"House Size: {size[0]} sq. ft. -> Predicted Price: ${price:.2f}")
Expected Output
1. Model Coefficients:
○ Intercept (β0): The base price when house size is 0.
○ Slope (β1): The increase in price per square foot.
2. Evaluation Metrics:
○ MSE: Measures the average squared difference between actual and predicted prices.
○ R²: Indicates how well the model explains the variance in house prices.
3. Regression Line:
○ A straight line that best fits the data points.
4. Predictions:
○ Predicted prices for new house sizes.
2. Data classification using various machine learning algorithms.
a) Classification with Logistic Regression
Problem: Binary Classification on the Iris Dataset
Use the Iris dataset to classify whether a flower is of the species Setosa or Versicolor based on sepal
length and width.
# Import libraries
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Load the Iris dataset
iris = load_iris()
X = iris.data[:, :2] # Use only sepal length and width
y = (iris.target == 0).astype(int) # Binary classification: Setosa (1) or Not Setosa (0)
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Train the Logistic Regression model
model = LogisticRegression()
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))
b) Classification with Decision Trees
Problem: Multi-class Classification on the Iris Dataset
Classify the Iris dataset into three species: Setosa, Versicolor, and Virginica.
# Import libraries
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Load the Iris dataset
iris = load_iris()
X = iris.data # Use all features
y = iris.target # Multi-class classification
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Train the Decision Tree model
model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))
c) Classification with K-Nearest Neighbors (KNN)
Problem: Binary Classification on Synthetic Data
Classify synthetic data into two classes using the KNN algorithm.
# Import libraries
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Generate synthetic data
X, y = make_classification(n_samples=1000, n_features=4, n_classes=2, n_clusters_per_class=1,
random_state=42)
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Train the KNN model
model = KNeighborsClassifier(n_neighbors=5)
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))
d) Classification with Support Vector Machines (SVM)
Problem: Binary Classification on Synthetic Data
Classify synthetic data into two classes using an SVM with a linear kernel.
# Import libraries
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Generate synthetic data
X, y = make_classification(n_samples=1000, n_features=4, n_classes=2, n_clusters_per_class=1,
random_state=42)
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Train the SVM model
model = SVC(kernel='linear', random_state=42)
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))
Key Takeaways:
1. Data Preprocessing: Always split data into training and testing sets.
2. Model Selection: Choose the algorithm based on the problem (binary/multi-class classification).
3. Evaluation Metrics: Use accuracy, confusion matrix, and classification report to evaluate
performance.
4. Hyperparameter Tuning: Experiment with different parameters (e.g., n_neighbors in KNN,
kernel in SVM).
3. Create a Simple Image Classification Network using Deep Network Designer.
Train a neural network to classify images of handwritten digits (0–9) using the MNIST dataset.
What You’ll Need:
1. Hardware: A computer with internet access.
2. Software: Python along with libraries: TensorFlow, NumPy, and Matplotlib.
Steps:
Install the required libraries using pip:
pip install tensorflow numpy matplotlib
Open a Python editor (e.g., Jupyter Notebook, VS Code, or any IDE).
Step 1: Load and Explore the Dataset
Use the MNIST dataset (built into TensorFlow), which contains 28x28 grayscale images of
handwritten digits.
Run this code to load and visualize the data:
import tensorflow as tf
import matplotlib.pyplot as plt
# Load MNIST dataset
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
# Print dataset info
print("Training samples:", train_images.shape) # (60000, 28, 28)
print("Test samples:", test_images.shape) # (10000, 28, 28)
# Show a sample image
plt.imshow(train_images[0], cmap='gray')
plt.title(f"Label: {train_labels[0]}")
plt.show()
Step 2: Preprocess the Data
Normalize pixel values (0–255) to a range of 0–1.
Reshape the data to fit the neural network input:
# Normalize pixel values
train_images = train_images / 255.0
test_images = test_images / 255.0
# Reshape for the network (add channel dimension)
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
Step 3: Build the Neural Network
Create a simple Convolutional Neural Network (CNN) with Keras:
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax') # 10 output classes (digits 0–9)
])
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Show model summary
model.summary()
Step 4: Train the Model
#Train the network on the training data for a few epochs:
model.fit(train_images, train_labels, epochs=5, batch_size=32)
Step 5: Evaluate the Model
#Test the model on the test dataset and check accuracy:
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"Test accuracy: {test_acc:.4f}")
Step 6: Make Predictions
#Use the model to predict a few test images and visualize the results
predictions = model.predict(test_images[:5])
for i in range(5):
plt.imshow(test_images[i].reshape(28, 28), cmap='gray')
plt.title(f"Predicted: {predictions[i].argmax()}, True: {test_labels[i]}")
plt.show()
Expected Output
The model should achieve ~97–99% accuracy on the test set after 5 epochs.
You’ll see sample predictions with images and their predicted labels.
Experiment by changing the number of epochs, adding more layers, or tweaking the number of
neurons in the Dense layers to see how accuracy changes.
4. Development of Image classification models using Squeezenet.
SqueezeNet is a lightweight convolutional neural network (CNN) that achieves good accuracy with
fewer parameters.
Below is a simple Python experiment using SqueezeNet for image classification. This example uses
TensorFlow and Keras, which are beginner-friendly libraries for deep learning.
Python code:
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.applications import SqueezeNet
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
import numpy as np
Step 1: Load and Preprocess the Dataset
For simplicity, we'll use the CIFAR-10 dataset, which is a common dataset for image classification
tasks.
# Load CIFAR-10 dataset
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
print("Training samples:", train_images.shape) # (50000, 32, 32)
print("Test samples:", test_images.shape) # (10000, 32, 32)
# Show a sample image
plt.imshow(train_images[10], cmap='gray')
plt.title(f"Label: {train_labels[10]}")
plt.show()
# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0
# Convert labels to one-hot encoding
train_labels = to_categorical(train_labels, 10)
test_labels = to_categorical(test_labels, 10)
Step 2: Build the SqueezeNet Model
use the pre-trained SqueezeNet model and fine-tune it for the CIFAR-10 dataset.
# Load SqueezeNet with pre-trained weights (exclude the top classification layer)
base_model = SqueezeNet(weights='imagenet', include_top=False, input_shape=(32, 32, 3))
# Freeze the base model (optional for fine-tuning)
base_model.trainable = False
# Add custom classification layers
model = models.Sequential([
base_model,
layers.GlobalAveragePooling2D(),
layers.Dense(10, activation='softmax') # CIFAR-10 has 10 classes
])
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Print model summary
model.summary()
Step 3: Train the Model
Train the model on the CIFAR-10 dataset.
# Train the model
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
Step 4: Evaluate the Model
Evaluate the model's performance on the test dataset.
# Evaluate the model
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f"Test accuracy: {test_acc:.4f}")
Step 7: Visualize Results
Plot the training and validation accuracy/loss to understand the model's performance.
# Plot training and validation accuracy
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
# Plot training and validation loss
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Step 8: Make Predictions
Use the trained model to make predictions on new images.
# Make predictions
predictions = model.predict(test_images)
# Display the predicted class for the first test image
predicted_class = np.argmax(predictions[0])
print(f"Predicted class: {predicted_class}")
Dataset: You can experiment with other datasets like MNIST, Fashion-MNIST, or your own custom
dataset.
Fine-Tuning: Try unfreezing some layers of the SqueezeNet model and fine-tuning it for better
performance.
Hyperparameters: Experiment with different optimizers, learning rates, and batch sizes.
Deployment: Once trained, you can save the model using model.save() and deploy it in a real-world
application.
This experiment provides a basic understanding of how to use SqueezeNet for image classification.
5. Development of an alarm system using a neural network fitting tool.
The goal is to create a neural network that can classify whether an alarm should be triggered based on
input sensor data (e.g., temperature, humidity, or motion).
Lab Experiment: Alarm System Using a Neural Network
Objective
Develop a neural network-based alarm system that can classify whether an alarm should be triggered
based on input sensor data.
Tools and Libraries
● Python with the following libraries:
○ TensorFlow or Keras (for building the neural network).
○ Pandas and NumPy (for data handling).
○ Matplotlib or Seaborn (for visualization).
○ Scikit-learn (for data preprocessing and evaluation).
Dataset
We’ll use a synthetic dataset for this experiment. The dataset will contain the following features:
1. Temperature: Simulated temperature readings.
2. Humidity: Simulated humidity readings.
3. Motion: Simulated motion sensor data (0 = no motion, 1 = motion detected).
4. Alarm: Target variable (0 = no alarm, 1 = alarm triggered).
Step 1: Generate Synthetic Dataset
import numpy as np
import pandas as pd
# Generate synthetic data
np.random.seed(42)
n_samples = 1000
# Simulate temperature, humidity, and motion
temperature = np.random.normal(25, 5, n_samples) # Mean = 25°C, Std = 5
humidity = np.random.normal(60, 10, n_samples) # Mean = 60%, Std = 10
motion = np.random.randint(0, 2, n_samples) # Binary motion data (0 or 1)
# Define alarm conditions
alarm = np.where(((temperature > 30) & (humidity > 70)) | (motion == 1), 1, 0)
# Create a DataFrame
data = pd.DataFrame({ 'Temperature': temperature,'Humidity': humidity,
'Motion': motion, 'Alarm': alarm})
# Save the dataset (optional)
data.to_csv('alarm_system_data.csv', index=False)
print(data.head())
Step 2: Preprocess the Data
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Load the dataset
data = pd.read_csv('alarm_system_data.csv')
# Split features and target
X = data[['Temperature', 'Humidity', 'Motion']]
y = data['Alarm']
# Split into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Normalize the features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
Step 3: Build the Neural Network
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Define the neural network model
model = Sequential([
Dense(16, activation='relu', input_shape=(X_train.shape[1],)), # Input layer
Dense(8, activation='relu'), # Hidden layer
Dense(1, activation='sigmoid') # Output layer
])
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Print the model summary
model.summary()
Step 4: Train the Neural Network
# Train the model
history = model.fit(X_train, y_train,epochs=50, batch_size=32, validation_split=0.2,
verbose=1 )
Step 5: Evaluate the Model
# Evaluate the model on the test set
loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"Test Accuracy: {accuracy * 100:.2f}%")
# Make predictions
y_pred = (model.predict(X_test) > 0.5).astype(int)
# Confusion matrix and classification report
from sklearn.metrics import confusion_matrix, classification_report
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Classification Report:\n", classification_report(y_test, y_pred))
Step 6: Visualize Training Performance
import matplotlib.pyplot as plt
# Plot training and validation accuracy
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
# Plot training and validation loss
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
Step 7: Test the Alarm System
# Test the system with new data
new_data = np.array([[28, 65, 0], # No alarm (normal conditions)
[35, 75, 1], # Alarm (high temperature, high humidity, motion)
[22, 50, 0]]) # No alarm (normal conditions)
# Normalize the new data
new_data = scaler.transform(new_data)
# Predict alarm status
predictions = (model.predict(new_data) > 0.5).astype(int)
print("Alarm Predictions:", predictions.flatten())
Expected Output
1. Test Accuracy: Should be close to 100% if the dataset is well-separated.
2. Confusion Matrix: Shows true positives, true negatives, false positives, and false negatives.
3. Classification Report: Provides precision, recall, and F1-score.
4. Alarm Predictions: The model should correctly classify whether an alarm should be triggered.
Key Takeaways for Students
1. Neural Network Basics: Understand input layers, hidden layers, and output layers.
2. Data Preprocessing: Importance of normalizing data for neural networks.
3. Model Evaluation: Use accuracy, confusion matrix, and classification report to evaluate
performance.
4. Real-World Application: Neural networks can be used for decision-making systems like
alarms.
6. Deployment of Prediction Model in the target device.
Deploying an image classification model like one built using SqueezeNet involves making the model
accessible for real-world use. The choice of deployment device depends on the application requirements,
such as latency, power consumption, and scalability. Below are some common deployment options.
1. Local Machine (Laptop/Desktop)
Use Case: Prototyping, testing, or small-scale applications.
Steps:
1. Save the trained model using model.save('squeezenet_model.h5').
2. Load the model in a Python script or Jupyter Notebook for inference.
3. Use a web framework like Flask or FastAPI to create an API for the model.
4. Run the API locally and test it using Postman or a web browser.
2. Edge Devices (Raspberry Pi, NVIDIA Jetson Nano)
Use Case: Real-time applications with low latency, such as IoT or robotics.
Steps:
1. Save the trained model.
2. Convert the model to a format optimized for edge devices (e.g., TensorFlow Lite or
ONNX).
3. Deploy the model on the edge device using a lightweight inference library like
TensorFlow Lite or OpenCV.
4. Write a Python script to capture images from a camera and perform inference.
5. Run the script on the device and test it.
1. Local Machine (Laptop/Desktop)
Detailed Steps for Deployment Using Flask (Local Machine)
Step 1: Save the Trained Model
Save the trained model as before.
Step 2: Create a Flask API
Write a Flask app to serve the model.
Python:
from flask import Flask, request, jsonify
import numpy as np
from PIL import Image
import tensorflow as tf
app = Flask(__name__)
# Load the model
model = tf.keras.models.load_model('squeezenet_model.h5')
@app.route('/predict', methods=['POST'])
def predict():
# Load and preprocess the image
file = request.files['image']
image = Image.open(file).resize((32, 32))
image = np.array(image, dtype=np.float32) / 255.0
image = np.expand_dims(image, axis=0)
# Perform inference
predictions = model.predict(image)
predicted_class = np.argmax(predictions)
# Return the result
return jsonify({'predicted_class': int(predicted_class)})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Step 3: Run the Flask App
Run the Flask app on your local machine.
python app.py
Step 4: Test the API
Use Postman or a Python script to send an image to the API and get predictions.
import requests
url = 'http://localhost:5000/predict'
files = {'image': open('test_image.jpg', 'rb')}
response = requests.post(url, files=files)
print(response.json())
2. Detailed Steps for Deployment on a Raspberry Pi (Edge Device)
Step 1: Save the Trained Model
Save the trained SqueezeNet model in Keras format.
Python
model.save(‘squeezenet_model.h5’)
Step 2: Convert the Model to TensorFlow Lite
Convert the model to TensorFlow Lite format for edge devices.
import tensorflow as tf
# Load the saved model
model = tf.keras.models.load_model('squeezenet_model.h5')
# Convert to TensorFlow Lite
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the TensorFlow Lite model
with open('squeezenet_model.tflite', 'wb') as f:
f.write(tflite_model)
Step 3: Set Up the Raspberry Pi
1. Install TensorFlow Lite on the Raspberry Pi:
pip install tflite-runtime
2. Transfer the .tflite model file to the Raspberry Pi using SCP or a USB drive.
Step 4: Write an Inference Script
Write a Python script to perform inference on the Raspberry Pi.
import numpy as np
import tflite_runtime.interpreter as tflite
from PIL import Image
# Load the TensorFlow Lite model
interpreter = tflite.Interpreter(model_path='squeezenet_model.tflite')
interpreter.allocate_tensors()
# Get input and output details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Load and preprocess an image
image = Image.open('test_image.jpg').resize((32, 32)) # Resize to match model input
image = np.array(image, dtype=np.float32) / 255.0 # Normalize
image = np.expand_dims(image, axis=0) # Add batch dimension
# Perform inference
interpreter.set_tensor(input_details[0]['index'], image)
interpreter.invoke()
output = interpreter.get_tensor(output_details[0]['index'])
# Get the predicted class
predicted_class = np.argmax(output)
print(f"Predicted class: {predicted_class}")
Step 5: Test the Deployment
1. Capture an image using a Raspberry Pi camera or load an existing image.
2. Run the inference script and check the output.
Conclusion
Deploying your image classification model can be done on various devices depending on your needs.
For beginners, starting with a local machine or Raspberry Pi is recommended. As you gain experience,
you can explore cloud platforms or mobile deployment. Each deployment method has its own
advantages.
7. Create a system to monitor and control temparature using an Arduino , a temparature sensor
(e.r LM35), and a cooling fan.
Components Required
1. Arduino Uno (or any compatible microcontroller)
2. Temperature Sensor (e.g., LM35 or DHT11)
3. Cooling Fan (DC motor with a fan blade)
4. Transistor (e.g., NPN transistor like 2N2222 or MOSFET like IRF540)
5. Diode (e.g., 1N4007 for flyback protection)
6. Resistor (e.g., 220Ω for the transistor base)
7. Breadboard and Jumper Wires
8. Power Supply (e.g., 9V battery or external power for the fan)
Circuit Diagram
1. Temperature Sensor:
o Connect the VCC pin of the sensor to 5V on the Arduino.
o Connect the GND pin of the sensor to GND on the Arduino.
o Connect the output pin of the sensor to an analog input pin on the Arduino (e.g., A0).
2. Cooling Fan:
o Connect the positive terminal of the fan to the collector of the transistor.
o Connect the emitter of the transistor to GND.
o Connect the base of the transistor to a digital pin on the Arduino (e.g., D9) through a
220Ω resistor.
o Place a diode across the fan terminals (anode to GND, cathode to the positive terminal)
for flyback protection.
Arduino Code
// Define pins
const int tempSensorPin = A0; // Temperature sensor connected to A0
const int fanPin = 9; // Fan connected to D9 (PWM pin)
// Define temperature thresholds
const float lowTemp = 25.0; // Fan turns on above this temperature
const float highTemp = 30.0; // Fan runs at full speed above this temperature
void setup() {
pinMode(fanPin, OUTPUT); // Set fan pin as output
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Read temperature sensor value
int sensorValue = analogRead(tempSensorPin);
float voltage = sensorValue * (5.0 / 1023.0); // Convert to voltage
float temperature = voltage * 100.0; // Convert to temperature (LM35)
// Print temperature to serial monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
// Control the fan based on temperature
if (temperature > highTemp) {
analogWrite(fanPin, 255); // Fan at full speed
} else if (temperature > lowTemp) {
int fanSpeed = map(temperature, lowTemp, highTemp, 100, 255); // Adjust fan speed
analogWrite(fanPin, fanSpeed);
} else {
analogWrite(fanPin, 0); // Fan off
}
delay(1000); // Wait for 1 second before next reading
}
Steps to Build the System
Step 1: Connect the Circuit
1. Connect the temperature sensor to the Arduino as described in the circuit diagram.
2. Connect the cooling fan to the transistor and Arduino.
3. Double-check all connections to avoid short circuits.
Step 2: Upload the Code
1. Open the Arduino IDE on your computer.
2. Copy and paste the code above into a new sketch.
3. Select the correct board (e.g., Arduino Uno) and port in the IDE.
4. Upload the code to the Arduino.
5.
6. Step 3: Test the System
1. Power the Arduino using a USB cable or external power supply.
2. Open the Serial Monitor in the Arduino IDE to view the temperature readings.
3. Observe the fan behavior as the temperature changes:
o The fan should turn on when the temperature exceeds 25°C.
o The fan speed should increase as the temperature rises.
o The fan should turn off when the temperature drops below 25°C.
Step 4: Calibrate and Improve
If the temperature readings are inaccurate, calibrate the sensor or adjust the code.
Add an LCD display to show the temperature and fan status in real-time.
Use a relay module if the fan requires higher voltage/current than the Arduino can handle.
8. Develop a smart lighting system that adjusts brigtness based on ambient light using an arduino,
a light sensor (eg LDR), and an LED
Components Required
1. Arduino Uno (or any compatible microcontroller)
2. Light Dependent Resistor (LDR)
3. LED (any color)
4. Resistors:
o 10kΩ resistor (for the LDR voltage divider)
o 220Ω resistor (for the LED current limiting)
5. Breadboard and Jumper Wires
6. Power Supply (e.g., USB cable or external power for the Arduino)
Circuit Diagram
1. LDR Circuit:
o Connect one leg of the LDR to 5V on the Arduino.
o Connect the other leg of the LDR to an analog input pin on the Arduino (e.g., A0) and to
one end of the 10kΩ resistor.
o Connect the other end of the 10kΩ resistor to GND.
2. LED Circuit:
o Connect the anode (longer leg) of the LED to a digital PWM pin on the Arduino (e.g.,
D9) through a 220Ω resistor.
o Connect the cathode (shorter leg) of the LED to GND.
Arduino Code
Here’s the code to read the ambient light level and adjust the LED brightness accordingly:
// Define pins
const int ldrPin = A0; // LDR connected to A0
const int ledPin = 9; // LED connected to D9 (PWM pin)
// Define brightness thresholds
const int darkThreshold = 200; // Below this value, LED is at full brightness
const int brightThreshold = 800; // Above this value, LED is off
void setup() {
pinMode(ledPin, OUTPUT); // Set LED pin as output
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Read LDR value
int ldrValue = analogRead(ldrPin);
// Print LDR value to serial monitor
Serial.print("LDR Value: ");
Serial.println(ldrValue);
// Adjust LED brightness based on LDR value
if (ldrValue < darkThreshold) {
analogWrite(ledPin, 255); // Full brightness in dark conditions
} else if (ldrValue > brightThreshold) {
analogWrite(ledPin, 0); // Turn off LED in bright conditions
} else {
// Map LDR value to LED brightness (inverse relationship)
int brightness = map(ldrValue, darkThreshold, brightThreshold, 255, 0);
analogWrite(ledPin, brightness);
}
delay(100); // Small delay for stability
}
Steps to Build the System
Step 1: Connect the Circuit
1. Connect the LDR to the Arduino as described in the circuit diagram.
2. Connect the LED to the Arduino through the 220Ω resistor.
3. Double-check all connections to avoid short circuits.
Step 2: Upload the Code
1. Open the Arduino IDE on your computer.
2. Copy and paste the code above into a new sketch.
3. Select the correct board (e.g., Arduino Uno) and port in the IDE.
4. Upload the code to the Arduino.
Step 3: Test the System
1. Power the Arduino using a USB cable or external power supply.
2. Open the Serial Monitor in the Arduino IDE to view the LDR readings.
3. Observe the LED brightness as the ambient light changes:
o The LED should be at full brightness in dark conditions.
o The LED should turn off in bright conditions.
o The LED brightness should adjust smoothly between these extremes.
Step 4: Calibrate and Improve
Adjust the darkThreshold and brightThreshold values in the code to match your environment.
Use a potentiometer to manually adjust the brightness thresholds.
Add more LEDs or use an RGB LED for colorful lighting effects.
Optional Enhancements
1. LCD Display:
o Add an LCD to display the LDR value and LED brightness.
o Use the LiquidCrystal library to interface with the LCD.
2. WiFi/Bluetooth Connectivity:
o Use an ESP8266 or Bluetooth module to send light data to a smartphone or computer.
3. Motion Sensor:
o Add a PIR motion sensor to turn the LED on only when motion is detected.
4. Enclosure:
o Build an enclosure for the system to protect the components and improve aesthetics.
Explanation of the Code
The LDR value is read using analogRead(). This value ranges from 0 (dark) to 1023 (bright).
The map() function is used to convert the LDR value to an appropriate LED brightness level.
The analogWrite() function sets the LED brightness using PWM (Pulse Width Modulation).