AI Tutorial 93: Building a Neural Network Model from Scratch with Python151
Introduction
In this tutorial, we will create a simple neural network model from scratch using Python. The model will learn to classify images of handwritten digits from the MNIST dataset. While building the model, we will discuss the underlying concepts of neural networks in detail.
What are Neural Networks?
Neural networks are a type of machine learning algorithm inspired by the human brain. They consist of layers of interconnected nodes, called neurons, which process information and learn from data.
Simple Neural Network Architecture
Our neural network will have three layers:
Input layer: Receives the input data (images)
Hidden layer: Processes the input and learns patterns
Output layer: Produces the final output (digit classification)
Creating the Neural Network
We will use NumPy and matplotlib libraries for matrix operations and visualization.
1. Initialize the Network Parameters
We start by defining the network parameters:```python
import numpy as np
# Number of neurons in the hidden layer
hidden_size = 100
# Number of neurons in the output layer (10 digits)
output_size = 10
# Input data shape (28x28 grayscale images)
input_shape = (28, 28)
# Initialize weights and biases randomly
w1 = (input_shape[0] * input_shape[1], hidden_size)
b1 = ((1, hidden_size))
w2 = (hidden_size, output_size)
b2 = ((1, output_size))
```
2. Define the Forward Pass
The forward pass calculates the network's output given an input:```python
def forward_pass(x):
# Reshape the input to a flat vector
x = ()
# Calculate the hidden layer activation
h = ((x, w1) + b1)
# Calculate the output layer activation
out = (h, w2) + b2
return out
```
3. Define the Loss Function
The loss function measures the error between the network's output and the expected output:```python
def loss_function(y_pred, y_true):
# Calculate the cross-entropy loss
return -(y_true * (y_pred))
```
4. Update the Network Parameters
We use gradient descent to minimize the loss function:```python
def update_parameters(x, y, lr=0.1):
# Calculate the gradients
grad_w1 = (x.T, (((x, w1) + b1) - y))
grad_b1 = ((((x, w1) + b1) - y), axis=0)
grad_w2 = (h.T, (out - y))
grad_b2 = ((out - y), axis=0)
# Update the parameters
w1 -= lr * grad_w1
b1 -= lr * grad_b1
w2 -= lr * grad_w2
b2 -= lr * grad_b2
```
Training the Neural Network
We will load the MNIST dataset and train our network for 10 epochs:```python
from import mnist
# Load the MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Normalize the input data
x_train = ("float32") / 255
x_test = ("float32") / 255
# One-hot encode the target labels
y_train = (10)[y_train]
y_test = (10)[y_test]
# Train the neural network
for epoch in range(10):
for i in range(len(x_train)):
# Forward pass and calculate the loss
out = forward_pass(x_train[i])
loss = loss_function(out, y_train[i])
# Backpropagate and update the parameters
update_parameters(x_train[i], y_train[i])
# Evaluate the model on the test set
accuracy = ((forward_pass(x_test), axis=1) == y_test) / len(x_test)
print(f"Epoch {epoch + 1}: Accuracy = {accuracy}")
```
Conclusion
Congratulations! You have successfully built and trained a simple neural network from scratch. This is just a basic example, and neural networks can be much more complex and used to solve a wide range of real-world problems.
2025-02-08
Previous:Precipitation Data Download Tutorial: A Comprehensive Guide
![A Comprehensive Guide to Essential Cooking Techniques](https://cdn.shapao.cn/images/text.png)
A Comprehensive Guide to Essential Cooking Techniques
https://zeidei.com/lifestyle/55043.html
![Text Graffiti Tutorial: Transform Your Phone into a Street Art Masterpiece](https://cdn.shapao.cn/images/text.png)
Text Graffiti Tutorial: Transform Your Phone into a Street Art Masterpiece
https://zeidei.com/technology/55042.html
![Mastering Personal Finance: The Complete Guide for Beginners](https://cdn.shapao.cn/images/text.png)
Mastering Personal Finance: The Complete Guide for Beginners
https://zeidei.com/lifestyle/55041.html
![Video Tutorials for Data Structures](https://cdn.shapao.cn/images/text.png)
Video Tutorials for Data Structures
https://zeidei.com/technology/55040.html
![How to Get Started with Tencent Financial Management](https://cdn.shapao.cn/images/text.png)
How to Get Started with Tencent Financial Management
https://zeidei.com/lifestyle/55039.html
Hot
![A Beginner‘s Guide to Building an AI Model](https://cdn.shapao.cn/images/text.png)
A Beginner‘s Guide to Building an AI Model
https://zeidei.com/technology/1090.html
![DIY Phone Case: A Step-by-Step Guide to Personalizing Your Device](https://cdn.shapao.cn/images/text.png)
DIY Phone Case: A Step-by-Step Guide to Personalizing Your Device
https://zeidei.com/technology/1975.html
![Odoo Development Tutorial: A Comprehensive Guide for Beginners](https://cdn.shapao.cn/images/text.png)
Odoo Development Tutorial: A Comprehensive Guide for Beginners
https://zeidei.com/technology/2643.html
![Android Development Video Tutorial](https://cdn.shapao.cn/images/text.png)
Android Development Video Tutorial
https://zeidei.com/technology/1116.html
![Database Development Tutorial: A Comprehensive Guide for Beginners](https://cdn.shapao.cn/images/text.png)
Database Development Tutorial: A Comprehensive Guide for Beginners
https://zeidei.com/technology/1001.html