Untitled

Anonymous
plain_text
09/28/2026 6:27 AM
2.4 KB
4
Indexable
import pandas as pd
import numpy as np


df = pd.read_csv("iris.csv")

df = df[df["variety"].isin(["Setosa", "Versicolor"])]


X = df[
    [
        "sepal.length",
        "sepal.width",
        "petal.length",
        "petal.width"
    ]
].values

y = df["variety"].map({
    "Setosa": 0,
    "Versicolor": 1
}).values

np.random.seed(42)

indices = np.random.permutation(len(X))

test_size = int(0.2 * len(X))

test_indices = indices[:test_size]
train_indices = indices[test_size:]

X_train = X[train_indices]
X_test = X[test_indices]

y_train = y[train_indices]
y_test = y[test_indices]



X_train_bias = np.c_[
    np.ones(X_train.shape[0]),
    X_train
]

X_test_bias = np.c_[
    np.ones(X_test.shape[0]),
    X_test
]

weights = np.zeros(X_train_bias.shape[1])


def sigmoid(z):
    return 1 / (1 + np.exp(-z))


learning_rate = 0.01
epochs = 10000



for i in range(epochs):

   
    z = np.dot(X_train_bias, weights)
    predictions = sigmoid(z)

    # Calculate gradient
    gradient = np.dot(
        X_train_bias.T,
        (predictions - y_train)
    ) / len(y_train)

    # Update weights
    weights = weights - learning_rate * gradient




probabilities = sigmoid(
    np.dot(X_test_bias, weights)
)

y_pred = (probabilities >= 0.5).astype(int)



print("Actual values:")
print(
    np.where(y_test == 0, "Setosa", "Versicolor")
)

print("\nPredicted values:")
print(
    np.where(y_pred == 0, "Setosa", "Versicolor")
)



accuracy = np.mean(y_pred == y_test)

print("\nAccuracy:")
print(accuracy)




confusion = np.zeros((2, 2), dtype=int)

for actual, predicted in zip(y_test, y_pred):
    confusion[actual][predicted] += 1

print("\nConfusion Matrix:")
print(confusion)


Editor is loading...
Leave a Comment