diff --git a/QUICKSTART.md b/QUICKSTART.md deleted file mode 100644 index 89086b4..0000000 --- a/QUICKSTART.md +++ /dev/null @@ -1,225 +0,0 @@ -# 快速开始指南 - -本指南将帮助您在5分钟内运行信用卡欺诈检测系统。 - -## 前置要求 - -- Python 3.10 或更高版本 -- pip(Python包管理器) - -## 安装步骤 - -### 1. 克隆仓库 - -```bash -git clone -cd Credit-Card-Fraud-Detection -``` - -### 2. 创建虚拟环境(推荐) - -**Windows:** -```bash -python -m venv venv -venv\Scripts\activate -``` - -**Linux/Mac:** -```bash -python3 -m venv venv -source venv/bin/activate -``` - -### 3. 安装依赖 - -**方式1: 使用 requirements.txt(推荐)** -```bash -pip install -r requirements.txt -``` - -**方式2: 使用 setup.py** -```bash -pip install -e . -``` - -**方式3: 使用 uv(需要先安装 uv)** -```bash -pip install uv -uv sync -``` - -### 4. 准备数据 - -确保 `data/creditcard.csv` 文件存在。如果不存在,请: - -1. 从 Kaggle 下载数据集: https://www.kaggle.com/mlg-ulb/creditcardfraud -2. 将下载的 `creditcard.csv` 文件放入 `data/` 目录 - -### 5. 训练模型 - -```bash -python src/train.py -``` - -训练完成后,模型文件将保存在 `models/` 目录中: -- `random_forest_model.joblib` - 随机森林模型 -- `logistic_regression_model.joblib` - 逻辑回归模型 -- `scaler.joblib` - 特征缩放器 - -### 6. 运行应用 - -**方式1: 使用 agent_app.py(推荐)** -```bash -python src/agent_app.py -``` - -这将自动启动 Web 界面并在浏览器中打开。 - -**方式2: 直接运行 Streamlit** -```bash -streamlit run src/streamlit_app.py -``` - -## 使用说明 - -### Web 界面使用 - -1. **选择输入方式** - - 上传CSV文件:批量处理交易数据 - - 手动输入:输入30个特征值 - -2. **输入特征** - - Time: 交易时间(秒) - - V1-V28: PCA转换后的特征 - - Amount: 交易金额 - -3. **点击"检测欺诈"按钮** - - 系统会显示预测结果 - - 查看特征解释 - - 获取行动建议 - -### 命令行使用 - -```python -from src.agent_app import create_agent - -agent = create_agent() - -transaction = [ - 0, -1.3598071336738, -0.0727811733098497, 2.53634673796914, 1.37815522427443, - -0.338320769942518, 0.462387777762292, 0.239598554061257, 0.0986979012610507, - 0.363786969611213, 0.0907941719789316, -0.551599533260813, -0.617800855762348, - -0.991389847235408, -0.311169353699879, 1.46817697209427, -0.470400525259478, - 0.207971241929242, 0.0257905801985591, 0.403992960255733, 0.251412098239705, - -0.018306777944153, 0.277837575558899, -0.110473910188767, 0.0669280749146731, - 0.128539358273528, -0.189114843888824, 0.133558376740387, -0.0210530534538215, - 149.62 -] - -result = agent.process_transaction(transaction) -print(f"预测类别: {result.evaluation.class_name}") -print(f"欺诈概率: {result.evaluation.fraud_probability:.4f}") -``` - -## 运行测试 - -```bash -# 运行所有测试 -pytest tests/ - -# 运行特定测试文件 -pytest tests/test_data.py - -# 查看测试覆盖率 -pytest tests/ --cov=src --cov-report=html -``` - -## 常见问题 - -### Q1: 找不到数据文件 - -**错误信息**: `FileNotFoundError: data/creditcard.csv` - -**解决方案**: -1. 确保数据文件存在于 `data/` 目录 -2. 从 Kaggle 下载数据集并放入正确位置 - -### Q2: 模型文件不存在 - -**错误信息**: `RuntimeError: 模型或缩放器加载失败` - -**解决方案**: -```bash -# 先训练模型 -python src/train.py -``` - -### Q3: 依赖安装失败 - -**错误信息**: `pip install` 失败 - -**解决方案**: -1. 确保使用 Python 3.10+ -2. 升级 pip: `pip install --upgrade pip` -3. 使用国内镜像源: `pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple` - -### Q4: Streamlit 无法启动 - -**错误信息**: `streamlit not found` - -**解决方案**: -```bash -pip install streamlit -``` - -### Q5: 端口被占用 - -**错误信息**: `Address already in use` - -**解决方案**: -```bash -# 使用不同端口启动 -streamlit run src/streamlit_app.py --server.port 8502 -``` - -## 项目结构 - -``` -Credit-Card-Fraud-Detection/ -├── data/ # 数据目录 -│ └── creditcard.csv # 信用卡交易数据 -├── models/ # 模型目录 -│ ├── random_forest_model.joblib -│ ├── logistic_regression_model.joblib -│ └── scaler.joblib -├── src/ # 源代码 -│ ├── agent_app.py # Agent 入口(推荐使用) -│ ├── streamlit_app.py # Streamlit Web 应用 -│ ├── train.py # 模型训练 -│ ├── infer.py # 推理接口 -│ ├── data.py # 数据处理 -│ └── features.py # 特征定义 -├── tests/ # 测试文件 -├── requirements.txt # Python 依赖 -├── setup.py # 安装脚本 -├── QUICKSTART.md # 快速开始指南(本文件) -└── README.md # 详细文档 -``` - -## 下一步 - -- 阅读 [README.md](README.md) 了解项目详情 -- 查看 [src/](src/) 目录下的源代码 -- 运行测试确保一切正常 -- 开始使用系统进行欺诈检测 - -## 技术支持 - -如遇到问题,请: -1. 检查本指南的"常见问题"部分 -2. 查看 [README.md](README.md) 获取更多信息 -3. 提交 Issue 到项目仓库 - -## 许可证 - -MIT License diff --git a/auto_install.py b/auto_install.py deleted file mode 100644 index 7502795..0000000 --- a/auto_install.py +++ /dev/null @@ -1,241 +0,0 @@ -""" -信用卡欺诈检测系统 - 自动化安装脚本 -跨平台支持:Windows、Linux、macOS -""" - -import sys -import subprocess -import os -from pathlib import Path -import time - - -def print_header(text): - """打印标题""" - print("=" * 60) - print(text) - print("=" * 60) - print() - - -def print_step(step_num, total_steps, description): - """打印步骤信息""" - print(f"[步骤 {step_num}/{total_steps}] {description}") - - -def run_command(command, description=""): - """运行命令并处理错误""" - try: - if description: - print(f" 正在执行: {description}") - - result = subprocess.run( - command, - shell=True, - check=True, - capture_output=True, - text=True - ) - - if result.stdout: - print(result.stdout) - - return True - except subprocess.CalledProcessError as e: - print(f" [错误] 命令执行失败") - if e.stderr: - print(f" 错误信息: {e.stderr}") - return False - - -def check_python_version(): - """检查Python版本""" - print_step(1, 5, "检查Python版本...") - - version = sys.version_info - print(f" Python版本: {version.major}.{version.minor}.{version.micro}") - - if version.major == 3 and version.minor >= 10: - print(" ✓ Python版本符合要求 (>= 3.10)") - return True - else: - print(" ✗ Python版本不符合要求,需要3.10或更高版本") - print(" 请从 https://www.python.org/downloads/ 下载最新版本") - return False - - -def install_dependencies(): - """安装Python依赖""" - print_step(2, 5, "安装Python依赖...") - print(" 正在安装依赖包,这可能需要几分钟...") - - # 尝试使用pip安装 - success = run_command( - f"{sys.executable} -m pip install -r requirements.txt", - "安装依赖包" - ) - - if success: - print(" ✓ 依赖安装完成") - return True - else: - print(" ✗ 依赖安装失败") - print(" 请检查网络连接或尝试使用国内镜像源:") - print(f" {sys.executable} -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple") - return False - - -def check_data_file(): - """检查数据文件""" - print_step(3, 5, "检查数据文件...") - - data_file = Path("data/creditcard.csv") - - if data_file.exists(): - file_size = data_file.stat().st_size / (1024 * 1024) # MB - print(f" ✓ 数据文件已存在 (大小: {file_size:.2f} MB)") - return True - else: - print(" ✗ 未找到数据文件 data/creditcard.csv") - print() - print(" 请从以下地址下载数据集:") - print(" https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud") - print() - print(" 下载后将 creditcard.csv 文件放入 data/ 目录") - print() - - response = input(" 数据文件已准备好吗?(Y/N): ").strip().upper() - if response == 'Y': - print(" ✓ 继续安装...") - return True - else: - print(" ✗ 安装已取消") - return False - - -def check_model_files(): - """检查并训练模型""" - print_step(4, 5, "检查模型文件...") - - models_dir = Path("models") - model_file = models_dir / "random_forest_model.joblib" - - if model_file.exists(): - file_size = model_file.stat().st_size / 1024 # KB - print(f" ✓ 模型文件已存在 (大小: {file_size:.2f} KB)") - return True - else: - print(" 模型文件不存在,开始训练模型...") - print(" 这可能需要几分钟,请耐心等待...") - - success = run_command( - f"{sys.executable} src/train.py", - "训练模型" - ) - - if success: - print(" ✓ 模型训练完成") - return True - else: - print(" ✗ 模型训练失败") - return False - - -def run_environment_check(): - """运行环境检查""" - print_step(5, 5, "运行环境检查...") - - success = run_command( - f"{sys.executable} check_environment.py", - "检查环境" - ) - - if success: - print(" ✓ 环境检查通过") - else: - print(" ⚠ 环境检查发现问题,但将继续启动应用") - - return True - - -def launch_application(): - """启动应用""" - print() - print_header("安装完成!正在启动Web界面...") - print() - print("提示:") - print("- Web界面将在浏览器中自动打开") - print("- 如果没有自动打开,请访问: http://localhost:8501") - print("- 按 Ctrl+C 可以停止服务") - print() - - # 等待几秒让用户看到提示 - time.sleep(2) - - # 启动应用 - try: - subprocess.run( - f"{sys.executable} src/agent_app.py", - shell=True, - check=True - ) - except KeyboardInterrupt: - print() - print("应用已停止") - except Exception as e: - print(f"启动应用时出错: {e}") - - -def main(): - """主函数""" - print_header("信用卡欺诈检测系统 - 自动化安装脚本") - - # 检查Python版本 - if not check_python_version(): - input("按回车键退出...") - sys.exit(1) - - print() - - # 安装依赖 - if not install_dependencies(): - input("按回车键退出...") - sys.exit(1) - - print() - - # 检查数据文件 - if not check_data_file(): - input("按回车键退出...") - sys.exit(1) - - print() - - # 检查模型文件 - if not check_model_files(): - input("按回车键退出...") - sys.exit(1) - - print() - - # 运行环境检查 - run_environment_check() - - # 启动应用 - launch_application() - - -if __name__ == "__main__": - try: - main() - except KeyboardInterrupt: - print() - print("安装已取消") - sys.exit(1) - except Exception as e: - print() - print(f"安装过程中出现错误: {e}") - import traceback - traceback.print_exc() - input("按回车键退出...") - sys.exit(1) diff --git a/check_environment.py b/check_environment.py deleted file mode 100644 index 569bf71..0000000 --- a/check_environment.py +++ /dev/null @@ -1,193 +0,0 @@ -""" -环境检查脚本 -用于验证项目依赖和环境配置是否正确 -""" - -import sys -import importlib -from pathlib import Path - -def check_python_version(): - """检查Python版本""" - print("=" * 60) - print("检查 Python 版本...") - print("=" * 60) - - version = sys.version_info - print(f"当前 Python 版本: {version.major}.{version.minor}.{version.micro}") - - if version.major == 3 and version.minor >= 10: - print("✓ Python 版本符合要求 (>= 3.10)") - return True - else: - print("✗ Python 版本不符合要求,需要 3.10 或更高版本") - return False - -def check_dependencies(): - """检查必要的依赖包""" - print("\n" + "=" * 60) - print("检查依赖包...") - print("=" * 60) - - required_packages = { - 'numpy': 'numpy', - 'polars': 'polars', - 'sklearn': 'scikit-learn', - 'imblearn': 'imbalanced-learn', - 'matplotlib': 'matplotlib', - 'seaborn': 'seaborn', - 'joblib': 'joblib', - 'pydantic': 'pydantic', - 'streamlit': 'streamlit', - } - - missing_packages = [] - - for module_name, package_name in required_packages.items(): - try: - module = importlib.import_module(module_name) - version = getattr(module, '__version__', 'unknown') - print(f"✓ {package_name:20s} - 版本: {version}") - except ImportError: - print(f"✗ {package_name:20s} - 未安装") - missing_packages.append(package_name) - - if missing_packages: - print(f"\n缺少 {len(missing_packages)} 个依赖包") - print(f"请运行: pip install {' '.join(missing_packages)}") - return False - else: - print("\n✓ 所有依赖包已正确安装") - return True - -def check_data_files(): - """检查数据文件""" - print("\n" + "=" * 60) - print("检查数据文件...") - print("=" * 60) - - data_dir = Path("data") - creditcard_csv = data_dir / "creditcard.csv" - - if creditcard_csv.exists(): - file_size = creditcard_csv.stat().st_size / (1024 * 1024) # MB - print(f"✓ data/creditcard.csv 存在 (大小: {file_size:.2f} MB)") - return True - else: - print("✗ data/creditcard.csv 不存在") - print("请从以下地址下载数据集:") - print("https://www.kaggle.com/mlg-ulb/creditcardfraud") - print("并将 creditcard.csv 文件放入 data/ 目录") - return False - -def check_model_files(): - """检查模型文件""" - print("\n" + "=" * 60) - print("检查模型文件...") - print("=" * 60) - - models_dir = Path("models") - required_models = [ - "random_forest_model.joblib", - "logistic_regression_model.joblib", - "scaler.joblib" - ] - - missing_models = [] - - for model_file in required_models: - model_path = models_dir / model_file - if model_path.exists(): - file_size = model_path.stat().st_size / 1024 # KB - print(f"✓ {model_file:35s} (大小: {file_size:.2f} KB)") - else: - print(f"✗ {model_file:35s} - 不存在") - missing_models.append(model_file) - - if missing_models: - print(f"\n缺少 {len(missing_models)} 个模型文件") - print("请运行: python src/train.py 来训练模型") - return False - else: - print("\n✓ 所有模型文件已存在") - return True - -def check_source_files(): - """检查源代码文件""" - print("\n" + "=" * 60) - print("检查源代码文件...") - print("=" * 60) - - src_dir = Path("src") - required_files = [ - "__init__.py", - "data.py", - "features.py", - "train.py", - "infer.py", - "agent_app.py", - "streamlit_app.py" - ] - - missing_files = [] - - for file_name in required_files: - file_path = src_dir / file_name - if file_path.exists(): - print(f"✓ src/{file_name}") - else: - print(f"✗ src/{file_name} - 不存在") - missing_files.append(file_name) - - if missing_files: - print(f"\n缺少 {len(missing_files)} 个源代码文件") - return False - else: - print("\n✓ 所有源代码文件完整") - return True - -def run_all_checks(): - """运行所有检查""" - print("\n" + "=" * 60) - print("信用卡欺诈检测系统 - 环境检查") - print("=" * 60) - - results = { - "Python 版本": check_python_version(), - "依赖包": check_dependencies(), - "数据文件": check_data_files(), - "模型文件": check_model_files(), - "源代码文件": check_source_files(), - } - - print("\n" + "=" * 60) - print("检查结果汇总") - print("=" * 60) - - for check_name, result in results.items(): - status = "✓ 通过" if result else "✗ 失败" - print(f"{check_name:15s}: {status}") - - all_passed = all(results.values()) - - print("\n" + "=" * 60) - if all_passed: - print("✓ 所有检查通过!您可以运行系统了") - print("\n运行命令:") - print(" python src/agent_app.py") - else: - print("✗ 部分检查未通过,请根据上述提示解决问题") - print("\n快速修复:") - if not results["依赖包"]: - print(" 1. 安装依赖: pip install -r requirements.txt") - if not results["数据文件"]: - print(" 2. 下载数据: 从 Kaggle 下载 creditcard.csv 到 data/ 目录") - if not results["模型文件"]: - print(" 3. 训练模型: python src/train.py") - print("=" * 60) - - return all_passed - -if __name__ == "__main__": - success = run_all_checks() - sys.exit(0 if success else 1) diff --git a/install.bat b/install.bat deleted file mode 100644 index b334040..0000000 --- a/install.bat +++ /dev/null @@ -1,112 +0,0 @@ -@echo off -chcp 65001 >nul -setlocal enabledelayedexpansion - -echo ============================================================ -echo 信用卡欺诈检测系统 - 一键安装脚本 -echo ============================================================ -echo. - -REM 检查Python是否安装 -python --version >nul 2>&1 -if %errorlevel% neq 0 ( - echo [错误] 未检测到Python,请先安装Python 3.10或更高版本 - echo 下载地址: https://www.python.org/downloads/ - pause - exit /b 1 -) - -echo [步骤 1/5] 检查Python版本... -for /f "tokens=2" %%i in ('python --version 2^>^&1') do set PYTHON_VERSION=%%i -echo Python版本: %PYTHON_VERSION% -echo. - -REM 检查Python版本是否满足要求 -for /f "tokens=1,2 delims=." %%a in ("%PYTHON_VERSION%") do ( - set MAJOR=%%a - set MINOR=%%b -) - -if %MAJOR% lss 3 ( - echo [错误] Python版本过低,需要3.10或更高版本 - pause - exit /b 1 -) - -if %MAJOR% equ 3 ( - if %MINOR% lss 10 ( - echo [错误] Python版本过低,需要3.10或更高版本 - pause - exit /b 1 - ) -) - -echo [步骤 2/5] 安装Python依赖... -echo 正在安装依赖包,这可能需要几分钟... -pip install -r requirements.txt -if %errorlevel% neq 0 ( - echo [错误] 依赖安装失败 - echo 请检查网络连接或尝试使用国内镜像源: - echo pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple - pause - exit /b 1 -) -echo 依赖安装完成 -echo. - -echo [步骤 3/5] 检查数据文件... -if not exist "data\creditcard.csv" ( - echo [警告] 未找到数据文件 data\creditcard.csv - echo. - echo 请从以下地址下载数据集: - echo https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud - echo. - echo 下载后将 creditcard.csv 文件放入 data\ 目录 - echo. - set /p DATA_READY="数据文件已准备好吗?(Y/N): " - if /i not "!DATA_READY!"=="Y" ( - echo 安装已取消 - pause - exit /b 1 - ) -) else ( - echo 数据文件已存在 -) -echo. - -echo [步骤 4/5] 检查模型文件... -if not exist "models\random_forest_model.joblib" ( - echo 模型文件不存在,开始训练模型... - echo 这可能需要几分钟,请耐心等待... - python src\train.py - if %errorlevel% neq 0 ( - echo [错误] 模型训练失败 - pause - exit /b 1 - ) - echo 模型训练完成 -) else ( - echo 模型文件已存在 -) -echo. - -echo [步骤 5/5] 运行环境检查... -python check_environment.py -if %errorlevel% neq 0 ( - echo [警告] 环境检查发现问题,但将继续启动应用 -) -echo. - -echo ============================================================ -echo 安装完成!正在启动Web界面... -echo ============================================================ -echo. -echo 提示: -echo - Web界面将在浏览器中自动打开 -echo - 如果没有自动打开,请访问: http://localhost:8501 -echo - 按 Ctrl+C 可以停止服务 -echo. - -python src\agent_app.py - -pause diff --git a/install.sh b/install.sh deleted file mode 100644 index e990438..0000000 --- a/install.sh +++ /dev/null @@ -1,96 +0,0 @@ -#!/bin/bash - -set -e - -echo "============================================================" -echo "信用卡欺诈检测系统 - 一键安装脚本" -echo "============================================================" -echo "" - -# 检查Python是否安装 -if ! command -v python3 &> /dev/null; then - echo "[错误] 未检测到Python,请先安装Python 3.10或更高版本" - echo "Ubuntu/Debian: sudo apt-get install python3 python3-pip" - echo "CentOS/RHEL: sudo yum install python3 python3-pip" - echo "macOS: brew install python3" - exit 1 -fi - -echo "[步骤 1/5] 检查Python版本..." -PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}') -echo "Python版本: $PYTHON_VERSION" -echo "" - -# 检查Python版本是否满足要求 -PYTHON_MAJOR=$(echo $PYTHON_VERSION | cut -d. -f1) -PYTHON_MINOR=$(echo $PYTHON_VERSION | cut -d. -f2) - -if [ "$PYTHON_MAJOR" -lt 3 ] || ([ "$PYTHON_MAJOR" -eq 3 ] && [ "$PYTHON_MINOR" -lt 10 ]); then - echo "[错误] Python版本过低,需要3.10或更高版本" - exit 1 -fi - -echo "[步骤 2/5] 安装Python依赖..." -echo "正在安装依赖包,这可能需要几分钟..." -pip3 install -r requirements.txt -if [ $? -ne 0 ]; then - echo "[错误] 依赖安装失败" - echo "请检查网络连接或尝试使用国内镜像源:" - echo "pip3 install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple" - exit 1 -fi -echo "依赖安装完成" -echo "" - -echo "[步骤 3/5] 检查数据文件..." -if [ ! -f "data/creditcard.csv" ]; then - echo "[警告] 未找到数据文件 data/creditcard.csv" - echo "" - echo "请从以下地址下载数据集:" - echo "https://www.kaggle.com/datasets/mlg-ulb/creditcardfraud" - echo "" - echo "下载后将 creditcard.csv 文件放入 data/ 目录" - echo "" - read -p "数据文件已准备好吗?(Y/N): " DATA_READY - if [[ ! "$DATA_READY" =~ ^[Yy]$ ]]; then - echo "安装已取消" - exit 1 - fi -else - echo "数据文件已存在" -fi -echo "" - -echo "[步骤 4/5] 检查模型文件..." -if [ ! -f "models/random_forest_model.joblib" ]; then - echo "模型文件不存在,开始训练模型..." - echo "这可能需要几分钟,请耐心等待..." - python3 src/train.py - if [ $? -ne 0 ]; then - echo "[错误] 模型训练失败" - exit 1 - fi - echo "模型训练完成" -else - echo "模型文件已存在" -fi -echo "" - -echo "[步骤 5/5] 运行环境检查..." -python3 check_environment.py -if [ $? -ne 0 ]; then - echo "[警告] 环境检查发现问题,但将继续启动应用" -fi -echo "" - -echo "============================================================" -echo "安装完成!正在启动Web界面..." -echo "============================================================" -echo "" -echo "提示:" -echo "- Web界面将在浏览器中自动打开" -echo "- 如果没有自动打开,请访问: http://localhost:8501" -echo "- 按 Ctrl+C 可以停止服务" -echo "" - -python3 src/agent_app.py diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 7b5a7f4..0000000 --- a/requirements.txt +++ /dev/null @@ -1,9 +0,0 @@ -numpy>=1.24.0 -polars>=0.19.0 -scikit-learn>=1.3.0 -imbalanced-learn>=0.11.0 -matplotlib>=3.7.0 -seaborn>=0.12.0 -joblib>=1.3.0 -pydantic>=2.0.0 -streamlit>=1.28.0 diff --git a/setup.py b/setup.py deleted file mode 100644 index 3ac38c2..0000000 --- a/setup.py +++ /dev/null @@ -1,25 +0,0 @@ -from setuptools import setup, find_packages - -setup( - name="creditcard-fraud-detection", - version="0.1.0", - description="信用卡欺诈检测系统", - packages=find_packages(), - python_requires=">=3.10", - install_requires=[ - "numpy>=1.24.0", - "polars>=0.19.0", - "scikit-learn>=1.3.0", - "imbalanced-learn>=0.11.0", - "matplotlib>=3.7.0", - "seaborn>=0.12.0", - "joblib>=1.3.0", - "pydantic>=2.0.0", - "streamlit>=1.28.0", - ], - entry_points={ - "console_scripts": [ - "train=src.train:train_and_evaluate", - ], - }, -)