# equipment_fault_prediction.py
# 设备故障预测(异常检测)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest
from sklearn.svm import OneClassSVM
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
from sklearn.model_selection import train_test_split
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')

# 配置matplotlib中文显示
plt.rcParams['font.sans-serif'] = ['WenQuanYi Zen Hei', 'SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

def generate_equipment_data(n_samples=10000, fault_ratio=0.05):
    """
    生成设备运行模拟数据
    
    参数:
    - n_samples: 总样本数
    - fault_ratio: 故障样本比例
    
    返回:
    - DataFrame: 包含设备参数和故障标签的数据
    """
    np.random.seed(42)
    n_normal = int(n_samples * (1 - fault_ratio))
    n_fault = n_samples - n_normal
    
    # 正常数据生成(基于多元正态分布)
    normal_params = {
        'temperature': np.random.normal(75, 5, n_normal),
        'vibration': np.random.normal(2.5, 0.5, n_normal),
        'current': np.random.normal(45, 3, n_normal),
        'voltage': np.random.normal(380, 5, n_normal),
        'runtime': np.random.exponential(100, n_normal),
        'pressure': np.random.normal(5.5, 0.5, n_normal),
        'speed': np.random.normal(1450, 50, n_normal)
    }
    
    # 故障数据生成
    fault_params = {
        'temperature': np.concatenate([
            np.random.normal(95, 8, int(n_fault * 0.4)),
            np.random.normal(85, 10, int(n_fault * 0.3)),
            np.random.normal(110, 5, int(n_fault * 0.3))
        ]),
        'vibration': np.concatenate([
            np.random.normal(5.5, 1.5, int(n_fault * 0.5)),
            np.random.normal(8, 2, int(n_fault * 0.5))
        ]),
        'current': np.concatenate([
            np.random.normal(55, 8, int(n_fault * 0.6)),
            np.random.normal(35, 5, int(n_fault * 0.4))
        ]),
        'voltage': np.concatenate([
            np.random.normal(350, 15, int(n_fault * 0.5)),
            np.random.normal(410, 10, int(n_fault * 0.5))
        ]),
        'runtime': np.random.exponential(500, n_fault),
        'pressure': np.concatenate([
            np.random.normal(7.5, 1, int(n_fault * 0.5)),
            np.random.normal(3.5, 1, int(n_fault * 0.5))
        ]),
        'speed': np.concatenate([
            np.random.normal(1200, 100, int(n_fault * 0.5)),
            np.random.normal(1700, 100, int(n_fault * 0.5))
        ])
    }
    
    normal_data = pd.DataFrame(normal_params)
    fault_data = pd.DataFrame(fault_params)
    normal_data['label'] = 0
    fault_data['label'] = 1
    
    data = pd.concat([normal_data, fault_data], ignore_index=True)
    data['timestamp'] = pd.date_range('2024-01-01', periods=n_samples, freq='15min')
    data['temp_vibration_ratio'] = data['temperature'] / data['vibration']
    data['power_consumption'] = data['voltage'] * data['current'] / 1000
    
    data = data.sample(frac=1, random_state=42).reset_index(drop=True)
    
    return data

def create_advanced_features(data):
    """创建高级特征"""
    df = data.copy()
    
    # 变化率特征
    df['temp_change_rate'] = df['temperature'].pct_change() * 100
    df['vibration_change_rate'] = df['vibration'].pct_change() * 100
    df['current_change_rate'] = df['current'].pct_change() * 100
    
    # 多参数组合特征
    df['stress_index'] = (df['temperature'] / 80) * (df['vibration'] / 3) * (df['current'] / 45)
    df['energy_efficiency'] = df['speed'] / (df['power_consumption'] + 1e-6)
    df['health_score'] = 100 - (
        (df['temperature'] - 75).clip(0, 999) / 2 +
        (df['vibration'] - 2.5).clip(0, 999) * 10 +
        (df['current'] - 45).abs() / 2 +
        (df['voltage'] - 380).abs() / 4
    ).clip(0, 100)
    
    # 滚动统计特征
    for window in [5, 10]:
        df[f'temp_rolling_mean_{window}'] = df['temperature'].rolling(window=window, min_periods=1).mean()
        df[f'vibration_rolling_mean_{window}'] = df['vibration'].rolling(window=window, min_periods=1).mean()
    
    # 填充NaN
    df = df.fillna(method='ffill').fillna(method='bfill').fillna(0)
    
    return df

def prepare_features(data, feature_cols=None):
    """准备特征数据"""
    base_features = ['temperature', 'vibration', 'current', 'voltage', 
                    'runtime', 'pressure', 'speed', 'temp_vibration_ratio', 
                    'power_consumption', 'temp_change_rate', 'vibration_change_rate',
                    'stress_index', 'health_score']
    
    if feature_cols is None:
        feature_cols = base_features
    
    # 确保所有特征都存在
    available_features = [f for f in feature_cols if f in data.columns]
    missing_features = set(feature_cols) - set(available_features)
    if missing_features:
        print(f"警告:缺少特征 {missing_features},使用默认值0填充")
        for f in missing_features:
            data[f] = 0
        available_features = feature_cols
    
    X = data[available_features]
    y = data['label'] if 'label' in data.columns else None
    
    return X, y, available_features

def train_anomaly_detection_models(X_train, X_test, y_train, y_test):
    """训练多种异常检测模型"""
    
    models = {}
    predictions = {}
    scores = {}
    
    # 1. 孤立森林算法
    print("\n训练孤立森林模型...")
    iso_forest = IsolationForest(
        contamination=0.1,
        random_state=42,
        n_estimators=200,
        max_samples='auto',
        bootstrap=False,
        verbose=0
    )
    iso_forest.fit(X_train)
    models['IsolationForest'] = iso_forest
    
    y_pred_iso = iso_forest.predict(X_test)
    y_pred_iso = np.where(y_pred_iso == -1, 1, 0)
    predictions['IsolationForest'] = y_pred_iso
    scores['IsolationForest'] = iso_forest.score_samples(X_test)
    
    # 2. OneClass SVM算法
    print("训练OneClass SVM模型...")
    svm_model = OneClassSVM(nu=0.1, kernel='rbf', gamma='auto', verbose=False)
    svm_model.fit(X_train)
    models['OneClassSVM'] = svm_model
    
    y_pred_svm = svm_model.predict(X_test)
    y_pred_svm = np.where(y_pred_svm == -1, 1, 0)
    predictions['OneClassSVM'] = y_pred_svm
    scores['OneClassSVM'] = svm_model.score_samples(X_test)
    
    # 3. 扩展孤立森林
    print("训练扩展孤立森林(低污染)...")
    iso_forest_low = IsolationForest(contamination=0.05, random_state=42)
    iso_forest_low.fit(X_train)
    models['IsolationForest_Low'] = iso_forest_low
    
    y_pred_iso_low = iso_forest_low.predict(X_test)
    y_pred_iso_low = np.where(y_pred_iso_low == -1, 1, 0)
    predictions['IsolationForest_Low'] = y_pred_iso_low
    scores['IsolationForest_Low'] = iso_forest_low.score_samples(X_test)
    
    return models, predictions, scores

def evaluate_models(y_test, predictions):
    """评估模型性能"""
    results = {}
    
    print("\n" + "="*80)
    print("模型评估结果")
    print("="*80)
    
    for model_name, y_pred in predictions.items():
        print(f"\n{model_name}:")
        print("-" * 40)
        
        accuracy = accuracy_score(y_test, y_pred)
        precision = precision_score(y_test, y_pred, zero_division=0)
        recall = recall_score(y_test, y_pred, zero_division=0)
        f1 = f1_score(y_test, y_pred, zero_division=0)
        
        print(f"准确率 (Accuracy): {accuracy:.4f}")
        print(f"精确率 (Precision): {precision:.4f}")
        print(f"召回率 (Recall): {recall:.4f}")
        print(f"F1分数: {f1:.4f}")
        
        cm = confusion_matrix(y_test, y_pred)
        print(f"混淆矩阵:\n{cm}")
        
        results[model_name] = {
            'accuracy': accuracy,
            'precision': precision,
            'recall': recall,
            'f1': f1,
            'confusion_matrix': cm
        }
    
    return results

def plot_anomaly_detection_results(data, test_indices, predictions, scores, feature_names, y_test):
    """可视化异常检测结果"""
    
    try:
        fig = plt.figure(figsize=(16, 12))
        
        # 1. 原始数据分布
        ax1 = fig.add_subplot(2, 3, 1)
        scatter1 = ax1.scatter(data.iloc[test_indices]['temperature'], 
                              data.iloc[test_indices]['vibration'],
                              c=predictions['IsolationForest'], 
                              cmap='RdYlGn', alpha=0.6, s=30)
        ax1.set_xlabel('温度 (°C)')
        ax1.set_ylabel('振动 (mm/s)')
        ax1.set_title('孤立森林异常检测结果')
        
        # 2. 异常分数分布
        ax2 = fig.add_subplot(2, 3, 2)
        for model_name, score in scores.items():
            if 'IsolationForest' in model_name:
                ax2.hist(score, bins=50, alpha=0.5, label=model_name)
        ax2.set_xlabel('异常分数')
        ax2.set_ylabel('频次')
        ax2.set_title('异常分数分布')
        ax2.legend()
        ax2.grid(True, alpha=0.3)
        
        # 3. 特征相关性热力图
        ax3 = fig.add_subplot(2, 3, 3)
        corr_matrix = data[feature_names[:8]].corr()
        im = ax3.imshow(corr_matrix, cmap='coolwarm', aspect='auto')
        ax3.set_xticks(range(len(feature_names[:8])))
        ax3.set_yticks(range(len(feature_names[:8])))
        ax3.set_xticklabels(feature_names[:8], rotation=45, ha='right', fontsize=8)
        ax3.set_yticklabels(feature_names[:8], fontsize=8)
        ax3.set_title('特征相关性矩阵')
        plt.colorbar(im, ax=ax3)
        
        # 4. 模型性能对比
        ax4 = fig.add_subplot(2, 3, 4)
        metrics = ['accuracy', 'precision', 'recall', 'f1']
        x = np.arange(len(metrics))
        width = 0.25
        
        temp_results = {}
        for model_name in predictions.keys():
            y_pred = predictions[model_name]
            temp_results[model_name] = {
                'accuracy': accuracy_score(y_test, y_pred),
                'precision': precision_score(y_test, y_pred, zero_division=0),
                'recall': recall_score(y_test, y_pred, zero_division=0),
                'f1': f1_score(y_test, y_pred, zero_division=0)
            }
        
        for i, (model_name, results) in enumerate(temp_results.items()):
            values = [results[m] for m in metrics]
            ax4.bar(x + i*width, values, width, label=model_name)
        
        ax4.set_xlabel('评估指标')
        ax4.set_ylabel('得分')
        ax4.set_title('模型性能对比')
        ax4.set_xticks(x + width)
        ax4.set_xticklabels(metrics)
        ax4.legend(fontsize=8)
        ax4.set_ylim([0, 1])
        
        # 5. 时间序列异常检测
        ax5 = fig.add_subplot(2, 3, 5)
        test_data = data.iloc[test_indices].copy()
        test_data['predicted_anomaly'] = predictions['IsolationForest']
        test_data['anomaly_score'] = scores['IsolationForest']
        
        ax5.plot(test_data.index, test_data['temperature'], 'b-', alpha=0.7, label='温度')
        anomaly_points = test_data[test_data['predicted_anomaly'] == 1]
        ax5.scatter(anomaly_points.index, anomaly_points['temperature'], 
                   color='red', s=50, label='检测到的异常', zorder=5)
        ax5.set_xlabel('时间序列')
        ax5.set_ylabel('温度 (°C)')
        ax5.set_title('时序异常检测')
        ax5.legend()
        ax5.grid(True, alpha=0.3)
        
        # 6. 健康度评分分布
        ax6 = fig.add_subplot(2, 3, 6)
        data_with_health = create_advanced_features(data)
        health_scores = data_with_health['health_score'].iloc[test_indices]
        
        ax6.hist(health_scores[predictions['IsolationForest'] == 0], 
                bins=30, alpha=0.5, label='正常设备', color='green')
        ax6.hist(health_scores[predictions['IsolationForest'] == 1], 
                bins=30, alpha=0.5, label='异常设备', color='red')
        ax6.set_xlabel('健康度评分')
        ax6.set_ylabel('频次')
        ax6.set_title('设备健康度分布')
        ax6.legend()
        ax6.grid(True, alpha=0.3)
        
        plt.tight_layout()
        plt.show()
    except Exception as e:
        print(f"可视化出错: {e}")
        print("跳过可视化,继续执行...")

def equipment_anomaly_detection():
    """设备异常检测主函数"""
    
    print("="*80)
    print("设备故障预测系统 - 基于运行参数的异常检测")
    print("="*80)
    
    # 1. 生成模拟数据
    print("\n1. 生成设备运行数据...")
    data = generate_equipment_data(n_samples=5000, fault_ratio=0.08)
    print(f"总样本数: {len(data)}")
    print(f"正常样本: {len(data[data['label']==0])}")
    print(f"故障样本: {len(data[data['label']==1])}")
    print(f"故障比例: {len(data[data['label']==1])/len(data):.2%}")
    
    # 2. 数据预处理
    print("\n2. 数据预处理...")
    data = create_advanced_features(data)
    
    # 选择特征
    feature_cols = ['temperature', 'vibration', 'current', 'voltage', 
                   'runtime', 'pressure', 'speed', 'temp_vibration_ratio',
                   'power_consumption', 'temp_change_rate', 'vibration_change_rate',
                   'stress_index', 'health_score']
    
    X, y, used_features = prepare_features(data, feature_cols)
    
    # 标准化
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)
    X_scaled = pd.DataFrame(X_scaled, columns=used_features)
    
    print(f"使用特征数: {len(used_features)}")
    print(f"特征列表: {used_features[:5]}...")
    
    # 3. 划分数据集
    train_size = int(len(X_scaled) * 0.7)
    X_train = X_scaled[:train_size]
    X_test = X_scaled[train_size:]
    y_train = y[:train_size]
    y_test = y[train_size:]
    test_indices = list(range(train_size, len(X_scaled)))
    
    print(f"\n训练集大小: {len(X_train)}")
    print(f"测试集大小: {len(X_test)}")
    print(f"测试集故障比例: {y_test.sum()/len(y_test):.2%}")
    
    # 4. 训练异常检测模型
    print("\n3. 训练异常检测模型...")
    models, predictions, scores = train_anomaly_detection_models(
        X_train, X_test, y_train, y_test
    )
    
    # 5. 评估模型
    evaluate_results = evaluate_models(y_test, predictions)
    
    # 6. 实时监控和预警系统
    print("\n4. 实时监控预警系统...")
    print("-"*80)
    
    print("模拟实时设备监控(最后20个测试样本):")
    print("-"*60)
    
    recent_predictions = predictions['IsolationForest'][-20:]
    recent_actual = y_test[-20:].values if hasattr(y_test, 'values') else y_test[-20:]
    recent_scores = scores['IsolationForest'][-20:]
    
    for i, (pred, actual, score) in enumerate(zip(recent_predictions, recent_actual, recent_scores)):
        status = "⚠️ 异常预警" if pred == 1 else "✓ 正常运行"
        actual_status = "故障" if actual == 1 else "正常"
        match = "✓" if pred == actual else "✗"
        
        print(f"样本{i+1:2d}: {status:10s} | 预测: {pred} | 实际: {actual_status} | "
              f"异常分: {score:.3f} | 匹配: {match}")
        
        if pred == 1:
            print(f"        🔔 预警!设备可能即将发生故障,建议立即检查!")
    
    # 7. 异常特征分析
    print("\n5. 异常特征分析...")
    print("-"*80)
    
    anomaly_indices = np.where(predictions['IsolationForest'] == 1)[0]
    if len(anomaly_indices) > 0:
        original_anomaly_indices = [test_indices[idx] for idx in anomaly_indices[:5]]
        
        print("异常样本的主要特征偏差:")
        for i, (idx, orig_idx) in enumerate(zip(anomaly_indices[:5], original_anomaly_indices[:5])):
            print(f"\n异常样本 {i+1}:")
            original_values = X.iloc[orig_idx]
            mean_values = X.mean()
            
            for col in used_features[:6]:
                original_value = original_values[col]
                mean_value = mean_values[col]
                deviation = (original_value - mean_value) / mean_value * 100 if mean_value != 0 else 0
                print(f"  {col}: {original_value:.2f} (偏离均值: {deviation:+.1f}%)")
    else:
        print("未检测到异常样本")
    
    # 8. 设备健康报告
    print("\n6. 设备健康报告...")
    print("-"*80)
    
    health_scores = data['health_score'].values[test_indices]
    avg_health = health_scores.mean()
    min_health = health_scores.min()
    anomaly_count = predictions['IsolationForest'].sum()
    anomaly_ratio = anomaly_count / len(predictions['IsolationForest'])
    
    print(f"设备整体健康度: {avg_health:.1f}/100")
    print(f"最低健康度: {min_health:.1f}/100")
    print(f"检测到的异常数: {anomaly_count}")
    print(f"异常率: {anomaly_ratio:.2%}")
    
    if avg_health >= 85:
        health_level = "优秀"
        recommendation = "设备运行良好,继续保持定期维护"
    elif avg_health >= 70:
        health_level = "良好"
        recommendation = "建议增加巡检频率,关注关键参数"
    elif avg_health >= 50:
        health_level = "注意"
        recommendation = "存在潜在故障风险,建议安排检修"
    else:
        health_level = "危险"
        recommendation = "设备状态较差,建议立即停机检修"
    
    print(f"健康等级: {health_level}")
    print(f"建议: {recommendation}")
    
    # 9. 可视化结果
    print("\n7. 生成可视化图表...")
    plot_anomaly_detection_results(data, test_indices, predictions, scores, used_features, y_test)
    
    # 10. 返回结果
    results = {
        'models': models,
        'predictions': predictions,
        'scores': scores,
        'evaluation': evaluate_results,
        'scaler': scaler,
        'feature_names': used_features,
        'best_model': models['IsolationForest'],
        'X_train': X_train,
        'X_test': X_test,
        'y_test': y_test,
        'test_indices': test_indices,
        'health_report': {
            'avg_health': avg_health,
            'min_health': min_health,
            'anomaly_count': anomaly_count,
            'anomaly_ratio': anomaly_ratio,
            'health_level': health_level,
            'recommendation': recommendation
        }
    }
    
    print("\n" + "="*80)
    print("设备故障预测完成!")
    print("="*80)
    
    return results

