def data():
    raise Exception('''
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')

print(df.head())
print(df.tail())

print(help(df))
print("Information:")
df.info()

print("Description")
df.describe()

print("Null values: \n", df.isnull().sum())

df.hist(figsize=(10,6))
plt.show()

sns.boxplot(data=df)
plt.show()

sns.countplot(x='species', data=df)
plt.show()

#Scatter Plot
plt.scatter(df['sepal_length'], df['sepal_width'])
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.show()

sns.pairplot(df, hue='species')
plt.show()

plt.figure(figsize=(10,6))
plt.scatter(df['petal_length'], df['sepal_length'], label='Sepal Length')
plt.scatter(df['petal_length'], df['sepal_width'], label='Sepal Width')
plt.scatter(df['petal_length'], df['petal_width'], label='Petal Width')

plt.xlabel('Petal Length')
plt.ylabel('Values of Other Attributes')
plt.title('Scatter Multiple Plot (Iris Dataset)')
plt.legend()
plt.show()

from pandas.plotting import scatter_matrix
plt.figure(figsize=(10,8))
scatter_matrix(df.iloc[:, :4], figsize=(10,8), diagonal='hist')
plt.show()

from pandas.plotting import parallel_coordinates

plt.figure(figsize=(10,6))
parallel_coordinates(df, 'species')
plt.title('Parallel Coordinates Plot - Iris Dataset')
plt.show()

#Deviation Chart (from mean)
mean_vals = df.iloc[:, :4].mean()

plt.figure(figsize=(10,6))
plt.plot(df.iloc[:, :4] - mean_vals)
plt.title('Deviation Chart - Deviation from Mean')
plt.xlabel('Record Index')
plt.ylabel('Deviation')
plt.show()


#Andrews Curve
from pandas.plotting import andrews_curves

plt.figure(figsize=(10,6))
andrews_curves(df, 'species')
plt.title('Andrews Curves - Iris Dataset')
plt.show()
        ''')

def decisiontree():
    raise Exception('''
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report

from sklearn.datasets import load_iris

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

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
dt_model = DecisionTreeClassifier(criterion="gini", max_depth=3)
dt_model.fit(X_train, y_train)
y_pred = dt_model.predict(X_test)
print(y_pred)

accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

print(classification_report(y_test, y_pred))

from sklearn.tree import plot_tree
import matplotlib.pyplot as plt

plt.figure(figsize=(12,8))
plot_tree(dt_model, feature_names=iris.feature_names,
          class_names=iris.target_names, filled=True)
plt.show()

# mtcars dataset
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report

mtcars = pd.read_csv("mtcars.csv")
mtcars.head()

mtcars = mtcars.drop(columns=['model'])
X = mtcars.drop('am', axis=1)
y = mtcars['am']


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
dt_model = DecisionTreeClassifier(criterion="gini",max_depth=3)
dt_model.fit(X_train, y_train)
y_pred = dt_model.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

print(classification_report(y_test, y_pred))


from sklearn.tree import plot_tree
import matplotlib.pyplot as plt

plt.figure(figsize=(14,8))
plot_tree(
    dt_model,
    feature_names=X.columns,
    class_names=["Automatic", "Manual"],
    filled=True
)
plt.show()


    ''')

def kmeans():
    raise Exception('''
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans

iris = load_iris()
X = iris.data

k = 3

kmeans = KMeans(n_clusters=3, random_state=0)
kmeans.fit(X)

labels = kmeans.labels_
centroids = kmeans.cluster_centers_
print(labels)
print(centroids)

plt.scatter(X[:,2], X[:,3], c=labels)
plt.scatter(centroids[:,2], centroids[:,3], marker='X')
plt.xlabel("Petal Length")
plt.ylabel("Petal Width")
plt.title("K-Means Clustering on Iris Dataset")
plt.show()

# DBSCAN 
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler

iris = load_iris()
X = iris.data

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

dbscan = DBSCAN(eps=0.6, min_samples=5)

labels = dbscan.fit_predict(X_scaled)

print(np.unique(labels))

plt.scatter(X_scaled[:, 0], X_scaled[:, 1], c=labels)
plt.xlabel("Sepal Length")
plt.ylabel("Sepal Width")
plt.title("DBSCAN Clustering on Iris Dataset")
plt.show()
    ''')

