mail@pastecode.io avatar
2 months ago
1.8 kB
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler

# Load iris dataset
iris = load_iris()
X, y = iris.data[:, :2], iris.target

# Select only the first two classes for binary classification
X = X[y != 2]
y = y[y != 2]

# 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)

# Standardize the features (optional but often recommended for logistic regression)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# Create a logistic regression model
model = LogisticRegression()

# Train the model
model.fit(X_train, y_train)

# Make predictions on the test set
y_pred = model.predict(X_test)

# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")

# Define the sigmoid function
def sigmoid(x):
    return 1 / (1 + np.exp(-x))

# Values for creating the sigmoid function plot
x_values_sigmoid = np.linspace(-7, 7, 300)
y_values_sigmoid = sigmoid(x_values_sigmoid)

# Plot the sigmoid function
plt.plot(x_values_sigmoid, y_values_sigmoid, label='Sigmoid Function', color='red', linestyle='--')

# Plot the scatter plot of predicted probabilities
plt.scatter(X_test[:, 0], y_pred, label='Predicted Probabilities', marker='o', c=y_test, cmap='coolwarm', alpha=0.7)

plt.xlabel('Feature 1')
plt.ylabel('Predicted Probabilities')
plt.title('Scatter Plot of Predicted Probabilities and Sigmoid Function on Binary Iris Dataset')
Leave a Comment