def create_full_features_for_prediction(data, feature_names):
    """为预测创建完整的特征集"""
    df = data.copy()
    
    # 计算所有需要的衍生特征
    if 'temp_vibration_ratio' not in df.columns and 'temperature' in df.columns and 'vibration' in df.columns:
        df['temp_vibration_ratio'] = df['temperature'] / (df['vibration'] + 1e-6)
    
    if 'power_consumption' not in df.columns and 'voltage' in df.columns and 'current' in df.columns:
        df['power_consumption'] = df['voltage'] * df['current'] / 1000
    
    if 'temp_change_rate' not in df.columns and 'temperature' in df.columns:
        df['temp_change_rate'] = df['temperature'].pct_change() * 100
    
    if 'vibration_change_rate' not in df.columns and 'vibration' in df.columns:
        df['vibration_change_rate'] = df['vibration'].pct_change() * 100
    
    if 'stress_index' not in df.columns:
        temp = df.get('temperature', 75)
        vib = df.get('vibration', 2.5)
        curr = df.get('current', 45)
        df['stress_index'] = (temp / 80) * (vib / 3) * (curr / 45)
    
    if 'health_score' not in df.columns:
        temp = df.get('temperature', 75)
        vib = df.get('vibration', 2.5)
        curr = df.get('current', 45)
        volt = df.get('voltage', 380)
        df['health_score'] = 100 - (
            (temp - 75).clip(0, 999) / 2 +
            (vib - 2.5).clip(0, 999) * 10 +
            (curr - 45).abs() / 2 +
            (volt - 380).abs() / 4
        ).clip(0, 100)
    
    # 填充NaN
    df = df.fillna(method='ffill').fillna(method='bfill').fillna(0)
    
    # 确保所有需要的特征都存在
    for feature in feature_names:
        if feature not in df.columns:
            df[feature] = 0
    
    return df[feature_names]