def regression():
    raise Exception('''
#Slr
import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split, cross_val_score, KFold
from sklearn.metrics import mean_squared_error, r2_score

#(p-values, std err)
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor

import scipy.stats as stats 

hours = np.array([1, 2, 4, 5, 5, 6])
score = np.array([64, 66, 76, 73, 74, 81])

df = pd.DataFrame({"hours": hours, "score": score})

# Scatter plot with regression line visually
sns.scatterplot(x="hours", y="score", data=df, s=80)
sns.regplot(x="hours", y="score", data=df, ci=None, scatter=False)  # fitted line
plt.title("Hours studied vs Exam Score")
plt.xlabel("Hours studied")
plt.ylabel("Exam Score")
plt.show()

# Boxplot 
plt.figure()
sns.boxplot(y=df["score"])
plt.title("Boxplot of Exam Scores")
plt.show()

X = df[["hours"]]  # 2D array (n_samples, n_features)
y = df["score"]

lr = LinearRegression()
lr.fit(X, y)

b0 = lr.intercept_
b1 = lr.coef_[0]
print(f"Intercept (b0): {b0:.4f}")
print(f"Slope (b1): {b1:.4f}")

X_sm = sm.add_constant(X) 
model_sm = sm.OLS(y, X_sm).fit()
print(model_sm.summary())

#(single value)
new_hours = pd.DataFrame({"hours": [3]})
predicted_score = lr.predict(new_hours)
print("Predicted score for 3 hours:", predicted_score[0])

grid = pd.DataFrame({"hours": np.linspace(df.hours.min(), df.hours.max(), 50)})
grid["predicted_score"] = lr.predict(grid)
grid.head()

df["predicted"] = lr.predict(X)
df["residuals"] = df["score"] - df["predicted"]

# Residual vs Fitted
plt.figure()
plt.scatter(df["predicted"], df["residuals"], s=60)
plt.axhline(0, linestyle='--')
plt.xlabel("Fitted values")
plt.ylabel("Residuals")
plt.title("Residuals vs Fitted")
plt.show()

#QQ
plt.figure()
sm.qqplot(df["residuals"], line='45', fit=True)
plt.title("Q-Q plot of residuals")
plt.show()

#Hist
plt.figure()
sns.histplot(df["residuals"], kde=True)
plt.title("Histogram of residuals")
plt.show()

#mlr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split, KFold, cross_val_score

import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.stats.diagnostic import het_breuschpagan
from statsmodels.stats.stattools import durbin_watson
import scipy.stats as stats

house = pd.read_csv("index.csv")
house.head()
house.shape

house.info()          
house.describe().T    
house.columns      

house.isnull().sum()

#Pairwiserelation
sns.pairplot(house[['death_rate','doctor_avail','hosp_avail','annual_income','density_per_capita']])
plt.suptitle("Pairwise plots", y=1.02)
plt.show()

# Correlation matrix
corr = house[['death_rate','doctor_avail','hosp_avail','annual_income','density_per_capita']].corr()
print(corr)
sns.heatmap(corr, annot=True, fmt=".2f")
plt.title("Correlation matrix")
plt.show()

X = house[['death_rate','doctor_avail','hosp_avail','annual_income']]
y = house['density_per_capita']

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

lr = LinearRegression()
lr.fit(X_train, y_train)

print("Intercept (sklearn):", lr.intercept_)
print("Coefficients (sklearn):")
for name, coef in zip(X.columns, lr.coef_):
    print(f"  {name}: {coef:.6f}")

# p-values, std errors, R-squared etc.
X_sm = sm.add_constant(X)           
model_sm = sm.OLS(y, X_sm).fit()

print(model_sm.summary())

house['predicted'] = model_sm.predict(X_sm)   # statsmodels predict expects same X with constant

y_test_pred = lr.predict(X_test)

new_obs = pd.DataFrame({'death_rate':[2.0], 'doctor_avail':[1.5], 'hosp_avail':[0.7], 'annual_income':[35000]})
pred_new = lr.predict(new_obs)   # sklearn
print("Predicted density_per_capita for new_obs:", pred_new[0])

rmse = np.sqrt(mean_squared_error(y_test, y_test_pred))
r2 = r2_score(y_test, y_test_pred)
print("Test RMSE:", rmse)
print("Test R2:", r2)

for col in X.columns:
    plt.figure()
    sns.scatterplot(x=house[col], y=house['density_per_capita'])
    sns.regplot(x=house[col], y=house['density_per_capita'], ci=None, scatter=False)
    plt.xlabel(col)
    plt.ylabel('density_per_capita')
    plt.title(f'density_per_capita vs {col}')
    plt.show()

# Actual Vs Predicted
plt.figure()
sns.scatterplot(x=house['predicted'], y=house['density_per_capita'])
plt.plot([house['predicted'].min(), house['predicted'].max()],
[house['predicted'].min(), house['predicted'].max()], color='red', linestyle='--')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Actual vs Predicted')
plt.show()

# Residuals vs Fitted (heteroscedasticity / non-linearity)
residuals = house['density_per_capita'] - house['predicted']
plt.figure()
sns.scatterplot(x=house['predicted'], y=residuals)
plt.axhline(0, color='red', linestyle='--')
plt.xlabel('Fitted values')
plt.ylabel('Residuals')
plt.title('Residuals vs Fitted')
plt.show()

# Q-Q Plot
sm.qqplot(residuals, line='45', fit=True)
plt.title('Q-Q plot of residuals')
plt.show()

stat, pval = stats.shapiro(residuals)
print("Shapiro-Wilk: stat=%.4f, p=%.4f" % (stat, pval))

# Influence / Leverage plot (outliers & influential points)
sm.graphics.influence_plot(model_sm, criterion="cooks")
plt.show()
    ''')

