Episode 95: Python – Machine Learning and AI – Multiple Types of Correlation Algorithms

# network_kpi_correlation.py

import pandas as pd
import numpy as np

# -------------------------------
# 1. Simulated KPI Data
# -------------------------------
np.random.seed(42)
time_index = pd.date_range(start="2025-06-01", periods=10, freq="H")

data = pd.DataFrame({
    "timestamp": time_index,
    "Core_CPU_Util": np.random.normal(60, 5, size=10),
    "RAN_User_Throughput": np.random.normal(100, 10, size=10),
    "Transport_Packet_Loss": np.random.normal(0.5, 0.1, size=10),
    "App_Latency": np.random.normal(200, 20, size=10),
    "Transport_Latency": np.random.normal(50, 5, size=10),
    "IP_Drop_Rate": np.random.normal(0.2, 0.05, size=10)
})

# -------------------------------
# 2. Cross-Domain Correlation
# -------------------------------
def cross_domain_correlation(df, domain_kpi_columns, method='pearson'):
    domain_data = df[domain_kpi_columns]
    return domain_data.corr(method=method)

# -------------------------------
# 3. Cross-Layer Correlation
# -------------------------------
def cross_layer_correlation(df, layer_kpi_groups, method='pearson'):
    layer_averages = {layer: df[cols].mean(axis=1) for layer, cols in layer_kpi_groups.items()}
    layer_df = pd.DataFrame(layer_averages)
    return layer_df.corr(method=method)

# -------------------------------
# 4. Windowed Correlation
# -------------------------------
#def windowed_correlation(df, col_x, col_y, window_size, method='pearson'):
#    return df[[col_x, col_y]].rolling(window=window_size).corr(method=method).unstack().iloc[:, 1]
def windowed_correlation(df, col_x, col_y, window_size):
    """
    Computes rolling (windowed) Pearson correlation between two KPI columns.
    :param df: DataFrame with time series data
    :param col_x: First KPI column name
    :param col_y: Second KPI column name
    :param window_size: Rolling window size (int)
    :return: Series with correlation values over time
    """
    return df[col_x].rolling(window=window_size).corr(df[col_y])


# -------------------------------
# 5. Cross-Network Correlation
# -------------------------------
def cross_network_correlation(df, kpi_column, group_column='Network', method='pearson'):
    pivot_df = df.pivot(index="timestamp", columns=group_column, values=kpi_column)
    return pivot_df.corr(method=method)

def simulate_counterfactual(df, kpi_column, delta=5.0):
    """
    Simulates a counterfactual scenario by perturbing the given KPI column.
    Adds 'delta' to the original values to observe change in correlations.
    """
    df_cf = df.copy()
    df_cf[kpi_column] = df_cf[kpi_column] + delta
    return df_cf
    
# -------------------------------
# 6. Example Usage
# -------------------------------
if __name__ == "__main__":
    # Cross-Domain Correlation
    """domain_kpis = ["Core_CPU_Util", "RAN_User_Throughput", "Transport_Packet_Loss"]
    print("\nšŸ”„ Cross-Domain Correlation:")
    print(cross_domain_correlation(data, domain_kpis))

    # Cross-Layer Correlation
    layer_kpis = {
        "Application": ["App_Latency"],
        "Transport": ["Transport_Latency"],
        "IP": ["IP_Drop_Rate"]
    }
    print("\n🌐 Cross-Layer Correlation:")
    print(cross_layer_correlation(data, layer_kpis))

    # Windowed Correlation
    print("\nšŸ“ˆ Windowed Correlation (3-hour rolling):")
    print(windowed_correlation(data, "Core_CPU_Util", "RAN_User_Throughput", 3).dropna())

    # Cross-Network Correlation
    networks = ['Region_A', 'Region_B']
    data_multi_net = pd.concat([
        data.assign(Network='Region_A'),
        data.assign(Network='Region_B', Core_CPU_Util=data['Core_CPU_Util'] + np.random.normal(5, 2, 10))
    ])
    print("\nšŸŒ Cross-Network Correlation:")
    print(cross_network_correlation(data_multi_net, "Core_CPU_Util", group_column="Network"))"""

    import json

