如何用R的ggplot2绘制正则化逻辑回归的非线性决策边界
使用ggplot2绘制多项式正则化逻辑回归的决策边界
Got it, let's walk through how to recreate that decision boundary plot with ggplot2—since you already have your grid and prediction matrix ready, it's just a matter of getting your data into a format ggplot2 loves, then putting the pieces together.
Step 1: Reshape your grid data into a tidy data frame
ggplot2 works best with long-format (tidy) data, so first we'll convert your u, v grid and z matrix into a single data frame. The key here is making sure the order of your z values matches the grid combinations:
# Create a data frame with all u-v grid pairs grid_df <- expand.grid(u = u, v = v) # Flatten the z matrix into a vector and bind it to the grid data frame # as.vector() defaults to column-wise ordering, which matches expand.grid's output grid_df$z <- as.vector(z)
Step 2: Build the ggplot2 plot
Now we can use geom_contour to draw the p=0.5 decision boundary (which corresponds to z=0), then add your original data points with geom_point:
library(ggplot2) ggplot() + # Draw the decision boundary contour (breaks = 0 targets the z=0 line) geom_contour( data = grid_df, aes(x = u, y = v, z = z), breaks = 0, # This is equivalent to levels = 0 in base R contour() color = "darkred", size = 1.2 ) + # Add your original test data points geom_point( data = data, aes(x = Test1, y = Test2), alpha = 0.7, # Optional: make points slightly transparent color = "steelblue" ) + # Optional: polish the plot with labels and a clean theme labs( x = "Test 1", y = "Test 2", title = "Polynomial Regularized Logistic Regression Decision Boundary" ) + theme_minimal()
Quick notes to avoid issues:
- Double-check that
as.vector(z)is using the right order: base R'scontour()readszcolumn-wise, andexpand.grid()generates grid pairs in the same column-first order, so this should line up perfectly. If your contour looks messed up, you can tryas.vector(t(z))to transpose the matrix first (though that shouldn't be needed here). - If you want to visualize the predicted probabilities across the grid (not just the boundary), you can use
geom_tile(aes(fill = z))to add a heatmap layer underneath the contour.
内容的提问来源于stack exchange,提问作者Melvin86
相关产品推荐
相关产品推荐