def predict_real_time(model, scaler, feature_names, new_data):
    """
    实时预测新数据的设备状态
    
    参数:
    - model: 训练好的模型
    - scaler: 标准化器
    - feature_names: 特征名称列表(完整的13个特征)
    - new_data: 新的设备数据(DataFrame格式,包含基础参数)
    
    返回:
    - prediction: 预测结果(0正常,1异常)
    - anomaly_score: 异常分数
    - alert_level: 预警级别
    """
    
    # 创建完整的特征集
    full_features = create_full_features_for_prediction(new_data, feature_names)
    
    # 标准化
    full_features_scaled = scaler.transform(full_features)
    
    # 预测
    prediction_raw = model.predict(full_features_scaled)
    prediction = np.where(prediction_raw == -1, 1, 0)
    anomaly_score = model.score_samples(full_features_scaled)
    
    # 预警级别
    if prediction[0] == 1:
        if anomaly_score[0] < -0.5:
            alert_level = "高危"
        elif anomaly_score[0] < -0.2:
            alert_level = "中危"
        else:
            alert_level = "低危"
    else:
        alert_level = "正常"
    
    return prediction[0], anomaly_score[0], alert_level

def real_time_monitoring_demo(results):
    """实时监控演示"""
    print("\n" + "="*80)
    print("实时监控演示")
    print("="*80)
    
    # 模拟新的实时数据(只提供基础参数)
    new_equipment_data = pd.DataFrame({
        'temperature': [78, 96, 73, 88, 102],
        'vibration': [2.6, 5.8, 2.4, 4.2, 7.5],
        'current': [46, 58, 44, 52, 63],
        'voltage': [382, 355, 379, 365, 345],
        'runtime': [120, 450, 80, 320, 580],
        'pressure': [5.6, 7.2, 5.4, 6.5, 8.1],
        'speed': [1460, 1350, 1455, 1400, 1280]
    })
    
    print("\n实时监控5台设备:")
    print("-"*60)
    
    for i in range(len(new_equipment_data)):
        single_data = new_equipment_data.iloc[[i]]
        prediction, score, alert = predict_real_time(
            results['best_model'], 
            results['scaler'], 
            results['feature_names'],  # 使用完整的特征列表
            single_data
        )
        
        status = "🔴 异常" if prediction == 1 else "🟢 正常"
        print(f"设备 {i+1}: {status} | 异常分数: {score:.3f} | 预警等级: {alert}")
        
        if prediction == 1:
            print(f"        ⚠️ 建议立即检查设备 {i+1} 的运行状态!")
            # 输出异常参数
            print(f"        异常参数: 温度={single_data['temperature'].values[0]}°C, "
                  f"振动={single_data['vibration'].values[0]}mm/s, "
                  f"电流={single_data['current'].values[0]}A")