if __name__ == "__main__":
    # 1. Cross-Domain Correlation
    domain_kpis = ["Core_CPU_Util", "RAN_User_Throughput", "Transport_Packet_Loss"]
    domain_corr = cross_domain_correlation(data, domain_kpis)

    # 2. Cross-Layer Correlation
    layer_kpis = {
        "Application": ["App_Latency"],
        "Transport": ["Transport_Latency"],
        "IP": ["IP_Drop_Rate"]
    }
    layer_corr = cross_layer_correlation(data, layer_kpis)

    # 3. Windowed Correlation
    window_corr = windowed_correlation(data, "Core_CPU_Util", "RAN_User_Throughput", 3).dropna()

    # 4. Cross-Network Correlation
    data_multi_net = pd.concat([
        data.assign(Network='Region_A'),
        data.assign(Network='Region_B', Core_CPU_Util=data['Core_CPU_Util'] + np.random.normal(5, 2, 10))
    ])
    net_corr = cross_network_correlation(data_multi_net, "Core_CPU_Util", group_column="Network")

    # Combine all results into a JSON object
    result_json = {
        "cross_domain_correlation": domain_corr.round(3).to_dict(),
        "cross_layer_correlation": layer_corr.round(3).to_dict(),
        "windowed_correlation": window_corr.round(3).to_dict(),
        "cross_network_correlation": net_corr.round(3).to_dict()
    }

    # Pretty print JSON
    print(json.dumps(result_json, indent=4))
    
"""#Counter factual Reasoning
    import json

if __name__ == "__main__":
    # Original Data
    domain_kpis = ["Core_CPU_Util", "RAN_User_Throughput", "Transport_Packet_Loss"]
    layer_kpis = {
        "Application": ["App_Latency"],
        "Transport": ["Transport_Latency"],
        "IP": ["IP_Drop_Rate"]
    }

    # Simulate Counterfactual: Increase Core_CPU_Util by +5
    cf_data = simulate_counterfactual(data, "Core_CPU_Util", delta=5)

    # Cross-Domain Correlation
    domain_corr = cross_domain_correlation(data, domain_kpis)
    domain_corr_cf = cross_domain_correlation(cf_data, domain_kpis)

    # Cross-Layer Correlation
    layer_corr = cross_layer_correlation(data, layer_kpis)
    layer_corr_cf = cross_layer_correlation(cf_data, layer_kpis)

    # Windowed Correlation
    window_corr = windowed_correlation(data, "Core_CPU_Util", "RAN_User_Throughput", 3).dropna()
    window_corr_cf = windowed_correlation(cf_data, "Core_CPU_Util", "RAN_User_Throughput", 3).dropna()

    # Cross-Network Correlation
    data_multi_net = pd.concat([
        data.assign(Network='Region_A'),
        data.assign(Network='Region_B', Core_CPU_Util=data['Core_CPU_Util'] + np.random.normal(5, 2, 10))
    ])
    data_multi_net_cf = simulate_counterfactual(data_multi_net, "Core_CPU_Util", delta=5)

    net_corr = cross_network_correlation(data_multi_net, "Core_CPU_Util", group_column="Network")
    net_corr_cf = cross_network_correlation(data_multi_net_cf, "Core_CPU_Util", group_column="Network")

    # Final JSON with counterfactuals
    result_json = {
        "cross_domain_correlation": {
            "original": domain_corr.round(3).to_dict(),
            "counterfactual (+5 CPU)": domain_corr_cf.round(3).to_dict()
        },
        "cross_layer_correlation": {
            "original": layer_corr.round(3).to_dict(),
            "counterfactual (+5 CPU)": layer_corr_cf.round(3).to_dict()
        },
        "windowed_correlation": {
            "original": window_corr.round(3).to_dict(),
            "counterfactual (+5 CPU)": window_corr_cf.round(3).to_dict()
        },
        "cross_network_correlation": {
            "original": net_corr.round(3).to_dict(),
            "counterfactual (+5 CPU)": net_corr_cf.round(3).to_dict()
        }
    }

    # Print pretty JSON
    print(json.dumps(result_json, indent=4))"""

