Introduction to Deep Learning with Keras: Building and Training a Simple Neural Network
This tutorial introduces the fundamentals of deep learning, covering neural network basics, Keras fundamentals, and provides a step‑by‑step Python example that loads the Iris dataset, preprocesses data, builds, compiles, trains, evaluates, visualizes, and predicts with a simple neural network model.
Goal : Understand the basic concepts of deep learning.
Learning Content : Neural network basics, Keras basics, and a hands‑on practice building a simple neural network with Keras.
Code Example :
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
# Load example dataset (Iris)
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['target'] = iris.target
print(f"Example dataset:
{df.head()}")
# Split dataset into training and test sets
X = df.drop('target', axis=1)
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(f"Training features:
{X_train.head()}")
print(f"Test features:
{X_test.head()}")
print(f"Training labels:
{y_train.head()}")
print(f"Test labels:
{y_test.head()}")
# Standardize features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Define a simple neural network model
model = Sequential()
model.add(Dense(10, input_dim=4, activation='relu')) # Input layer and first hidden layer
model.add(Dense(10, activation='relu')) # Second hidden layer
model.add(Dense(3, activation='softmax')) # Output layer
model.summary()
# Compile the model
model.compile(optimizer=Adam(learning_rate=0.01), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
history = model.fit(X_train_scaled, y_train, epochs=50, batch_size=10, validation_split=0.2)
# Evaluate the model on the test set
loss, accuracy = model.evaluate(X_test_scaled, y_test)
print(f"Test loss: {loss:.4f}")
print(f"Test accuracy: {accuracy:.4f}")
# Plot training and validation loss and accuracy
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
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.title('Training and Validation Loss')
plt.subplot(1, 2, 2)
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.title('Training and Validation Accuracy')
plt.show()
# Predict with the model
y_pred = model.predict(X_test_scaled)
y_pred_classes = np.argmax(y_pred, axis=1)
print(f"First few predictions:
{y_pred_classes[:10]}")
print(f"First few true labels:
{y_test[:10].values}")Practice : The same code is repeated as a hands‑on exercise, allowing learners to run the full workflow from data loading to model evaluation and prediction.
Summary : After completing the exercise, you should understand neural network fundamentals and be able to build, train, evaluate, and visualize a simple Keras model, ready to apply these skills to real projects.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