def association():
    raise Exception('''
import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules

transactions = [
    ['Milk', 'Bread'],
    ['Bread', 'Diaper', 'Beer', 'Eggs'],
    ['Milk', 'Diaper', 'Beer', 'Cola'],
    ['Bread', 'Milk', 'Diaper', 'Beer'],
    ['Bread', 'Milk', 'Diaper', 'Cola']
]

te = TransactionEncoder()
te_array = te.fit(transactions).transform(transactions)
df = pd.DataFrame(te_array, columns=te.columns_)
print(df)

frequent_itemsets = apriori(df, min_support=0.4, use_colnames=True)
print(frequent_itemsets)

rules = association_rules(
    frequent_itemsets,
    metric="confidence",
    min_threshold=0.6
)
print(rules[['antecedents', 'consequents', 'support', 'confidence', 'lift']])


# FP-Growth
import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules
from mlxtend.frequent_patterns import fpgrowth

transactions = [
    ['Milk', 'Bread'],
    ['Bread', 'Diaper', 'Beer', 'Eggs'],
    ['Milk', 'Diaper', 'Beer', 'Cola'],
    ['Bread', 'Milk', 'Diaper', 'Beer'],
    ['Bread', 'Milk', 'Diaper', 'Cola']
]

te = TransactionEncoder()
te_array = te.fit(transactions).transform(transactions)
df = pd.DataFrame(te_array, columns=te.columns_)
print(df)
frequent_itemsets_fp = fpgrowth(df, min_support=0.4, use_colnames=True)
print(frequent_itemsets_fp)
rules_fp = association_rules(
    frequent_itemsets_fp,
    metric="confidence",
    min_threshold=0.6
)
print(rules_fp[['antecedents', 'consequents', 'support', 'confidence', 'lift']])


    ''')

def cnn():
    raise Exception('''
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

x_train = x_train / 255.0
x_test = x_test / 255.0

x_train = x_train.reshape(-1,28,28,1)
x_test = x_test.reshape(-1,28,28,1)

model = keras.Sequential([
    layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
    layers.MaxPooling2D((2,2)),
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(10, activation='softmax')
])

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

model.fit(x_train, y_train, epochs=5, validation_split=0.1)

test_loss, test_acc = model.evaluate(x_test, y_test)
print("Test Accuracy:", test_acc)

plt.imshow(x_test[0].reshape(28,28), cmap='gray')
plt.show()

prediction = model.predict(x_test[0].reshape(1,28,28,1))
print("Predicted Digit:", prediction.argmax())


    ''')

