Menu

Building a Neural Network with Python

Building a Neural Network with Python

You can build a simple neural network using TensorFlow and Keras. Keras provides a high-level interface for defining, training, and evaluating neural networks.

Step 1: Install the Required Libraries

Run the following command:

pip install tensorflow scikit-learn

Step 2: Load Data and Train a Model

The following example uses the Iris dataset to classify flowers into three species based on four numerical features.

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow import keras
# Load the dataset
iris = load_iris()
X = iris.data
y = iris.target
# Split the data before fitting preprocessing steps
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)
# Standardize features using training data only
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Build the neural network
model = keras.Sequential([
keras.layers.Input(shape=(4,)),
keras.layers.Dense(16, activation="relu"),
keras.layers.Dense(8, activation="relu"),
keras.layers.Dense(3, activation="softmax")
])
# Configure the training process
model.compile(
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
# Train the model
model.fit(
X_train,
y_train,
epochs=50,
batch_size=16,
verbose=0
)
# Evaluate on unseen test data
loss, accuracy = model.evaluate(
X_test,
y_test,
verbose=0
)
print(f"Test accuracy: {accuracy:.2%}")

Understanding the Code

  • Input(shape=(4,)) defines four input features.
  • The two Dense layers contain hidden neurons that learn patterns.
  • ReLU provides nonlinear transformations in the hidden layers.
  • The final layer contains three outputs, one for each flower class.
  • Softmax converts the output scores into class probabilities.
  • sparse_categorical_crossentropy is appropriate because the target labels are integer class IDs.
  • The test dataset evaluates performance on examples not used for training.

The exact test accuracy can vary with the data split, initialization, and training process. A single test result does not guarantee that the model will perform equally well on new real-world data.


Artificial Intelligence Tutorial

VA

Vishalini A



Learn via Video Course

Artificial Intelligence and Machine Learning Course Logo

Artificial Intelligence and Machine Learning Course

55 hrs



Get in Touch For Details