import numpy as np
import pandas as pd
from [Link] import load_iris
from sklearn.model_selection import train_test_split
from [Link] import OneHotEncoder, StandardScaler
from [Link] import accuracy_score
# Load the Iris dataset
iris = load_iris()
X = [Link]
y = [Link]
# One-hot encode the target labels
encoder = OneHotEncoder(sparse_output=False)
y = encoder.fit_transform([Link](-1, 1))
# Standardize the features
scaler = StandardScaler()
X = scaler.fit_transform(X)
# Split the dataset 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)
# Define the neural network structure
input_size = [Link][1]
hidden_size = 5
output_size = [Link][1]
learning_rate = 0.01
epochs = 10000
# Initialize weights and biases
[Link](42)
W1 = [Link](input_size, hidden_size)
b1 = [Link]((1, hidden_size))
W2 = [Link](hidden_size, output_size)
b2 = [Link]((1, output_size))
# Activation function (sigmoid) and its derivative
def sigmoid(x):
return 1 / (1 + [Link](-x))
def sigmoid_derivative(x):
return x * (1 - x)
# Forward pass
def forward(X):
z1 = [Link](X, W1) + b1
a1 = sigmoid(z1)
z2 = [Link](a1, W2) + b2
a2 = sigmoid(z2)
return a1, a2
# Backward pass
def backward(X, y, a1, a2):
global W1, b1, W2, b2
m = [Link][0]
dz2 = a2 - y
dW2 = [Link](a1.T, dz2) / m
db2 = [Link](dz2, axis=0, keepdims=True) / m
dz1 = [Link](dz2, W2.T) * sigmoid_derivative(a1)
dW1 = [Link](X.T, dz1) / m
db1 = [Link](dz1, axis=0, keepdims=True) / m
W1 -= learning_rate * dW1
b1 -= learning_rate * db1
W2 -= learning_rate * dW2
b2 -= learning_rate * db2
# Training the neural network
for epoch in range(epochs):
a1, a2 = forward(X_train)
backward(X_train, y_train, a1, a2)
if epoch % 1000 == 0:
loss = [Link]([Link](y_train - a2))
print(f'Epoch {epoch}, Loss: {loss:.4f}')
# Testing the neural network
_, a2_test = forward(X_test)
predictions = [Link](a2_test, axis=1)
y_test_labels = [Link](y_test, axis=1)
accuracy = accuracy_score(y_test_labels, predictions)
print(f'Accuracy: {accuracy * 100:.2f}%')
# Classify a new sample
new_sample = [Link]([[5.1, 3.5, 1.4, 0.2]]) # Example input
new_sample = [Link](new_sample)
_, new_sample_output = forward(new_sample)
new_sample_prediction = [Link](new_sample_output, axis=1)
predicted_class = iris.target_names[new_sample_prediction[0]]
print(f'The new sample {new_sample} is classified as: {predicted_class}')