def recommendation():
    raise Exception('''
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity

data = {
    'User': ['U1','U1','U2','U2','U3','U3'],
    'Item': ['I1','I2','I1','I3','I2','I3'],
    'Rating': [5,4,4,5,3,4]
}
df = pd.DataFrame(data)

matrix = df.pivot_table(index='User', columns='Item', values='Rating').fillna(0)
print(matrix)

similarity = cosine_similarity(matrix.T)
similarity_df = pd.DataFrame(similarity, index=matrix.columns, columns=matrix.columns)
print(similarity_df)

def recommend(item):
    return similarity_df[item].sort_values(ascending=False)

print(recommend('I1'))


    ''')

def timeseries():
    raise Exception('''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.statespace.sarimax import SARIMAX

data = pd.read_csv("AirPassengers.csv")
data['Month'] = pd.to_datetime(data['Month'])
data.set_index('Month', inplace=True)
data.head()


plt.figure()
plt.plot(data['Passengers'])
plt.title('Monthly Air Passengers')
plt.xlabel('Year')
plt.ylabel('Number of Passengers')
plt.show()

result = adfuller(data['Passengers'])

print("ADF Statistic:", result[0])
print("p-value:", result[1])

data_diff = data['Passengers'].diff().dropna()

plt.figure()
plt.plot(data_diff)
plt.title('First Differenced Series')
plt.show()

adfuller(data_diff)

from statsmodels.graphics.tsaplots import plot_pacf
import matplotlib.pyplot as plt

plot_pacf(data_diff, lags=20)
plt.show()

from statsmodels.graphics.tsaplots import plot_acf

plot_acf(data_diff, lags=20)
plt.show()

model = ARIMA(data['Passengers'], order=(1,1,1))
model_fit = model.fit()
print(model_fit.summary())

forecast = model_fit.forecast(steps=12)
print(forecast)

plt.figure()
plt.plot(data['Passengers'], label='Actual')
plt.plot(forecast, label='Forecast', color='red')
plt.legend()
plt.show()

    ''')

def anomaly():
    raise Exception('''
# Z-Score
import pandas as pd
from scipy.stats import zscore

df = pd.DataFrame({
    'Employee_ID': ['E01','E02','E03','E04','E05','E06','E07'],
    'Salary': [48000, 52000, 50500, 49200, 51000, 120000, 18000]
})

df['Z_Score'] = zscore(df['Salary'])
print(df['Z_Score'])

outliers = df[abs(df['Z_Score']) > 2]
print(outliers)

# IQR Method
data = {
    'Employee_ID': ['E01','E02','E03','E04','E05','E06','E07'],
    'Salary': [48000, 52000, 50500, 49200, 51000, 120000, 18000]
}

df = pd.DataFrame(data)

Q1 = df['Salary'].quantile(0.25)
Q3 = df['Salary'].quantile(0.75)

IQR = Q3 - Q1

lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR

outliers = df[
    (df['Salary'] < lower_bound) |
    (df['Salary'] > upper_bound)
]

print("Lower Bound:", lower_bound)
print("Upper Bound:", upper_bound)
print("\nDetected Outliers:")
print(outliers)

#IsolationForest 
from sklearn.ensemble import IsolationForest
import pandas as pd

df = pd.DataFrame({
    'Amount': [2800, 3200, 3500, 2900, 3100, 18000, 50]
})

model = IsolationForest(contamination=0.2, random_state=42)
df['Anomaly'] = model.fit_predict(df)

print(df)

#KNN
from sklearn.neighbors import NearestNeighbors
import pandas as pd

df = pd.DataFrame({
    'Delivery_Time': [46, 48, 50, 47, 49, 95, 10]
})

nbrs = NearestNeighbors(n_neighbors=3)
nbrs.fit(df)

distances, _ = nbrs.kneighbors(df)
df['Avg_Distance'] = distances.mean(axis=1)

threshold = df['Avg_Distance'].mean() + 2*df['Avg_Distance'].std()
outliers = df[df['Avg_Distance'] > threshold]

print(outliers)

#LOF
from sklearn.neighbors import LocalOutlierFactor
import pandas as pd

df = pd.DataFrame({
    'Spending_Score': [45, 50, 48, 52, 49, 98, 5],
    'Purchase_Frequency': [18, 20, 22, 19, 21, 65, 2]
})

lof = LocalOutlierFactor(n_neighbors=3)
df['Outlier'] = lof.fit_predict(df)

outliers = df[df['Outlier'] == -1]
print(outliers)
    ''')