Tagged , , , | Leave a comment

Episode 94: Python – Machine Learning Anomaly Detection Algorithms

import pandas as pd
import numpy as np

def detect_anomalies(df, kpi_col='kpi_value', group_cols=['kpi_name', 'ne_name']):
    # Compute stats per KPI and NE group
    stats = df.groupby(group_cols)[kpi_col].agg(['mean', 'std']).reset_index()
    stats.rename(columns={'mean': 'typical', 'std': 'std_dev'}, inplace=True)

    # Merge stats back to the original DataFrame
    df = df.merge(stats, on=group_cols, how='left')

    # Calculate z-score
    df['z_score'] = (df[kpi_col] - df['typical']) / df['std_dev']

    # Define bounds
    threshold = 3
    df['lower_bound'] = df['typical'] - threshold * df['std_dev']
    df['upper_bound'] = df['typical'] + threshold * df['std_dev']
    df['actual'] = df[kpi_col]

    # Optional: Mark anomalies
    df['is_anomaly'] = df['z_score'].abs() > threshold

    # Select relevant columns
    result = df[['date_time', 'kpi_name', 'ne_name', 'typical', 'actual', 'lower_bound', 'upper_bound', 'z_score', 'is_anomaly']]
    return result

# Example usage
if __name__ == "__main__":
    # Replace with actual CSV file path or input DataFrame
    input_file = 'input_kpi_data.csv'
    df_input = pd.read_csv(input_file)

    result_df = detect_anomalies(df_input)
    result_df.to_csv('anomaly_output.csv', index=False)
    print("Anomaly detection completed. Output saved to 'anomaly_output.csv'.")

Leave a comment

Episode 93: Python – Machine Learning all types of Model Security Scanner

import os
import pickletools
import zipfile
import h5py
import onnx
import json

