#EDA
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv")

print("mean", df['Fare'].mean(numeric_only= True))

print("med", df['Fare'].median(numeric_only= True))

print("mode", df['PassengerId'].mode().iloc[0])

print("skew", df['Fare'].skew(numeric_only= True))

print("variance:", df['Fare'].var(numeric_only=True))
print("std:", df['Fare'].std(numeric_only=True))

print("range", df['Fare'].max(numeric_only=True)-df['Fare'].min(numeric_only=True))

print("Q1", df['Fare'].quantile(0.25))
print("Q2", df['Fare'].quantile(0.50))
print("Q3", df['Fare'].quantile(0.75))

print('IQR',df['Fare'].quantile(0.75)-df['Fare'].quantile(0.25))

print("kurtosis", df['Fare'].kurt(numeric_only=True))

#----------------------------------------------------
#HANDLING OUTLIERS
Q1 = df['Fare'].quantile(0.25)
Q3 = df['Fare'].quantile(0.75)
IQR = Q3 - Q1

df = df[(df['Fare'] >= Q1 - 1.5*IQR) & (df['Fare'] <= Q3 + 1.5*IQR)]

#----------------------------------------------------
#MISSING VALUES
# see missing values
df.isnull().sum()
df = df.fillna(df.mean(numeric_only=True))    #  sabse best shortcut
# Drop rows with missing values
ndf=df.dropna() #stored the new dataset after drop in ndf variable
df['Embarked'].fillna(df['Fare'].mean(numeric_only=True), inplace=True)   #to fill nan values with some value(not needed coz apan drop kar rhe sab nan rows ko)
# shape of graph
df.shape   # df (original) use kiya h yaha
ndf.shape  # ndf ko use kiya h yaha so rows are dropped (final output ndf ka hai )

#----------------------------------------------------
#CORRELATION
# Identify correlation between total_bill and tip
df[['Fare','Pclass']].corr()

#----------------------------------------------------
#PLOTS
import seaborn as sns

sns.histplot(df['Age'])
sns.histplot(x=df["Sex"],y=df["Fare"])
sns.boxplot(df["Fare"])
sns.heatmap(df.corr(numeric_only=True), annot=True)
sns.scatterplot(x=df['Age'], y=df['Fare'])
sns.violinplot(x=df['Sex'],y=df['Fare'])

#----------------------------------------------------
#LOGISTIC REG MODEL
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

X = df[['Pclass','Age','SibSp','Parch','Fare']]  # isme humesha x me normal numerical values daalo
y = df['Survived']   # y me 0, 1 wale daal    if incase nai hoga 0,1 then apply as  ---->
# from sklearn.preprocessing import LabelEncoder -----> le = LabelEncoder() ---->  y = le.fit_transform(df['species'])

X = X.fillna(X.mean())

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

# Model
model = LogisticRegression()
model.fit(X_train, y_train)

# Prediction
y_pred = model.predict(X_test)

# Metrics
print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))

# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
print("\nConfusion Matrix:\n", cm)

# Heatmap
sns.heatmap(cm, annot=True)
plt.show()

#----------------------------------------------------
#LINEAR REG MODEL
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# Features (X) and target (y)
X = df[['Pclass','Age','SibSp','Parch']]
y= df['Fare']  

X = X.fillna(X.mean())

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

# Model
model = LinearRegression()
model.fit(X_train, y_train)

# Prediction
y_pred = model.predict(X_test)

# Evaluation
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)

print("MSE:", mse)
print("RMSE:", rmse)

#----------------------------------------------------
#KMEANS
from sklearn.cluster import KMeans
import pandas as pd

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

# Use only features (NO Class column)
X = df.drop('Class', axis=1).fillna(0)

# Create model
model = KMeans(n_clusters=3)

# Predict clusters
df['cluster'] = model.fit_predict(X)

# See cluster distribution
print(df['cluster'].value_counts())

#------------------------------------------------------
#TIME SERIES
df = pd.read_csv('Name.csv')

df['Month']= pd.to_datetime(df['Month'])      #converts into yyyy-mm-dd

plt.plot(df['Month'],df['Passengers'])
plt.xlabel('Month')
plt.show()

df['MA'] = df['Passengers'].rolling(3).mean()     #normal moving avg
print(df)

# Forecast next 5 values
forecast = [round(df['Passengers'].mean(),2)] * 5
print(forecast)

#------------------------------------------------------
#ARIMA
from statsmodels.tsa.arima.model import ARIMA

model = ARIMA(df['Passengers'], order=(1,1,1))
model_fit = model.fit()
forecast = model_fit.forecast(5)
print(forecast)

#------------------------------------------------------
#SMOTE
import pandas as pd
from imblearn.over_sampling import SMOTE
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# Load data
df = pd.read_csv('creditcard.csv')
# Identify class imbalance
df['Class'].value_counts()

from imblearn.over_sampling import SMOTE


X = df.drop('Class', axis=1).fillna(0)
y = df['Class'].fillna(0)

X_res, y_res = SMOTE().fit_resample(X, y)

#Logistic code write here
#---------------------------------------------------
Installing collected packages: seaborn
Successfully installed seaborn-0.13.2
Note: you may need to restart the kernel to use updated packages.