if __name__ == "__main__":
    # 运行设备故障预测
    results = equipment_anomaly_detection()
    
    # 运行实时监控演示
    real_time_monitoring_demo(results)
    
    # 特征重要性分析
    print("\n" + "="*80)
    print("特征重要性分析")
    print("="*80)
    
    feature_importance = pd.DataFrame({
        'feature': results['feature_names'][:10],
        'description': [
            '设备温度', '振动强度', '工作电流', '工作电压', 
            '运行时长', '系统压力', '转速', '温度振动比',
            '能耗', '温度变化率'
        ]
    })
    
    print("\n关键监控特征:")
    print(feature_importance.to_string(index=False))

运行结果:

(ai_env) $ python3 equipment_fault_prediction.py
================================================================================
设备故障预测系统 - 基于运行参数的异常检测
================================================================================

1. 生成设备运行数据...
总样本数: 5000
正常样本: 4600
故障样本: 400
故障比例: 8.00%

2. 数据预处理...
使用特征数: 13
特征列表: ['temperature', 'vibration', 'current', 'voltage', 'runtime']...

训练集大小: 3500
测试集大小: 1500
测试集故障比例: 8.00%

3. 训练异常检测模型...

训练孤立森林模型...
训练OneClass SVM模型...
训练扩展孤立森林(低污染)...