def scan_ml_model(filepath):
    report = {
        "file": os.path.basename(filepath),
        "extension": os.path.splitext(filepath)[1].lower(),
        "format": "Unknown",
        "safe_to_upload": False,
        "recommendation": "",
        "details": "",
    }

    ext = report["extension"]

    # --- 1. Pickle-based formats ---
    if ext in [".pkl", ".pickle", ".joblib"]:
        try:
            with open(filepath, "rb") as f:
                data = f.read()

            suspicious_opcodes = set()
            for opcode, arg, pos in pickletools.genops(data):
                #if opcode.name in ["GLOBAL", "REDUCE", "BUILD", "INST", "OBJ", "NEWOBJ", "NEWOBJ_EX"]:
                if opcode.name in ["GLOBAL", "INST", "OBJ", "NEWOBJ_EX"]:
                    suspicious_opcodes.add(opcode.name)

            report["format"] = "Pickle/Joblib"
            if suspicious_opcodes:
                report["recommendation"] = "High risk: Suspicious opcodes found."
                report["details"] = f"Found: {sorted(suspicious_opcodes)}"
            else:
                report["safe_to_upload"] = True
                report["recommendation"] = "Safe: No dangerous opcodes detected."
                report["details"] = "Minimal pickle usage."
        except Exception as e:
            report["recommendation"] = "Error reading pickle file."
            report["details"] = str(e)

    # --- 2. ONNX format ---
    elif ext == ".onnx":
        try:
            onnx_model = onnx.load(filepath)
            report["format"] = "ONNX"
            report["safe_to_upload"] = True
            report["recommendation"] = "Safe: Valid ONNX model structure."
            report["details"] = f"IR Version: {onnx_model.ir_version}, Opset: {onnx_model.opset_import}"
        except Exception as e:
            report["recommendation"] = "Invalid ONNX model."
            report["details"] = str(e)

    # --- 3. HDF5/Keras model ---
    elif ext in [".h5", ".hdf5"]:
        try:
            with h5py.File(filepath, "r") as f:
                keras_attrs = list(f.attrs)
            report["format"] = "Keras HDF5"
            report["safe_to_upload"] = True
            report["recommendation"] = "Safe: Valid Keras/TensorFlow model."
            report["details"] = f"Root attributes: {keras_attrs}"
        except Exception as e:
            report["recommendation"] = "Invalid HDF5 model."
            report["details"] = str(e)

    # --- 4. .pb (TensorFlow Protobuf model) ---
    elif ext == ".pb":
        report["format"] = "TensorFlow Protobuf"
        report["safe_to_upload"] = True
        report["recommendation"] = "Assume Safe: No execution logic, but validate structure separately."
        report["details"] = "Static graph definition format."

    # --- 5. CoreML .mlmodel ---
    elif ext == ".mlmodel":
        report["format"] = "Core ML"
        report["safe_to_upload"] = True
        report["recommendation"] = "Safe: Static model representation."
        report["details"] = "Manual inspection recommended if Apple format used."

    # --- 6. .zip (skops or sklearn export) ---
    elif ext == ".zip":
        try:
            with zipfile.ZipFile(filepath, "r") as z:
                if "skops.yaml" in z.namelist():
                    report["format"] = "skops export"
                    report["safe_to_upload"] = True
                    report["recommendation"] = "Safe: skops-verified model."
                    report["details"] = "Valid skops format."
                else:
                    report["recommendation"] = "Unknown zip content."
                    report["details"] = f"Files: {z.namelist()}"
        except Exception as e:
            report["recommendation"] = "Error reading zip file."
            report["details"] = str(e)

    # --- 7. Pyspark models (metadata check) ---
    elif ext == ".pyspark" or "pyspark" in filepath.lower():
        if os.path.isdir(filepath):
            metadata_file = os.path.join(filepath, "metadata")
            if os.path.exists(metadata_file):
                report["format"] = "PySpark MLlib"
                report["safe_to_upload"] = True
                report["recommendation"] = "Safe: PySpark model metadata directory."
                report["details"] = "Contains metadata.json"
            else:
                report["recommendation"] = "Missing metadata. Not a valid PySpark model."
        else:
            report["recommendation"] = "PySpark models are typically folders, not files."

    # --- 8. Vertex AI (exported .json or TF format) ---
    elif ext in [".json", ".tflite"]:
        try:
            with open(filepath, "r", encoding="utf-8") as f:
                json.load(f)
            report["format"] = "Vertex AI Export / JSON"
            report["safe_to_upload"] = True
            report["recommendation"] = "Safe: JSON-based model configuration."
            report["details"] = "Valid JSON structure."
        except Exception as e:
            report["recommendation"] = "Invalid JSON."
            report["details"] = str(e)

    # --- Unknown ---
    else:
        report["recommendation"] = "Unknown file type. Manual inspection recommended."
        report["details"] = "Could not classify model type."

    return report

#model_file = "rf_classifier_v1.pkl"  
model_file = "5c34bff2104941a3ad9b0fb290e6e2.pkl"  
result = scan_ml_model(model_file)
print(json.dumps(result, indent=4))
Leave a comment

Episode 92 : Python – Casual Discovery – Momentary Conditional Discovery Algorithm ( PCMCI)

import pandas as pd
from tigramite import data_processing as pp
from tigramite.independence_tests.parcorr import ParCorr
from tigramite.pcmci import PCMCI
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan
import networkx as nx
import matplotlib.pyplot as plt
import plotly.graph_objects as go

def load_csv_data(file_path):
    """
    Load data from a CSV file and ensure it has multiple rows.
    """
    df = pd.read_csv(file_path)
    print("Loaded data shape:", df.shape)
    if 'date_time' not in df.columns or 'measType' not in df.columns or 'measValue' not in df.columns:
        raise KeyError("Data must contain 'date_time', 'measType', and 'measValue' columns.")
    df['date_time'] = pd.to_datetime(df['date_time'])
    df = df[['date_time', 'measType', 'measValue']]  # Select relevant columns
    df = df.pivot(index='date_time', columns='measType', values='measValue')  # Pivot for wide format
    df.fillna(0, inplace=True)  # Handle missing values
    if df.shape[0] < 2:  # Ensure at least two observations
        raise ValueError("Not enough observations for PCMCI analysis.")
    return df

