# -*- coding: utf-8 -*-
"""Using a deep feed forward network with two hidden layers for performing  linear regression and predicting values.

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1Cef6TY4UreI4bjAEovxQ6zb6GHHvCzAr
"""


#California housing

import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# Load and split data
data = fetch_california_housing()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Build the model
model = models.Sequential([
    layers.Dense(32, activation='relu', input_shape=(X_train_scaled.shape[1],)),
    layers.Dense(16, activation='relu'),
    layers.Dense(1)
])

# Compile and define Early Stopping
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
early_stopping = tf.keras.callbacks.EarlyStopping(patience=5, restore_best_weights=True)

# Train the model and capture the history
history = model.fit(X_train_scaled, y_train, epochs=100, batch_size=16,
          validation_split=0.2, callbacks=[early_stopping], verbose=0)

# Evaluate
loss, mae = model.evaluate(X_test_scaled, y_test, verbose=0)
print(f"Test MAE: {mae:.4f}")

y_pred = model.predict(X_test_scaled)

print("\nTrue vs Predicted Values:")
for i in range(20):
    print(f"True: {y_test[i]:.4f}, Predicted: {y_pred[i][0]:.4f}")

plt.figure(figsize=(8, 5))

# Changed 'blue' to 'yellow' per your request
plt.scatter(y_test, y_pred, color='yellow', alpha=0.6)

# This adds the red dashed line for reference (perfect predictions)
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], color='red', linestyle='--')

plt.title("True vs Predicted Values (California Housing)")
plt.xlabel("True Values")
plt.ylabel("Predicted Values")
plt.show()

plt.figure(figsize=(8, 5))
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Training and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()





#CAR DATA SET 

import tensorflow as tf
from tensorflow.keras import layers, models, callbacks
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import numpy as np
import os

# Reproducibility
tf.random.set_seed(42)
np.random.seed(42)
os.environ['PYTHONHASHSEED'] = '42'

# Load data
data = pd.read_csv('car_price_dataset.csv')

# Select numeric features and target
X = data[['Engine_Size', 'Mileage', 'Doors', 'Owner_Count']].copy()
y = data['Price'].copy()

# Handle missing values (simple strategy)
X = X.fillna(X.median())
y = y.fillna(y.median())

# Train/test split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Scale features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# Build model
model = models.Sequential([
    layers.Input(shape=(X_train.shape[1],)),
    layers.Dense(64, activation='relu'),
    layers.Dense(32, activation='relu'),
    layers.Dense(1, activation='linear')
])

model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_absolute_error'])

# Callbacks
es = callbacks.EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)

# Train
history = model.fit(
    X_train, y_train,
    epochs=100,
    batch_size=32,
    validation_split=0.2,
    callbacks=[es],
    verbose=1
)

# Evaluate
test_loss, test_mae = model.evaluate(X_test, y_test, verbose=1)
print(f"Test Loss (MSE): {test_loss}")
print(f"Test MAE: {test_mae}")

# Predict
y_pred = model.predict(X_test).flatten()

# Plot Actual vs Predicted
plt.figure(figsize=(8, 6))
plt.scatter(y_test, y_pred, alpha=0.6)
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--')
plt.xlabel("Actual Values")
plt.ylabel("Predicted Values")
plt.title("Actual vs Predicted Values")
plt.tight_layout()
plt.show()






# coffee Shop

import tensorflow as tf
from tensorflow.keras import layers, models
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.layers import Dense
import numpy as np 

data = pd.read_csv('/content/coffee_shop.csv')

data.head()

X = data.drop(columns=['Daily_Revenue'])
y = data['Daily_Revenue']

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 = models.Sequential()
model.add(Dense(64, input_dim=X_train.shape[1], activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(1, activation='linear'))

model.compile(optimizer='adam', loss='mean_squared_error')

model.fit(X_train, y_train, epochs=100, batch_size=32, validation_split=0.2)

y_pred = model.predict(X_test).ravel() 
y_test_arr = np.asarray(y_test).ravel() 

import matplotlib.pyplot as plt

plt.scatter(y_test_arr, y_pred, color='yellow')

plt.xlabel("Actual Values")
plt.ylabel("Predicted Values")
plt.title("Actual vs Predicted Values (Yellow Scatter)")
plt.show()

