使用Flask创建异常检测Web界面,核心是将异常检测逻辑与Web服务路由结合,同时设计对应的前端页面接收用户输入、展示检测结果。整个过程不需要复杂的框架配置,几步就能完成基础功能的搭建。

环境准备
首先需要安装必要的依赖库,核心依赖包括Flask框架和异常检测相关的库,这里以常用的孤立森林算法为例,还需要安装scikit-learn。执行以下命令安装依赖:
pip install flask scikit-learn numpy pandas
基础Flask应用搭建
先创建一个最基础的Flask应用,定义根路由返回基础页面,后续再逐步添加异常检测相关功能。
from flask import Flask, render_template, request, jsonify
import numpy as np
from sklearn.ensemble import IsolationForest
# 初始化Flask应用
app = Flask(__name__)
# 初始化异常检测模型,这里使用孤立森林作为示例
model = IsolationForest(n_estimators=100, contamination=0.1, random_state=42)
# 用示例数据训练模型,实际使用时替换为你的业务数据
train_data = np.random.randn(100, 2)
model.fit(train_data)
@app.route("/")
def index():
# 返回前端页面
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True, host="127.0.0.1", port=5000)
前端页面设计
在项目根目录下创建templates文件夹,在其中创建index.html文件,设计输入区域和结果展示区域。页面需要接收用户输入的特征数据,提交后展示是否为异常的结果。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>异常检测Web界面</title>
<style>
.container { width: 800px; margin: 50px auto; }
.input-group { margin: 10px 0; }
label { display: inline-block; width: 120px; }
input { width: 200px; padding: 5px; }
button { padding: 8px 20px; margin-top: 20px; }
.result { margin-top: 30px; padding: 15px; border: 1px solid #ccc; }
.normal { color: green; }
.abnormal { color: red; }
</style>
</head>
<body>
<div class="container">
<h2>异常检测工具</h2>
<div class="input-group">
<label>特征1:</label>
<input type="number" step="0.01" id="feature1" placeholder="请输入特征1数值">
</div>
<div class="input-group">
<label>特征2:</label>
<input type="number" step="0.01" id="feature2" placeholder="请输入特征2数值">
</div>
<button onclick="detect()">开始检测</button>
<div class="result" id="result"></div>
</div>
<script>
function detect() {
const feature1 = document.getElementById("feature1").value;
const feature2 = document.getElementById("feature2").value;
if (!feature1 || !feature2) {
alert("请填写所有特征数值");
return;
}
// 发送请求到后端检测接口
fetch("/detect", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ feature1: parseFloat(feature1), feature2: parseFloat(feature2) })
})
.then(response => response.json())
.then(data => {
const resultDiv = document.getElementById("result");
if (data.is_abnormal) {
resultDiv.innerHTML = `<p class="abnormal">检测结果:异常</p><p>异常得分:${data.score}</p>`;
} else {
resultDiv.innerHTML = `<p class="normal">检测结果:正常</p><p>异常得分:${data.score}</p>`;
}
});
}
</script>
</body>
</html>
添加检测接口
回到Flask应用文件,添加/detect路由,用于接收前端提交的特征数据,调用异常检测模型进行判断,返回检测结果。
@app.route("/detect", methods=["POST"])
def detect():
# 获取前端提交的JSON数据
data = request.get_json()
feature1 = data.get("feature1")
feature2 = data.get("feature2")
if feature1 is None or feature2 is None:
return jsonify({"error": "缺少必要的特征参数"}), 400
# 构造输入数据
input_data = np.array([[feature1, feature2]])
# 预测结果,-1表示异常,1表示正常
pred = model.predict(input_data)[0]
# 获取异常得分,得分越低越可能是异常
score = model.decision_function(input_data)[0]
return jsonify({
"is_abnormal": pred == -1,
"score": float(score)
})
功能扩展建议
基础功能实现后,可以根据实际需求扩展功能:
- 支持更多特征输入,动态适配不同维度的检测数据
- 添加历史检测记录功能,将检测结果存储到数据库
- 增加批量检测接口,支持上传文件批量处理数据
- 优化前端展示,添加异常得分的可视化图表
运行与测试
完成所有代码编写后,运行Flask应用,在浏览器访问127.0.0.1:5000,输入特征数值点击检测按钮,就能看到对应的异常检测结果。如果输入的特征数值和训练数据分布差异较大,大概率会返回异常结果。