def load_elasticsearch_data(es_host, index_name):
    """
    Load data from Elasticsearch.
    """
    es = Elasticsearch(es_host, timeout=60)
    query = {"query": {"match_all": {}}}
    results = scan(es, index=index_name, query=query)
    data = []
    for item in results:
        source = item['_source']
        if 'date_time' in source and 'measType' in source and 'measValue' in source:
            data.append({
                'date_time': source['date_time'],
                'measType': source['measType'],
                'measValue': source['measValue']
            })
    if not data:
        raise ValueError("No data found in the specified Elasticsearch index.")
    df = pd.DataFrame(data)
    df['date_time'] = pd.to_datetime(df['date_time'])
    df = df.pivot(index='date_time', columns='measType', values='measValue')  # Pivot for wide format
    df.fillna(0, inplace=True)  # Handle missing values
    return df


def run_pcmci(df):
    """
    Run PCMCI on the processed DataFrame.
    """
    data_array = df.to_numpy()
    dataframe = pp.DataFrame(data_array, var_names=df.columns.tolist())

    parcorr = ParCorr(significance='analytic')
    pcmci = PCMCI(dataframe=dataframe, cond_ind_test=parcorr)
    results = pcmci.run_pcmci(tau_max=3, pc_alpha=0.05)

    print("Significant Links:")
    pcmci.print_significant_links(
        p_matrix=results['p_matrix'],
        val_matrix=results['val_matrix'],
        alpha_level=0.05
    )

    return results, dataframe


def visualize_pcmci_graph(results, dataframe, alpha_level=0.05):
    """
    Visualize the PCMCI causal graph.
    """
    val_matrix = results['val_matrix']
    p_matrix = results['p_matrix']
    G = nx.DiGraph()

    # Add edges for significant causal links
    for i, var_from in enumerate(dataframe.var_names):
        for j, var_to in enumerate(dataframe.var_names):
            if i != j:
                for lag in range(1, 4):
                    if p_matrix[i, j, lag - 1] < alpha_level:
                        weight = val_matrix[i, j, lag - 1]
                        G.add_edge(f"{var_from} (t-{lag})", var_to, weight=weight)

    if G.number_of_edges() == 0:
        print("No significant links to display in the causal graph.")
        return

    pos = nx.spring_layout(G, seed=42)
    plt.figure(figsize=(12, 10))
    nx.draw(
        G, pos, with_labels=True, node_size=3000, node_color='skyblue',
        font_size=10, font_weight='bold', edge_color='gray'
    )
    edge_labels = {(u, v): f"{d['weight']:.2f}" for u, v, d in G.edges(data=True)}
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color='red', font_size=8)
    plt.title('PCMCI Causal Graph with Significant Links')
    plt.show()

def visualize_pcmci_graph_interactive(results, dataframe, alpha_level=0.05):
    """
    Visualize the PCMCI causal graph interactively using Plotly.
    """
    val_matrix = results['val_matrix']
    p_matrix = results['p_matrix']
    G = nx.DiGraph()

    # Add edges for significant causal links
    for i, var_from in enumerate(dataframe.var_names):
        for j, var_to in enumerate(dataframe.var_names):
            if i != j:
                for lag in range(1, 4):  # Lag range: 1 to 3
                    if p_matrix[i, j, lag - 1] < alpha_level:
                        weight = val_matrix[i, j, lag - 1]
                        G.add_edge(f"{var_from} (t-{lag})", var_to, weight=weight)

    if G.number_of_edges() == 0:
        print("No significant links to display in the causal graph.")
        return

    # Get positions for nodes
    pos = nx.spring_layout(G, seed=42)

    # Create edge traces
    edge_x = []
    edge_y = []
    edge_weights = []
    for edge in G.edges(data=True):
        x0, y0 = pos[edge[0]]
        x1, y1 = pos[edge[1]]
        edge_x.append(x0)
        edge_x.append(x1)
        edge_x.append(None)
        edge_y.append(y0)
        edge_y.append(y1)
        edge_y.append(None)
        edge_weights.append(edge[2]['weight'])

    edge_trace = go.Scatter(
        x=edge_x, y=edge_y,
        line=dict(width=0.5, color='#888'),
        hoverinfo='none',
        mode='lines'
    )

    # Create node traces
    node_x = []
    node_y = []
    node_text = []
    for node in G.nodes():
        x, y = pos[node]
        node_x.append(x)
        node_y.append(y)
        node_text.append(node)

    node_trace = go.Scatter(
        x=node_x, y=node_y,
        mode='markers+text',
        text=node_text,
        textposition="top center",
        marker=dict(
            size=20,
            color='skyblue',
            line_width=2
        ),
        hoverinfo='text'
    )

    # Combine edge and node traces into a single figure
    fig = go.Figure(data=[edge_trace, node_trace],
                    layout=go.Layout(
                        title='Interactive PCMCI Causal Graph',
                        titlefont_size=16,
                        showlegend=False,
                        hovermode='closest',
                        margin=dict(b=0, l=0, r=0, t=40),
                        xaxis=dict(showgrid=False, zeroline=False),
                        yaxis=dict(showgrid=False, zeroline=False)
                    ))

    fig.show()
    