def text():
    raise Exception('''
#Document Classification
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB

texts = [
    "Meeting scheduled with project team",
    "Family dinner this weekend",
    "Project deadline extended",
    "Birthday party invitation"
]

labels = ["Work", "Personal", "Work", "Personal"]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(texts)

model = MultinomialNB()
model.fit(X, labels)

prediction = model.predict(vectorizer.transform(["Project meeting tomorrow"]))
print(prediction)

# Sentiment Analysis
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression

reviews = [
    "The product is amazing",
    "Very bad quality",
    "I am happy with the purchase",
    "Worst experience ever"
]

sentiment = ["Positive", "Negative", "Positive", "Negative"]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(reviews)

model = LogisticRegression()
model.fit(X, sentiment)

print(model.predict(vectorizer.transform(["The product quality is good"])))

# Search Engines
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

documents = [
    "Data science and machine learning",
    "Introduction to text mining",
    "Python for data analysis"
]

query = ["text mining"]

vectorizer = TfidfVectorizer()
tfidf = vectorizer.fit_transform(documents + query)

similarity = (tfidf * tfidf.T).toarray()
print("Most relevant document index:", np.argmax(similarity[-1][:-1]))

# Spam Detection
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB

messages = [
    "Win a free lottery now",
    "Meeting scheduled tomorrow",
    "Urgent offer claim now",
    "Project discussion today"
]

labels = ["Spam", "Not Spam", "Spam", "Not Spam"]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(messages)

model = MultinomialNB()
model.fit(X, labels)

print(model.predict(vectorizer.transform(["Free offer just for you"])))

# Recommendation Systems
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

movies = [
    "Action adventure and hero story",
    "Romantic love story",
    "Adventure and fantasy world"
]

vectorizer = TfidfVectorizer()
tfidf = vectorizer.fit_transform(movies)

similarity = cosine_similarity(tfidf)
print(similarity)

    ''')

