EXE 1 DL
EXE 1 DL
Solving the XOR problem using a Deep Neural Network (DNN) typically involves
the following steps. These steps can be translated into a lab program depending on the
specific programming framework you are using (e.g., TensorFlow, PyTorch, etc.).
XOR (exclusive OR) is a logical operation that outputs true or 1 only when the
inputs are different.
python
import numpy as np
# XOR inputs
X = np.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])
# XOR outputs
y = np.array([[0],
[1],
[1],
[0]])
Create a neural network with at least one hidden layer. A typical architecture
for solving XOR would be:
o Input layer with 2 neurons (corresponding to the two inputs of XOR)
o 1 hidden layer with a few neurons (typically 2-4 neurons)
o Output layer with 1 neuron (for the XOR output)
Define the activation functions. Typically, sigmoid or tanh is used for the
hidden layers, and sigmoid for the output layer.
python
Copy code
from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import
Dense
model = Sequential()
model.add(Dense(4, input_dim=2, activation='tanh')) # Hidden layer
model.add(Dense(1, activation='sigmoid')) # Output layer
Define the loss function and optimizer. For binary classification problems like
XOR, use binary cross-entropy loss.
An optimizer like stochastic gradient descent (SGD) or Adam can be used.
python
Copy code
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
python
Copy code
model.fit(X, y, epochs=1000, verbose=1)
After training, evaluate the model's performance on the training data or new
data.
Check the accuracy to see if the model has learned the XOR function.
python
Copy code
_, accuracy = model.evaluate(X, y)print(f'Accuracy: {accuracy * 100:.2f}%')
8. Make Predictions
python
Copy code
model.save('xor_model.h5')
python
Copy code
import numpy as npfrom tensorflow.keras.models import Sequentialfrom
tensorflow.keras.layers import Dense
# XOR inputs and outputs
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# Define the model
model = Sequential()
model.add(Dense(4, input_dim=2, activation='tanh')) # Hidden layer with 4 neurons
model.add(Dense(1, activation='sigmoid')) # Output layer
# Compile the model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Train the model
model.fit(X, y, epochs=1000, verbose=1)
# Evaluate the model
_, accuracy = model.evaluate(X, y)print(f'Accuracy: {accuracy * 100:.2f}%')
# Make predictions
predictions = model.predict(X)print(f'Predictions:\n{predictions}')
# Save the model
model.save('xor_model.h5')
This code can be used in a lab environment to solve the XOR problem using a Deep
Neural Network.