deeplearning_labrecord
deeplearning_labrecord
Code:
import numpy as np
import matplotlib.pyplot as plt
# Generate dataset
def generate_dataset(num_examples):
np.random.seed(42)
X = np.random.rand(num_examples, 2) * 2 - 1 # Generate random points
y = (X[:, 0] + X[:, 1] > 0).astype(int) # Label: 1 if sum > 0, else 0
return X, y
# Train perceptron
def perceptron_train(X, y, learning_rate, epochs):
num_examples, num_features = X.shape
weights = np.random.rand(num_features) # Initialize weights
bias = np.random.rand() # Initialize bias
# Generating dataset
X, y = generate_dataset(size)
# Training perceptron
weights, bias = perceptron_train(X, y, lr, epoch)
# Printing predictions
predictions = perceptron_predict(X, weights, bias)
inputs_predictions = [(X[i], int(predictions[i])) for i in range(size)]
inputs_predictions
Output:
[(array([-0.25091976, 0.90142861]), 1),
(array([0.46398788, 0.19731697]), 1),
(array([-0.68796272, -0.68801096]), 0),
(array([-0.88383278, 0.73235229]), 0),
(array([0.20223002, 0.41614516]), 1),
(array([-0.95883101, 0.9398197 ]), 0),
(array([ 0.66488528, -0.57532178]), 0),
(array([-0.63635007, -0.63319098]), 0),
(array([-0.39151551, 0.04951286]), 0),
(array([-0.13610996, -0.41754172]), 0),
(array([ 0.22370579, -0.72101228]), 0),
(array([-0.4157107 , -0.26727631]), 0),
(array([-0.08786003, 0.57035192]), 1),
(array([-0.60065244, 0.02846888]), 0),
(array([ 0.18482914, -0.90709917]), 0),
(array([ 0.2150897 , -0.65895175]), 0),
(array([-0.86989681, 0.89777107]), 0),
(array([0.93126407, 0.6167947 ]), 1),
(array([-0.39077246, -0.80465577]), 0),
(array([ 0.36846605, -0.11969501]), 1),
(array([-0.75592353, -0.00964618]), 0),
(array([-0.93122296, 0.8186408 ]), 0),
(array([-0.48244004, 0.32504457]), 0),
(array([-0.37657785, 0.04013604]), 0),
(array([ 0.09342056, -0.63029109]), 0),
(array([0.93916926, 0.55026565]), 1),
(array([0.87899788, 0.7896547 ]), 1),
(array([0.19579996, 0.84374847]), 1),
(array([-0.823015 , -0.60803428]), 0),
(array([-0.90954542, -0.34933934]), 0),
(array([-0.22264542, -0.45730194]), 0),
(array([ 0.65747502, -0.28649335]), 1),
(array([-0.43813098, 0.08539217]), 0),
(array([-0.71815155, 0.60439396]), 0),
(array([-0.85089871, 0.97377387]), 1),
(array([ 0.54448954, -0.60256864]), 0),
(array([-0.98895577, 0.63092286]), 0),
(array([0.41371469, 0.45801434]), 1),
(array([ 0.54254069, -0.8519107 ]), 0),
(array([-0.28306854,-0.76826188]),0)]
EXPERIMENT-2
Aim: Write an application to build AND, OR gates using perceptron.
Dataset Description: The inputs for the gates are binary combinations of two inputs:
These represent the possible input combinations for logic gates. The expected outputs depend
on the behavior of the logic gate (AND or OR).
Attributes:
1. Inputs:
o Binary combinations of two inputs (0 or 1).
o Shape: (4, 2).
2. Weights and Bias:
o For the AND gate:
▪ Weights: [1, 1].
▪ Bias: -1.5.
o For the OR gate:
▪ Weights: [1, 1].
▪ Bias: -0.5.
3. Outputs:
o AND Gate:
▪ Produces 1 only when both inputs are 1.
o OR Gate:
▪ Produces 1 if at least one of the inputs is 1.
Code:
import numpy as np
import matplotlib.pyplot as plt
@classmethod
def predict(cls, inputs):
return 1 if np.dot(inputs, cls.weights) + cls.bias > 0 else 0
@classmethod
def predict(cls, inputs):
return 1 if np.dot(inputs, cls.weights) + cls.bias > 0 else 0
plt.xlim(-0.5, 1.5)
plt.ylim(-0.5, 1.5)
plt.xlabel('Input 1')
plt.ylabel('Input 2')
plt.legend()
plt.grid()
plt.show()
Output:
AND Gate:
[0 0] -> 0
[0 1] -> 0
[1 0] -> 0
[1 1] -> 1
OR Gate:
[0 0] -> 0
[0 1] -> 1
[1 0] -> 1
[1 1] -> 1
EXPERIMENT-3
Aim: Write an application to implement a simple neural network.
Dataset Description:
The dataset is designed to solve the XOR problem, which is a non-linear classification
problem.
Attributes:
1. Input Features:
o Two binary values representing the inputs to the XOR gate.
2. Target Output:
o A single binary value representing the XOR output.
3. Neural Network Architecture:
o Input Layer: 2 neurons (corresponding to the two inputs).
o Hidden Layer: 4 neurons (configurable).
o Output Layer: 1 neuron (for the binary XOR output).
Code:
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
input_neurons = X.shape[1]
output_neurons = Y.shape[1]
# Forward propagation
hidden_layer_output = sigmoid(hidden_layer_activation)
predicted_output = sigmoid(output_layer_activation)
losses.append(loss)
# Backpropagation
error = Y - predicted_output
error_hidden_layer = d_predicted_output.dot(output_weights.T)
# Predictions
hidden_layer_output = sigmoid(hidden_layer_activation)
predicted_output = sigmoid(output_layer_activation)
print("Predictions:")
for i in range(len(X)):
plt.figure(figsize=(8, 6))
plt.xlabel('Input 1')
plt.ylabel('Input 2')
predictions_grid = grid_output.reshape(xx.shape)
plt.legend()
plt.colorbar(label='Output')
plt.show()
plt.figure(figsize=(8, 6))
plt.plot(losses)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.show()
Output:
Predictions:
Input: [0 0], Predicted Output: 0.0402, Actual Output: 0
Input: [0 1], Predicted Output: 0.9420, Actual Output: 1
Input: [1 0], Predicted Output: 0.9420, Actual Output: 1
Input: [1 1], Predicted Output: 0.0678, Actual Output: 0
EXPERIMENT-4
Aim: Write an application to implement a Multi-layer neural network.
Dataset Description: The dataset consists of all possible 3-bit binary combinations as
inputs and their corresponding outputs based on the behavior of an AND gate.
• Input Data:
All possible combinations of three binary digits (0 or 1).
• Output Data:
The AND gate outputs 1 if and only if all three input bits are 1. Otherwise, it outputs 0.
Attributes:
Code:
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
inputs = np.array([
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]
])
np.random.seed(42)
epochs = 1000
learning_rate = 0.1
# Forward propagation
hidden_layer_output = sigmoid(hidden_layer_input)
predicted_output = sigmoid(output_layer_input)
# Backpropagation
error_hidden_layer = d_predicted_output.dot(weights_hidden_output.T)
test_data = np.array([
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]
])
for i in range(len(test_data)):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for i in range(len(test_data)):
x, y, z = test_data[i]
color = 'r'
ax.scatter(x, y, z, c=color)
ax.set_xlabel('Input 1')
ax.set_ylabel('Input 2')
ax.set_zlabel('Input 3')
plt.show()
Output:
3-Bit AND Gate Representation:
Input: [0 0 0] Output: 0
Input: [0 0 1] Output: 0
Input: [0 1 0] Output: 0
Input: [0 1 1] Output: 0
Input: [1 0 0] Output: 0
Input: [1 0 1] Output: 0
Input: [1 1 0] Output: 0
Input: [1 1 1] Output: 0
EXPERIMENT-5
Aim: To write an application to solve real world problem.
Dataset Description: The dataset is synthetically generated and consists of 1000 samples
with the following attributes:
Attributes:
Code:
import numpy as np
import pandas as pd
np.random.seed(42)
num_samples = 1000
# Creating a DataFrame
data = pd.DataFrame({
'Temperature': temperature,
'Humidity': humidity,
'Wind_Speed': wind_speed,
'Emission_Levels': emission_levels
})
data['Emission_Levels'],
test_size=0.2,
random_state=42
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
plt.plot(y_test, y_test, color='red', label='Ideal Line') # Ideal line where Predicted = Actual
plt.legend()
plt.show()
Output: