Practical Program: Study of TensorFlow Library in Python

Practical Program: Study of TensorFlow Library in Python

This program introduces TensorFlow by creating a simple neural network to predict a linear relationship between input and output data. TensorFlow is a powerful library used for machine learning, deep learning, and numerical computation.

Scenario: Predicting a Linear Relationship  
We will create a model to predict \( y = 2x + 1 \) using TensorFlow. The model will be trained on sample data.
Code Implementation
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# --- 1. Prepare the Dataset ---
# Input data (x) and corresponding labels (y)
x_train = np.array([0, 1, 2, 3, 4, 5], dtype=float)
y_train = np.array([1, 3, 5, 7, 9, 11], dtype=float)
print("Training Data:")
print("x:", x_train)
print("y:", y_train)
# --- 2. Define a Simple Linear Model ---
# A single-layer dense neural network with one unit
model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=1, input_shape=[1])  # One neuron with one input
])
# --- 3. Compile the Model ---
model.compile(optimizer='sgd',  # Stochastic Gradient Descent
              loss='mean_squared_error')
# --- 4. Train the Model ---
print("\nTraining the model...")
history = model.fit(x_train, y_train, epochs=500, verbose=0)
# Display training completion
print("Training completed!")
# --- 5. Evaluate the Model ---
# Predict for new inputs
x_test = np.array([6, 7, 8, 9, 10], dtype=float)
y_pred = model.predict(x_test)
# Print predictions
print("\nPredicted values:")
for i in range(len(x_test)):
    print(f"x = {x_test[i]}: y = {y_pred[i][0]:.2f}")
# --- 6. Visualize the Results ---
# Plot training data and predictions
plt.figure(figsize=(10, 6))
plt.scatter(x_train, y_train, color='blue', label='Training Data')
plt.plot(x_test, y_pred, color='red', label='Model Predictions', linestyle='--')
plt.title('Linear Relationship Prediction')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid()
plt.show()
# --- 7. Examine Model Weights ---
weights, biases = model.layers[0].get_weights()
print("\nModel Weights and Bias:")
print(f"Weight (slope): {weights[0][0]:.2f}")
print(f"Bias (intercept): {biases[0]:.2f}")

Explanation of Code
1. Dataset Preparation:
   - \( x \) values range from 0 to 5.
   - Corresponding \( y \) values follow the equation \( y = 2x + 1 \).
2. Model Definition:
   - A single-layer dense neural network with one neuron is created.
   - The input has one feature, so `input_shape=[1]`.
3. Model Compilation:
   - Loss function: Mean Squared Error (MSE), as it's suitable for regression tasks.
   - Optimizer: Stochastic Gradient Descent (SGD), a basic optimizer for simplicity.
4. Training:
   - The model is trained for 500 epochs, updating weights to minimize the loss.
5. Evaluation:
   - New input values are used to test the model's predictions.
   - Predictions are displayed alongside the true relationship.
6. Visualization:
   - Scatter plot of training data and a line plot of model predictions for better understanding.
7. Model Weights:
   - Extracts the learned weight (slope) and bias (intercept) from the model for interpretation.

Sample Output
Training Data:
x: [0. 1. 2. 3. 4. 5.]
y: [ 1.  3.  5.  7.  9. 11.]
Predicted Values:
x = 6.0: y = 13.00
x = 7.0: y = 15.00
x = 8.0: y = 17.00
x = 9.0: y = 19.00
x = 10.0: y = 21.00
Model Weights and Bias:
Weight (slope): 2.00
Bias (intercept): 1.00

Visualization
  • Scatter Plot: Shows the training data points.
  • Line Plot: Represents the model's predictions, matching the true relationship \( y = 2x + 1 \).
Applications
  • Regression Tasks: Predict continuous outputs, such as stock prices or sales.
  • Linear Relationships: Understand the relationship between features and outcomes.
  • TensorFlow Basics: Learn how to build and train simple models.
This program provides an excellent starting point for understanding TensorFlow's basics and its application in predictive analytics.

Comments