================================================================================
模型评估结果
================================================================================

IsolationForest:
----------------------------------------
准确率 (Accuracy): 0.9753
精确率 (Precision): 0.7643
召回率 (Recall): 1.0000
F1分数: 0.8664
混淆矩阵:
[[1343   37]
 [   0  120]]

OneClassSVM:
----------------------------------------
准确率 (Accuracy): 0.9633
精确率 (Precision): 0.7019
召回率 (Recall): 0.9417
F1分数: 0.8043
混淆矩阵:
[[1332   48]
 [   7  113]]

IsolationForest_Low:
----------------------------------------
准确率 (Accuracy): 0.9773
精确率 (Precision): 1.0000
召回率 (Recall): 0.7167
F1分数: 0.8350
混淆矩阵:
[[1380    0]
 [  34   86]]

4. 实时监控预警系统...
--------------------------------------------------------------------------------
模拟实时设备监控(最后20个测试样本):
------------------------------------------------------------
样本 1: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.384 | 匹配: ✓
样本 2: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.385 | 匹配: ✓
样本 3: ⚠ 异常预警    | 预测: 1 | 实际: 故障 | 异常分: -0.674 | 匹配: ✓
        🔔 预警!设备可能即将发生故障,建议立即检查!
样本 4: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.436 | 匹配: ✓
样本 5: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.368 | 匹配: ✓
样本 6: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.371 | 匹配: ✓
样本 7: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.364 | 匹配: ✓
样本 8: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.387 | 匹配: ✓
样本 9: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.392 | 匹配: ✓
样本10: ⚠ 异常预警    | 预测: 1 | 实际: 正常 | 异常分: -0.464 | 匹配: ✗
        🔔 预警!设备可能即将发生故障,建议立即检查!