def associationm():
    raise Exception('''
# apriori Algorithm
transactions = [
    {'Milk', 'Bread'},
    {'Bread', 'Diaper', 'Beer', 'Eggs'},
    {'Milk', 'Diaper', 'Beer', 'Cola'},
    {'Bread', 'Milk', 'Diaper', 'Beer'},
    {'Bread', 'Milk', 'Diaper', 'Cola'}
]

total_transactions = len(transactions)
min_support = 0.4
min_confidence = 0.6

def calculate_support(itemset):
    count = 0
    for transaction in transactions:
        if itemset.issubset(transaction):
            count += 1
    return count / total_transactions

items = set().union(*transactions)
frequent_1 = {}

for item in items:
    sup = calculate_support({item})
    if sup >= min_support:
        frequent_1[frozenset([item])] = sup

print("Frequent 1-Itemsets:")
for k, v in frequent_1.items():
    print(set(k), ":", v)

from itertools import combinations

frequent_2 = {}

for pair in combinations(items, 2):
    sup = calculate_support(set(pair))
    if sup >= min_support:
        frequent_2[frozenset(pair)] = sup

print("\nFrequent 2-Itemsets:")
for k, v in frequent_2.items():
    print(set(k), ":", v)

frequent_3 = {}

for triple in combinations(items, 3):
    sup = calculate_support(set(triple))
    if sup >= min_support:
        frequent_3[frozenset(triple)] = sup

print("\nFrequent 3-Itemsets:")
for k, v in frequent_3.items():
    print(set(k), ":", v)

def calculate_confidence(A, B):
    return calculate_support(A.union(B)) / calculate_support(A)

rules = []

for itemset in frequent_2:
    for item in itemset:
        A = frozenset([item])
        B = itemset - A
        conf = calculate_confidence(set(A), set(B))
        if conf >= min_confidence:
            rules.append((A, B, conf))

print("\nAssociation Rules:")
for rule in rules:
    print(set(rule[0]), "→", set(rule[1]), "Confidence:", rule[2])

def calculate_lift(A, B):
    return calculate_confidence(A, B) / calculate_support(B)

print("\nAssociation Rules with Lift:")
for rule in rules:
    lift = calculate_lift(set(rule[0]), set(rule[1]))
    print(set(rule[0]), "→", set(rule[1]), "Lift:", lift)

# FP-Growth Algorithm
transactions = [
    ['Milk', 'Bread'],
    ['Bread', 'Diaper', 'Beer', 'Eggs'],
    ['Milk', 'Diaper', 'Beer', 'Cola'],
    ['Bread', 'Milk', 'Diaper', 'Beer'],
    ['Bread', 'Milk', 'Diaper', 'Cola']
]

min_support = 2

from collections import defaultdict

item_count = defaultdict(int)

for transaction in transactions:
    for item in transaction:
        item_count[item] += 1

print("Item Frequencies:")
for item, count in item_count.items():
    print(item, ":", count)

frequent_items = {item: count for item, count in item_count.items()
                  if count >= min_support}

print("\nFrequent Items:")
print(frequent_items)

sorted_transactions = []

for transaction in transactions:
    filtered = [item for item in transaction if item in frequent_items]
    sorted_trans = sorted(filtered,
                          key=lambda x: frequent_items[x],
                          reverse=True)
    sorted_transactions.append(sorted_trans)

print("\nSorted Transactions:")
for t in sorted_transactions:
    print(t)

class FPNode:
    def __init__(self, item, count, parent):
        self.item = item
        self.count = count
        self.parent = parent
        self.children = {}

root = FPNode(None, 0, None)

def insert_tree(transaction, node):
    if len(transaction) == 0:
        return
    first = transaction[0]
    if first in node.children:
        node.children[first].count += 1
    else:
        node.children[first] = FPNode(first, 1, node)
    insert_tree(transaction[1:], node.children[first])

for transaction in sorted_transactions:
    insert_tree(transaction, root)

def display_tree(node, indent=0):
    for child in node.children.values():
        print(" " * indent, child.item, ":", child.count)
        display_tree(child, indent + 4)

print("\nFP-Tree:")
display_tree(root)

frequent_patterns = {}

for item, count in frequent_items.items():
    frequent_patterns[(item,)] = count

print("\nFrequent Patterns:")
for pattern, count in frequent_patterns.items():
    print(pattern, ":", count)

''')

def logreg():
    raise Exception('''
import pandas as pd
import numpy as np
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

df = sns.load_dataset("titanic")

df = df[["survived", "pclass", "sex", "age", "sibsp", "parch", "fare"]]

df["age"] = df["age"].fillna(df["age"].median())

df["sex"] = df["sex"].map({"male": 0, "female": 1})

X = df.drop("survived", axis=1)
y = df["survived"]

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

model = LogisticRegression(max_iter=500)
model.fit(X_train, y_train)

y_pred = model.predict(X_test)

acc = accuracy_score(y_test, y_pred)
cm = confusion_matrix(y_test, y_pred)
report = classification_report(y_test, y_pred)

print("Accuracy:", acc)
print("\nConfusion Matrix:\n", cm)
print("\nClassification Report:\n", report)

plt.figure(figsize=(6, 4))
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", cbar=False,
 xticklabels=["Predicted 0", "Predicted 1"],
 yticklabels=["Actual 0", "Actual 1"])
plt.title("Confusion Matrix")
plt.ylabel("Actual")
plt.xlabel("Predicted")
plt.show()
''')