def convert_results_to_json(results, dataframe, alpha_level=0.05):
    """
    Convert PCMCI results into JSON format for frontend UI.
    """
    val_matrix = results['val_matrix']
    p_matrix = results['p_matrix']

    # Initialize the JSON structure
    json_result = {
        "nodes": [],
        "edges": []
    }

    # Add nodes
    for var_name in dataframe.var_names:
        json_result["nodes"].append({
            "id": var_name,
            "label": var_name
        })

    # Add edges for significant causal links
    for i, var_from in enumerate(dataframe.var_names):
        for j, var_to in enumerate(dataframe.var_names):
            if i != j:
                for lag in range(1, 4):  # Lag range: 1 to 3
                    if p_matrix[i, j, lag - 1] < alpha_level:
                        weight = val_matrix[i, j, lag - 1]
                        json_result["edges"].append({
                            "source": var_from,
                            "target": var_to,
                            "lag": lag,
                            "weight": weight,
                            "p_value": p_matrix[i, j, lag - 1]
                        })

    return json_result

# Choose input method: CSV or Elasticsearch
source = "csv"  # Change to 'elasticsearch' for Elasticsearch input

if source == "csv":
    file_path = 'merged_kpi.csv'  
    data = load_csv_data(file_path)
elif source == "elasticsearch":
    es_host = "http://localhost:9200"  
    index_name = "index_name"  
    data = load_elasticsearch_data(es_host, index_name)

# Run PCMCI analysis
results, dataframe = run_pcmci(data)

#Visualize the causal graph
#visualize_pcmci_graph(results, dataframe)
visualize_pcmci_graph_interactive(results, dataframe)


json_output = convert_results_to_json(results, dataframe, alpha_level=0.05)
import json
output_file = "pcmci_results.json"
with open(output_file, "w") as f:
    json.dump(json_output, f, indent=4)

print(f"PCMCI results saved to {output_file}")




Tagged , , , , | Leave a comment

Episode 91: Python – Anomaly Detection Program with Sample Datasets

import pandas as pd
from scipy.stats import zscore

# Sample CSV data creation
sample_data = {
    'ID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'Value': [10, 12, 10, 11, 13, 400, 12, 10, 11, 14]
}

# Save to a sample CSV file
csv_file = 'sample_data.csv'

# Write the sample data to a CSV file for demonstration
pd.DataFrame(sample_data).to_csv(csv_file, index=False)

# Load the CSV file
def load_data(file_path):
    return pd.read_csv(file_path)

# Anomaly Detection Function
def detect_anomalies(data, column, threshold=3):
    # Calculate z-scores
    data['z_score'] = zscore(data[column])
    
    # Identify anomalies (abs(z_score) > threshold)
    data['is_anomaly'] = data['z_score'].abs() > threshold
    return data

