Here's an implementation of the iris dataset classification using Levenberg-Marquardt without using any external libraries:
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def softmax(x):
exps = np.exp(x - np.max(x)) # to avoid overflow
return exps / np.sum(exps, axis=1, keepdims=True)
def feed_forward(X, weights):
# Input to hidden layer
hidden_layer = sigmoid(np.dot(X, weights['W1']) + weights['b1'])
# Hidden to output layer
output_layer = softmax(np.dot(hidden_layer, weights['W2']) + weights['b2'])
return hidden_layer, output_layer
def loss_func(weights, X, y):
_, output = feed_forward(X, weights)
predicted_y = output.argmax(axis=1)
true_labels = y.argmax(axis=1)
loss = -np.sum(np.log(output[np.arange(len(X)), true_labels]))
return loss
def gradient(weights, X, y):
hidden_layer, output_layer = feed_forward(X, weights)
predicted_y = output_layer.argmax(axis=1)
true_labels = y.argmax(axis=1)
# Gradient of loss w.r.t output layer
grad_output = output_layer
grad_output[np.arange(len(X)), true_labels] -= 1
# Gradient of loss w.r.t weights
grad_weights = {}
grad_weights['W2'] = np.dot(hidden_layer.T, grad_output)
grad_weights['b2'] = np.sum(grad_output, axis=0)
# Gradient of loss w.r.t hidden layer
grad_hidden = np.dot(grad_output, weights['W2'].T) * (1 - hidden_layer) * hidden_layer
grad_weights['W1'] = np.dot(X.T, grad_hidden)
grad_weights['b1'] = np.sum(grad_hidden, axis=0)
return grad_weights
def fit(X, y, params):
num_features = X.shape[1]
num_classes = y.shape[1]
# Initialize weights
np.random.seed(0)
weights = {
'W1': np.random.randn(num_features, params['hidden_units']),
'b1': np.zeros(params['hidden_units']),
'W2': np.random.randn(params['hidden_units'], num_classes),
'b2': np.zeros(num_classes)
}
# Train-validation split
num_samples = len(X)
num_val_samples = int(params['val_split'] * num_samples)
shuffled_indices = np.random.permutation(num_samples)
val_indices = shuffled_indices[:num_val_samples]
train_indices = shuffled_indices[num_val_samples:]
X_train, y_train = X[train_indices], y[train_indices]
X_val, y_val = X[val_indices], y[val_indices]
# Optimization using Levenberg-Marquardt
learning_rate = params['learning_rate']
num_iterations = params['num_iterations']
for i in range(num_iterations):
grad_weights = gradient(weights, X_train, y_train)
for key in weights:
weights[key] -= learning_rate * grad_weights[key]
# Evaluate on validation set
_, output = feed_forward(X_val, weights)
predicted_y = output.argmax(axis=1)
true_labels = y_val.argmax(axis=1)
val_accuracy = np.mean(predicted_y == true_labels)
print(f"Iteration {i+1}/{num_iterations} - Validation Accuracy: {val_accuracy}")
return weights
Load iris dataset
X = np.array([[5.1, 3.5, 1.4, 0.2],
[4.9, 3.0, 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2],
[5.0, 3.6, 1.4, 0.2],
[5.4, 3.9, 1.7, 0.4],
[4.6, 3.4, 1.4, 0.3],
[5.0, 3.4, 1.5, 0.2],
[4.4, 2.9, 1.4, 0.2],
[4.9, 3.1, 1.5, 0.1],
[5.4, 3.7, 1.5, 0.2],
[4.8, 3.4, 1.6, 0.2],
[4.8, 3.0, 1.4, 0.1],
[4.3, 3.0, 1.1, 0.1],
[5.8, 4.0, 1.2, 0.2],
[5.7, 4.4, 1.5, 0.4],
[5.4, 3.9, 1.3, 0.4],
[5.1, 3.5, 1.4, 0.3],
[5.7, 3.8, 1.7, 0.3],
[5.1, 3.8, 1.5, 0.3],
[5.4, 3.4, 1.7, 0.2],
[5.1, 3.7, 1.5, 0.4],
[4.6, 3.6, 1.0, 0.2],
[5.1, 3.3, 1.7, 0.5],
[4.8, 3.4, 1.9, 0.2],
[5.0, 3.0, 1.6, 0.2],
[5.0, 3.4, 1.6, 0.4],
[5.2, 3.5, 1.5, 0.2],
[5.2, 3.4, 1.4, 0.2],
[4.7, 3.2, 1.6, 0.2],
[4.8, 3.1, 1.6, 0.2],
[5.4, 3.4, 1.5, 0.4],
[5.2, 4.1, 1.5, 0.1],
[5.5, 4.2, 1.4, 0.2],
[4.9, 3.1, 1.5, 0.2],
[5.0, 3.2, 1.2, 0.2],
[5.5, 3.5, 1.3, 0.2],
[4.9, 3.1, 1.5, 0.1],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