Spaces:
Sleeping
Sleeping
Download data.py from VSaiTejaReddy004/fraud_detection: direct link, hf CLI and curl.
- Browser
- Download file 2.65 kB
-
https://huggingface.co/spaces/VSaiTejaReddy004/fraud_detection/resolve/main/data.py
- Command line
-
hf download hf://spaces/VSaiTejaReddy004/fraud_detection/data.py
-
curl -L -o data.py https://huggingface.co/spaces/VSaiTejaReddy004/fraud_detection/resolve/main/data.py
2.65 kB
| import random | |
| import uuid | |
| import os | |
| import csv | |
| from typing import List | |
| from models import TransactionWithLabel | |
| CSV_PATH = "creditcard.csv" | |
| def generate_mock_kaggle_data(filename: str, num_transactions: int = 500): | |
| """Creates a mock Kaggle creditcard.csv file if the real one isn't present.""" | |
| print("Generating mock Kaggle data since actual CSV wasn't found...") | |
| with open(filename, mode='w', newline='') as f: | |
| writer = csv.writer(f) | |
| header = ["Time"] + [f"V{i}" for i in range(1, 29)] + ["Amount", "Class"] | |
| writer.writerow(header) | |
| for i in range(num_transactions): | |
| time_val = float(i * 10) | |
| is_fraud = random.random() < 0.15 # 15% fraud in mock | |
| features = [] | |
| for j in range(1, 29): | |
| # Anomaly/fraud signals in V1, V2, V3 | |
| if is_fraud and j in [1, 2, 3]: | |
| val = random.uniform(5.0, 15.0) * random.choice([-1, 1]) | |
| else: | |
| val = random.gauss(0, 1) # Normal distribution around 0 | |
| features.append(round(val, 6)) | |
| amount = round(random.uniform(1.0, 1000.0) if not is_fraud else random.uniform(500.0, 5000.0), 2) | |
| cls = 1 if is_fraud else 0 | |
| row = [time_val] + features + [amount, cls] | |
| writer.writerow(row) | |
| def load_kaggle_data(num_transactions: int = 100) -> List[TransactionWithLabel]: | |
| """Loads transactions from creditcard.csv""" | |
| if not os.path.exists(CSV_PATH): | |
| generate_mock_kaggle_data(CSV_PATH, num_transactions=max(500, num_transactions * 2)) | |
| transactions = [] | |
| with open(CSV_PATH, mode='r') as f: | |
| reader = csv.DictReader(f) | |
| for i, row in enumerate(reader): | |
| if i >= num_transactions: | |
| break | |
| time_val = float(row["Time"]) | |
| amount_val = float(row["Amount"]) | |
| cls_val = int(row["Class"]) | |
| is_fraud = (cls_val == 1) | |
| # Extract V1-V28 | |
| features = [] | |
| for j in range(1, 29): | |
| key = f"V{j}" | |
| features.append(float(row[key])) | |
| t = TransactionWithLabel( | |
| transaction_id=f"TXN-{i+1:06d}-{hex(int(time_val))[2:].upper()}", | |
| Time=time_val, | |
| features=features, | |
| Amount=amount_val, | |
| is_fraud=is_fraud, | |
| fraud_reason="Class 1 (Fraud)" if is_fraud else None | |
| ) | |
| transactions.append(t) | |
| return transactions | |