样本11: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.395 | 匹配: ✓
样本12: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.400 | 匹配: ✓
样本13: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.440 | 匹配: ✓
样本14: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.346 | 匹配: ✓
样本15: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.355 | 匹配: ✓
样本16: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.380 | 匹配: ✓
样本17: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.363 | 匹配: ✓
样本18: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.390 | 匹配: ✓
样本19: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.350 | 匹配: ✓
样本20: ✓ 正常运行     | 预测: 0 | 实际: 正常 | 异常分: -0.356 | 匹配: ✓

5. 异常特征分析...
--------------------------------------------------------------------------------
异常样本的主要特征偏差:

异常样本 1:
  temperature: 81.95 (偏离均值: +6.8%)
  vibration: 4.59 (偏离均值: +62.2%)
  current: 47.56 (偏离均值: +5.4%)
  voltage: 362.36 (偏离均值: -4.7%)
  runtime: 77.74 (偏离均值: -40.7%)
  pressure: 11.23 (偏离均值: +104.0%)

异常样本 2:
  temperature: 75.98 (偏离均值: -1.0%)
  vibration: 1.08 (偏离均值: -61.7%)
  current: 41.36 (偏离均值: -8.3%)
  voltage: 382.40 (偏离均值: +0.6%)
  runtime: 112.16 (偏离均值: -14.5%)
  pressure: 5.16 (偏离均值: -6.3%)

