Design a neural network in Python with two hidden layers to solve a given classification…
- User
Design a neural network in Python with two hidden layers to solve a given classification task.
Assistant
Design a neural network in Python with two hidden layers to solve a given classification task.
Plan:
tensorflow, numpy, and sklearn utilities for data handling.sklearn.datasets.make_classification. This ensures the code is runnable immediately.tf.keras.models.Sequential.
Here is a complete solution using Python and the TensorFlow/Keras library. This example generates a synthetic dataset, builds a model with two hidden layers, trains it, and evaluates the results.
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 1. Generate a synthetic dataset
# We create 1000 samples with 20 features each, belonging to 2 classes (0 or 1).
X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)
# 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)
# 2. Define the Neural Network Architecture
model = Sequential()
# First Hidden Layer
# 'units' is the number of neurons. 'input_dim' matches the number of features (20).
# 'relu' is the standard activation function for hidden layers.
model.add(Dense(units=64, activation='relu', input_dim=X_train.shape[1]))
# Second Hidden Layer
# Note: We don't need input_dim here; Keras automatically connects it to the previous layer.
model.add(Dense(units=32, activation='relu'))
# Output Layer
# We use 1 unit with 'sigmoid' activation for binary classification (output is probability 0-1).
model.add(Dense(units=1, activation='sigmoid'))
# 3. Compile the Model
model.compile(optimizer='adam', # Standard optimizer
loss='binary_crossentropy', # Loss function for binary classification
metrics=['accuracy'])
# 4. Train the Model
print("Training model...")
model.fit(X_train, y_train, e