mlp1 ="""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.read_csv('tested.csv')

numerical_column = 'Age'
data = df[numerical_column]

mean_value = data.mean()
median_value = data.median()
mode_value = data.mode()[0]
std_dev = data.std()
variance = data.var()
data_range = data.max() - data.min()

print(f'Mean: {mean_value}')
print(f'Median: {median_value}')
print(f'Mode: {mode_value}')
print(f'Standard Deviation: {std_dev}')
print(f'Variance: {variance}')
print(f'Range: {data_range}')

plt.figure(figsize=(10, 6))
sns.histplot(data, kde=True)
plt.title('Histogram of ' + numerical_column)
plt.xlabel(numerical_column)
plt.ylabel('Frequency')

plt.figure(figsize=(10, 6))
sns.boxplot(x=data)
plt.title('Boxplot of ' + numerical_column)
plt.show()

Q1 = data.quantile(0.25)
Q3 = data.quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
outliers = data[(data < lower_bound) | (data > upper_bound)]
print(f'Outliers: {outliers}')

categorical_column = 'Embarked'
category_counts = df[categorical_column].value_counts()
print(category_counts)

plt.figure(figsize=(10, 6))
sns.barplot(x=category_counts.index, y=category_counts.values)
plt.title('Bar Chart of ' + categorical_column)
plt.xlabel(categorical_column)
plt.ylabel('Frequency')
plt.show()

plt.figure(figsize=(10, 6))
category_counts.plot.pie(autopct='%1.1f%%')
plt.title('Pie Chart of ' + categorical_column)
plt.ylabel('')
plt.show()
"""

mlp2="""
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import datasets

iris = datasets.load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)

x_column = 'sepal length (cm)'
y_column = 'sepal width (cm)'

plt.figure(figsize=(8, 6))
plt.scatter(df[x_column], df[y_column], color='b', alpha=0.5)
plt.title(f'Scatter plot of {x_column} vs {y_column}')
plt.xlabel(x_column)
plt.ylabel(y_column)
plt.show()

pearson_corr = df[x_column].corr(df[y_column])
print(f"Pearson correlation coefficient between {x_column} and {y_column}: {pearson_corr}")

cov_matrix = df.cov()
print("\nCovariance matrix:\n", cov_matrix)

corr_matrix = df.corr()
print("\nCorrelation matrix:\n", corr_matrix)

plt.figure(figsize=(10, 8))
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', linewidths=0.5)
plt.title('Correlation Matrix Heatmap')
plt.show()
"""

mlp3 = """
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

iris = datasets.load_iris()
X = iris.data
y = iris.target

df = pd.DataFrame(X, columns=iris.feature_names)
df['target'] = y

print('Original data (top 3 rows):')
print(X[:3])

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)

X_pca[:, 1] *= -1

print("\nPCA transformed data (top 3 rows):")
print(X_pca[:3])

df_pca = pd.DataFrame(X_pca, columns=['PCA1', 'PCA2'])
df_pca['target'] = y

print("\nPCA DataFrame head:")
print(df_pca.head())

plt.figure(figsize=(10, 7))
colors = ['r', 'g', 'b']
labels = iris.target_names

for target, color in zip(df_pca['target'].unique(), colors):
    subset = df_pca[df_pca['target'] == target]
    plt.scatter(subset['PCA1'], subset['PCA2'],
                color=color, label=labels[target])

plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.title('PCA of Iris Dataset (4D → 2D)')
plt.legend()
plt.grid()

plt.show()
"""

mlp4 = """
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, f1_score
from collections import Counter

def euclidean_distance(x1, x2):
    return np.sqrt(np.sum((x1 - x2) ** 2))

class KNN:
    def __init__(self, k=3, weighted=False):
        self.k = k
        self.weighted = weighted

    def fit(self, X_train, y_train):
        self.X_train = X_train
        self.y_train = y_train

    def predict(self, X_test):
        predictions = [self._predict(x) for x in X_test]
        return np.array(predictions)

    def _predict(self, x):
        distances = [euclidean_distance(x, x_train) for x_train in self.X_train]
        k_indices = np.argsort(distances)[:self.k]
        k_nearest_labels = [self.y_train[i] for i in k_indices]

        if self.weighted:
            weights = [1 / (distances[i] ** 2 + 1e-5) for i in k_indices]
            class_votes = {}
            for label, weight in zip(k_nearest_labels, weights):
                class_votes[label] = class_votes.get(label, 0) + weight
            return max(class_votes, key=class_votes.get)
        else:
            most_common = Counter(k_nearest_labels).most_common(1)
            return most_common[0][0]

iris = load_iris()
X, y = iris.data, iris.target

scaler = StandardScaler()
X = scaler.fit_transform(X)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

k_values = [1, 3, 5]

for k in k_values:
    knn = KNN(k=k, weighted=False)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    acc = accuracy_score(y_test, y_pred)
    f1 = f1_score(y_test, y_pred, average='weighted')
    print(f'k={k}, Regular k-NN -> Accuracy: {acc:.4f}, F1-score: {f1:.4f}')

for k in k_values:
    knn_weighted = KNN(k=k, weighted=True)
    knn_weighted.fit(X_train, y_train)
    y_pred_weighted = knn_weighted.predict(X_test)
    acc_weighted = accuracy_score(y_test, y_pred_weighted)
    f1_weighted = f1_score(y_test, y_pred_weighted, average='weighted')
    print(f'k={k}, Weighted k-NN -> Accuracy: {acc_weighted:.4f}, F1-score: {f1_weighted:.4f}')
"""

def print_programs():
    print("========================")
    print("      PROGRAM 1         ")
    print("========================")
    print(mlp1)
    
    print("\n\n========================")
    print("      PROGRAM 2         ")
    print("========================")
    print(mlp2)
    print("========================")
    print("      PROGRAM 3         ")
    print("========================")
    print(mlp3)
    
    print("\n\n========================")
    print("      PROGRAM 4         ")
    print("========================")
    print(mlp4)

if __name__ == "__main__":
    print_programs()