异常样本 3:
  temperature: 73.82 (偏离均值: -3.8%)
  vibration: 1.48 (偏离均值: -47.7%)
  current: 44.52 (偏离均值: -1.3%)
  voltage: 389.59 (偏离均值: +2.5%)
  runtime: 761.87 (偏离均值: +481.0%)
  pressure: 5.20 (偏离均值: -5.5%)

异常样本 4:
  temperature: 96.95 (偏离均值: +26.4%)
  vibration: 2.88 (偏离均值: +1.9%)
  current: 47.37 (偏离均值: +5.0%)
  voltage: 355.35 (偏离均值: -6.5%)
  runtime: 168.83 (偏离均值: +28.7%)
  pressure: 7.06 (偏离均值: +28.2%)

异常样本 5:
  temperature: 90.50 (偏离均值: +18.0%)
  vibration: 5.05 (偏离均值: +78.8%)
  current: 59.81 (偏离均值: +32.6%)
  voltage: 327.99 (偏离均值: -13.7%)
  runtime: 796.62 (偏离均值: +507.5%)
  pressure: 6.43 (偏离均值: +16.8%)

6. 设备健康报告...
--------------------------------------------------------------------------------
设备整体健康度: 90.1/100
最低健康度: 0.0/100
检测到的异常数: 157
异常率: 10.47%
健康等级: 优秀
建议: 设备运行良好,继续保持定期维护