if __name__ == "__main__":
    # Load the CSV file
    data = load_data(csv_file)
    print("Original Data:")
    print(data)

    # Detect anomalies in the 'Value' column
    threshold = 3  # Adjust threshold for sensitivity
    result = detect_anomalies(data, column='Value', threshold=threshold)

    print("\nData with Anomaly Detection:")
    print(result)

    # Print only anomalies
    anomalies = result[result['is_anomaly']]
    print("\nDetected Anomalies:")
    print(anomalies)

Tagged , , , , | Leave a comment

Episode 90: Python – Simple Isolation Forest Algorithm with Sample Datasets

import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import train_test_split

# Create a sample CSV file
def create_sample_csv(file_name="sample_data.csv"):
    data = {
        "Feature1": np.random.normal(10, 2, 100).tolist() + [50],  # Normal data + outlier
        "Feature2": np.random.normal(20, 3, 100).tolist() + [5],  # Normal data + outlier
    }
    df = pd.DataFrame(data)
    df.to_csv(file_name, index=False)
    print(f"Sample CSV file '{file_name}' created!")

# Load data from CSV and prepare it for Isolation Forest
def load_data(file_name="sample_data.csv"):
    df = pd.read_csv(file_name)
    return df

# Train Isolation Forest and detect anomalies
def isolation_forest_detection(data, contamination=0.05):
    # Splitting data into training and test sets
    train_data, test_data = train_test_split(data, test_size=0.2, random_state=42)

    # Training the Isolation Forest
    model = IsolationForest(n_estimators=100, contamination=contamination, random_state=42)
    model.fit(train_data)

    # Predict anomalies (-1: Anomaly, 1: Normal)
    data['Anomaly'] = model.predict(data)
    return data

def main():
    # Step 1: Create a sample CSV file
    create_sample_csv()

    # Step 2: Load the data
    data = load_data()
    print("Loaded Data:")
    print(data.head())

    # Step 3: Detect anomalies using Isolation Forest
    results = isolation_forest_detection(data)
    print("\nData with Anomalies Detected:")
    print(results)

    # Save the results to a new CSV file
    results.to_csv("results_with_anomalies.csv", index=False)
    print("\nResults saved to 'results_with_anomalies.csv'.")

if __name__ == "__main__":
    main()

Tagged , , , , | Leave a comment

Episode 89 : Python – Simple K Means Algorithm with Sample Data Sets

import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

# Create a sample CSV file
csv_content = """ID,Feature1,Feature2
1,2.0,3.0
2,3.0,4.0
3,5.0,6.0
4,8.0,8.0
5,1.0,0.5
6,9.0,11.0
"""

# Save the CSV content to a file
csv_file = "sample_data.csv"
with open(csv_file, "w") as file:
    file.write(csv_content)

# Load the sample data
try:
    data = pd.read_csv(csv_file)
except Exception as e:
    print(f"Error loading CSV: {e}")
    exit()

# Display the data
print("Data Loaded:")
print(data)

# Extract features for clustering
features = data[["Feature1", "Feature2"]]

# Perform K-Means clustering
kmeans = KMeans(n_clusters=3, random_state=42)
kmeans.fit(features)

# Add cluster labels to the data
data["Cluster"] = kmeans.labels_

# Display the data with clusters
print("\nData with Cluster Assignments:")
print(data)

# Visualize the clusters
plt.figure(figsize=(8, 6))
plt.scatter(features["Feature1"], features["Feature2"], c=data["Cluster"], cmap="viridis", marker="o")
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c="red", marker="X", label="Centroids")
plt.xlabel("Feature1")
plt.ylabel("Feature2")
plt.title("K-Means Clustering")
plt.legend()
plt.show()

Tagged , , , , | Leave a comment

Episode 88: Python – Naive Bays Algorithm with Sample Data

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, classification_report

# Sample CSV Data (for demonstration purposes, use your own CSV file)
data = {
    'Feature1': ['A', 'A', 'B', 'B', 'A', 'B', 'A', 'B'],
    'Feature2': ['X', 'Y', 'X', 'Y', 'X', 'X', 'Y', 'Y'],
    'Label': ['Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No']
}

