提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
紧接上文的逻辑回归原理分析
讲一讲在交通领域的应用
交通拥堵是现代城市面临的重要问题,如何通过数据科学方法理解拥堵形成机制至关重要。本文通过逻辑回归模型,结合动态可视化技术,展示机器学习如何从交通数据中学习拥堵模式。我们将模拟48小时的车流数据与平均速度,通过梯度下降训练逻辑回归模型,并通过动画直观呈现决策边界的演变过程。
这种标准的制定可以结合不同的交通场景,如高速、隧道等进行分析
在大多数标准高速场景下,使用对应数据集进行分析,得到的拥堵标准适用于标准高速场景
首先来看数据生成部分,我们模拟了48小时的交通流量数据:
# 设置随机种子以确保结果可重现
np.random.seed(42)
# 生成48小时的交通数据
hours = np.arange(48)
traffic_volume = np.random.randint(300, 800, size=48)
# 平均速度与车流数量负相关
average_speed = []
for volume in traffic_volume:
if volume > 600:
speed = np.random.randint(60, 90) # 高车流时速度较低
else:
speed = np.random.randint(80, 120) # 低车流时速度较高
average_speed.append(speed)
# 转换为numpy数组并创建特征矩阵和标签
average_speed = np.array(average_speed)
X = np.column_stack((traffic_volume, average_speed))
y = (average_speed < 80).astype(int) # 1表示拥堵,0表示畅通
这段代码生成了两个关键特征:
traffic_volume
:车流数量,在300-800辆/小时之间随机波动average_speed
:平均速度,与车流数量呈负相关(车流>600时速度降低)数据生成逻辑模拟了真实交通场景:高车流通常伴随低速度,形成拥堵状态。标签y
将速度低于80km/h的情况标记为拥堵(1),否则为畅通(0)。
逻辑回归的核心在于sigmoid函数与梯度下降优化,我们实现了数值稳定的版本:
# 数值稳定的sigmoid函数
def sigmoid(x):
"""数值稳定的sigmoid函数实现"""
return np.where(
x >= 0,
1 / (1 + np.exp(-x)),
np.exp(x) / (1 + np.exp(x))
)
# 预测函数(返回概率值)
def predict_prob(X, W, b):
linear_output = np.dot(X, W) + b
return sigmoid(linear_output)
# 训练函数
def train(X, y, lr=0.01, epochs=300, save_every=10):
n_samples, n_features = X.shape
W = np.random.randn(n_features)
b = 0
w_history = [W.copy()]
b_history = [b]
loss_history = []
for epoch in range(epochs):
linear_output = np.dot(X, W) + b
y_pred = sigmoid(linear_output)
# 计算梯度
dW = (1 / n_samples) * np.dot(X.T, (y_pred - y))
db = (1 / n_samples) * np.sum(y_pred - y)
# 更新参数
W -= lr * dW
b -= lr * db
if epoch % save_every == 0:
w_history.append(W.copy())
b_history.append(b)
loss = -np.mean(y * np.log(y_pred + 1e-10) + (1 - y) * np.log(1 - y_pred + 1e-10))
loss_history.append(loss)
print(f"Epoch {epoch}, Loss: {loss:.4f}")
return w_history, b_history, loss_history
数值稳定性优化:
sigmoid
函数通过分段计算避免指数溢出:
1e-10
防止log(0)导致的数值错误梯度下降过程:
linear_output = X·W + b
y_pred = sigmoid(linear_output)
W = W - lr·dW
, b = b - lr·db
动画可视化是理解模型训练的关键,我们使用matplotlib的动画功能展示决策边界的变化:
# 动画更新函数
def update(frame, w_history, b_history, X, y, gs, scaler=None):
W = w_history[frame]
b = b_history[frame]
plt.clf()
fig = plt.gcf()
fig.set_size_inches(12, 10)
# 主图:数据点和决策边界
ax1 = fig.add_subplot(gs[0, :])
scatter0 = ax1.scatter(X[y == 0, 0], X[y == 0, 1], c='blue',
label='畅通 (速度≥80km/h)', alpha=0.8, edgecolors='w', s=80)
scatter1 = ax1.scatter(X[y == 1, 0], X[y == 1, 1], c='red',
label='拥堵 (速度<80km/h)', alpha=0.8, edgecolors='w', s=80)
# 绘制概率等高线和决策边界
if scaler is not None:
x_min, x_max = X[:, 0].min() - 50, X[:, 0].max() + 50
y_min, y_max = X[:, 1].min() - 10, X[:, 1].max() + 10
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 300), np.linspace(y_min, y_max, 300))
mesh_points = np.c_[xx.ravel(), yy.ravel()]
mesh_points_scaled = scaler.transform(mesh_points)
Z_prob = predict_prob(mesh_points_scaled, W, b)
Z_prob = Z_prob.reshape(xx.shape)
contour = ax1.contourf(xx, yy, Z_prob, levels=20, cmap='RdBu', alpha=0.5)
ax1.contour(xx, yy, Z_prob, levels=[0.5], colors='black', linewidths=2)
# 子图:损失曲线
ax2 = fig.add_subplot(gs[1, :])
ax2.plot(range(len(loss_history)), loss_history, 'r-', linewidth=2)
ax2.set_xlabel('迭代次数 (x5)', fontsize=12)
ax2.set_ylabel('交叉熵损失', fontsize=12)
# 显示当前准确率
current_pred = predict(X if scaler is None else scaler.transform(X), W, b)
accuracy = np.mean(current_pred == y) * 100
ax2.text(0.05, 0.95, f'当前准确率: {accuracy:.2f}%', transform=ax2.transAxes)
可视化包含两个核心部分:
主图:
子图:
特征标准化是提升模型稳定性的重要步骤:
# 特征标准化(可选)
use_scaling = True # 切换是否使用标准化
if use_scaling:
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
training_data = X_scaled
else:
scaler = None
training_data = X
# 模型评估
final_W = w_history[-1]
final_b = b_history[-1]
final_pred = predict(X if scaler is None else scaler.transform(X), final_W, final_b)
final_accuracy = np.mean(final_pred == y) * 100
print(f"最终模型参数:")
print(f"车流数量权重: {final_W[0]:.4f}")
print(f"平均速度权重: {final_W[1]:.4f}")
print(f"截距: {final_b:.4f}")
print(f"最终准确率: {final_accuracy:.2f}%")
标准化通过StandardScaler
实现,将特征缩放到均值为0、标准差为1的范围,解决以下问题:
运行代码后,我们可以观察到:
尽管逻辑回归在本案例中表现良好,但存在以下局限性:
本文通过动态可视化的逻辑回归模型,展示了机器学习如何从交通数据中学习拥堵模式。这种可视化不仅帮助理解模型训练过程,也为交通管理提供了数据支持。在实际应用中,结合更多特征(如时间、天气、道路状况等)和更复杂的模型(如神经网络、随机森林),可以进一步提升预测精度,为智能交通系统提供更强的决策支持。
完整代码已包含数值稳定性优化、特征标准化、动态可视化等最佳实践,可作为机器学习入门与可视化的典型案例。