7. 生成可视化图表...

================================================================================
设备故障预测完成!
================================================================================

================================================================================
实时监控演示
================================================================================

实时监控5台设备:
------------------------------------------------------------
设备 1:  正常 | 异常分数: -0.346 | 预警等级: 正常
设备 2:  异常 | 异常分数: -0.610 | 预警等级: 高危
        ⚠ 建议立即检查设备 2 的运行状态!
        异常参数: 温度=96°C, 振动=5.8mm/s, 电流=58A
设备 3:  正常 | 异常分数: -0.351 | 预警等级: 正常
设备 4:  异常 | 异常分数: -0.528 | 预警等级: 高危
        ⚠ 建议立即检查设备 4 的运行状态!
        异常参数: 温度=88°C, 振动=4.2mm/s, 电流=52A
设备 5:  异常 | 异常分数: -0.679 | 预警等级: 高危
        ⚠ 建议立即检查设备 5 的运行状态!
        异常参数: 温度=102°C, 振动=7.5mm/s, 电流=63A

================================================================================
特征重要性分析
================================================================================

关键监控特征:
             feature description
         temperature        设备温度
           vibration        振动强度
             current        工作电流
             voltage        工作电压
             runtime        运行时长
            pressure        系统压力
               speed          转速
temp_vibration_ratio       温度振动比
   power_consumption          能耗
    temp_change_rate       温度变化率
(ai_env) $
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