# -*- coding: utf-8 -*-
"""3A.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1114df2JayPBPVkfVqx5CByZl4-4jlL0k
"""

import pandas as pd
import numpy as np
import tensorflow as tf
import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score

df = pd.read_csv('heart.csv')
print(df.head())

X = df.drop(columns=['output'])  # Features
y = df['output']  # Target variable

X.fillna(X.mean(), inplace=True)

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

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

model = Sequential()

model.add(Dense(64, input_dim=X_train.shape[1], activation='relu'))

model.add(Dense(32, activation='relu'))

model.add(Dense(16, activation='relu'))

model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer=Adam(), loss='binary_crossentropy', metrics=['accuracy'])

model.fit(X_train, y_train, epochs=100, batch_size=32, validation_data=(X_test, y_test))

loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Loss: {loss}")
print(f"Test Accuracy: {accuracy}")

y_pred = (model.predict(X_test) > 0.5).astype(int)  # Threshold at 0.5 for binary output
print(f"Manual Accuracy: {accuracy_score(y_test, y_pred)}")

print(f"Predicted Labels: {y_pred[:10]}")  # Show the first 10 predictions
print(f"True Labels: {y_test.values[:10]}")  # Show the first 10 actual labels

from sklearn.metrics import accuracy_score
print(f"Manual Accuracy: {accuracy_score(y_test, y_pred)}")















#   mushrooms

import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.initializers import GlorotUniform
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split

# 1. Load and Preprocess Data
df = pd.read_csv("C:/Users/admin/Desktop/MSCDS SEM IV/DL/Datasets/mushrooms.csv")

label_encoder = LabelEncoder()
df["class"] = label_encoder.fit_transform(df["class"])

df_encoded = df.apply(LabelEncoder().fit_transform)

# 2. Split Features and Target
X = df_encoded.drop("class", axis=1)
y = df_encoded["class"]

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

# 3. Set Seeds for Reproducibility
np.random.seed(42)
tf.random.set_seed(42)

# 4. Define the Model Architecture
model = Sequential([
    Dense(32, activation='relu', input_shape=(X_train.shape[1],), kernel_initializer=GlorotUniform()), # Hidden Layer 1
    Dense(16, activation='relu', kernel_initializer=GlorotUniform()), # Hidden Layer 2
    Dense(16, activation='relu', kernel_initializer=GlorotUniform()), # Hidden Layer 3
    Dense(8, activation='relu', kernel_initializer=GlorotUniform()),  # Hidden Layer 4
    Dense(8, activation='relu', kernel_initializer=GlorotUniform()),  # Hidden Layer 5
    Dense(1, activation='sigmoid', kernel_initializer=GlorotUniform()) # Output Layer
])

# 5. Summary, Compile, and Train
model.summary()

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(X_train, y_train, epochs=50, batch_size=32, verbose=1, validation_data=(X_test, y_test))

# 6. Evaluate and Predict
loss, accuracy = model.evaluate(X_test, y_test, verbose=1)
print(f"\nModel Evaluation - Loss: {loss:.4f}, Accuracy: {accuracy:.4f}")

predictions = model.predict(X_test)
binary_predictions = (predictions > 0.5).astype(int)

# 7. Display Sample Predictions
print("\nSample Predictions:")
print("Actual | Predicted")
for i in range(10):  # Show only first 10 predictions
    print(f"  {y_test.iloc[i]}    |    {binary_predictions[i][0]}")