# Create DataFrame and save to CSV
sample_csv = "sample_data.csv"
pd.DataFrame(data).to_csv(sample_csv, index=False)

# Load the CSV file
df = pd.read_csv(sample_csv)

# Encode categorical features and labels
from sklearn.preprocessing import LabelEncoder

label_encoders = {}
for column in df.columns:
    le = LabelEncoder()
    df[column] = le.fit_transform(df[column])
    label_encoders[column] = le

# Split features and labels
X = df.drop('Label', axis=1)
y = df['Label']

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

# Create and train Naive Bayes model
model = GaussianNB()
model.fit(X_train, y_train)

# Make predictions
y_pred = model.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Classification Report:\n", classification_report(y_test, y_pred))

# Decode predictions and labels (if needed)
def decode_label(encoded_label, column):
    return label_encoders[column].inverse_transform([encoded_label])[0]

# Display decoded predictions and their actual labels
for i in range(len(y_pred)):
    print(f"Predicted: {decode_label(y_pred[i], 'Label')}, Actual: {decode_label(y_test.iloc[i], 'Label')}")

Tagged , , , , | Leave a comment

Episode 87: Python – Logistic Regression Algorithm using sample data

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report

# Step 1: Create a sample CSV file
data = {
    "Feature1": [2.5, 3.6, 1.5, 3.2, 2.7, 3.9, 1.2, 2.4, 3.1, 2.8],
    "Feature2": [1.8, 2.9, 1.1, 2.5, 2.0, 3.1, 1.0, 1.9, 2.4, 2.1],
    "Label": [0, 1, 0, 1, 0, 1, 0, 0, 1, 0]
}

# Save sample data to a CSV file
sample_csv_file = "sample_data.csv"
pd.DataFrame(data).to_csv(sample_csv_file, index=False)
print(f"Sample CSV file '{sample_csv_file}' created.")

# Step 2: Load the CSV file
data = pd.read_csv(sample_csv_file)
X = data[["Feature1", "Feature2"]]  # Features
y = data["Label"]  # Target variable

# Step 3: Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Step 4: Create and train the logistic regression model
model = LogisticRegression()
model.fit(X_train, y_train)

# Step 5: Make predictions
y_pred = model.predict(X_test)

# Step 6: Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy * 100:.2f}%")
print("Classification Report:\n", classification_report(y_test, y_pred))

# Additional Step: Predict for new data
new_data = pd.DataFrame({"Feature1": [2.5, 3.5], "Feature2": [1.5, 2.8]})
new_predictions = model.predict(new_data)
print("Predictions for new data:", new_predictions)

Tagged , , , , | Leave a comment

Episode 86: Send automatic email for Login Notification

import smtplib
from email.message import EmailMessage
import datetime

# Email configuration
SMTP_SERVER = 'smtp.gmail.com'  # SMTP server for Gmail
SMTP_PORT = 587  # Port for Gmail's SMTP server
SENDER_EMAIL = 'your_email@gmail.com'  # Replace with sender's email address
SENDER_PASSWORD = 'your_email_password'  # Replace with sender's email password

# Function to send email
def send_login_email(user_email, website_name):
    try:
        # Create the email message
        msg = EmailMessage()
        msg['Subject'] = f'Login Notification for {website_name}'
        msg['From'] = SENDER_EMAIL
        msg['To'] = user_email

        # Email content
        login_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        msg.set_content(f"Hello,\n\nThis is a notification that a login occurred on {website_name}.\n\nLogin Details:\nDate and Time: {login_time}\n\nIf this wasn't you, please secure your account immediately.\n\nRegards,\n{website_name} Team")

        # Connect to the SMTP server and send the email
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()  # Secure the connection
            server.login(SENDER_EMAIL, SENDER_PASSWORD)
            server.send_message(msg)

        print("Email sent successfully.")
    except Exception as e:
        print(f"Failed to send email: {e}")

# Example usage
if __name__ == "__main__":
    # Replace with actual user email and website name
    user_email = 'user_email@example.com'
    website_name = 'Example Website'
    send_login_email(user_email, website_name)

Tagged , , , , , , | Leave a comment