感知机绘制决策边界报错求助:特征维度不匹配与值解包不足
Hey there! Let's break down why you're hitting those errors and get your decision boundary plotted properly.
What's Causing the Errors?
The core issue is simple: your trained perceptron is built to work with 13 features, but when you tried to plot the boundary, you only passed 2 features (the X1 and X2 from your meshgrid) to perceptron.predict(). The model throws a fit because it expects 13 inputs per sample, not 2. Your attempt to unpack 12 variables was off-base too—meshgrid only generates two 2D arrays, so that's why you got the second "not enough values" error.
Decision boundaries can only be visualized in a 2D plane, so we need to narrow our focus to two features. Below are two valid solutions depending on what you want to inspect.
Solution 1: Train a Perceptron on a Pair of Features
If you want to see if a specific pair of features can linearly separate your data, retrain the perceptron using only those two features. Here's the adjusted code:
from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import Perceptron # Choose two features to visualize (e.g., feature 0 and feature 1) feature_indices = [0, 1] X_two_features = X[:, feature_indices] # Retrain the perceptron on just these two features perceptron_two_feat = Perceptron(random_state=42) perceptron_two_feat.fit(X_two_features, Y) # Plot the decision boundary plt.clf() X_set, y_set = X_two_features, Y X1, X2 = np.meshgrid( np.arange(start=X_set[:, 0].min() - 1, stop=X_set[:, 0].max() + 1, step=0.01), np.arange(start=X_set[:, 1].min() - 1, stop=X_set[:, 1].max() + 1, step=0.01) ) # Predict using the two-feature perceptron plt.contourf( X1, X2, perceptron_two_feat.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha=0.75, cmap=ListedColormap(('navajowhite', 'darkkhaki')) ) # Plot data points plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter( X_set[y_set == j, 0], X_set[y_set == j, 1], c=ListedColormap(('red', 'green'))(i), label=j ) plt.title(f'Perceptron Decision Boundary (Feature {feature_indices[0]} vs Feature {feature_indices[1]})') plt.xlabel(f'Feature {feature_indices[0]}') plt.ylabel(f'Feature {feature_indices[1]}') plt.legend() plt.show()
Solution 2: Fix Other Features to Their Mean (Use Full Model)
If you want to visualize how two features interact within your original 13-feature model, fix the other 11 features to their mean values and only vary the two you want to plot. This keeps your original trained perceptron intact:
from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt import numpy as np # Choose two features to visualize (e.g., feature 2 and feature 5) feat1_idx, feat2_idx = 2, 5 # Calculate mean of all features to fix the other 11 features X_feature_means = X.mean(axis=0) plt.clf() X_set, y_set = X, Y X1, X2 = np.meshgrid( np.arange(start=X_set[:, feat1_idx].min() - 1, stop=X_set[:, feat1_idx].max() + 1, step=0.01), np.arange(start=X_set[:, feat2_idx].min() - 1, stop=X_set[:, feat2_idx].max() + 1, step=0.01) ) # Create grid points with fixed values for non-visualized features grid_points = np.zeros((X1.ravel().shape[0], X.shape[1])) grid_points[:, feat1_idx] = X1.ravel() grid_points[:, feat2_idx] = X2.ravel() # Fill other features with their mean values for idx in range(X.shape[1]): if idx != feat1_idx and idx != feat2_idx: grid_points[:, idx] = X_feature_means[idx] # Predict using your original 13-feature perceptron plt.contourf( X1, X2, perceptron.predict(grid_points).reshape(X1.shape), alpha=0.75, cmap=ListedColormap(('navajowhite', 'darkkhaki')) ) # Plot data points for the two features plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter( X_set[y_set == j, feat1_idx], X_set[y_set == j, feat2_idx], c=ListedColormap(('red', 'green'))(i), label=j ) plt.title(f'Perceptron Decision Boundary (Feature {feat1_idx} vs Feature {feat2_idx})') plt.xlabel(f'Feature {feat1_idx}') plt.ylabel(f'Feature {feat2_idx}') plt.legend() plt.show()
Key Notes
- Swap out the
feature_indicesorfeat1_idx/feat2_idxvalues to explore different pairs of features. - Solution 1 tells you if a pair of features alone can linearly separate your data; Solution 2 shows how two features behave within your full model.
内容的提问来源于stack exchange,提问作者gendry

