import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifier

# Load from CSV
df = pd.read_csv('data_2d_classification.csv')
X = df[['x1', 'x2']].values
y = df['label'].values

# Split for visualization
N = X.shape[0]
X1 = X[:N//2]
X2 = X[N//2:]

# Neural network classifier
clf = MLPClassifier(hidden_layer_sizes=(10,), alpha=0.01, max_iter=3000, random_state=1)
clf.fit(X, y)

# Boundary grid
h = 0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
Z = Z.reshape(xx.shape)

plt.figure(figsize=(8, 6))
plt.contourf(xx, yy, Z, alpha=0.3, levels=np.linspace(0, 1, 11), cmap=plt.cm.RdBu)
plt.scatter(X1[:, 0], X1[:, 1], color='blue', label='Group 0', edgecolor='k')
plt.scatter(X2[:, 0], X2[:, 1], color='red', label='Group 1', edgecolor='k')
plt.contour(xx, yy, Z, levels=[0.5], linewidths=2, colors='k')
plt.legend()
plt.title('Decision Boundary of 2D Classification (MLPClassifier)')
plt.xlabel('x1')
plt.ylabel('x2')
plt.tight_layout()
plt.show()
