python画子图时会遇见如下进行迭代的情况,当画多个子图时,因为axes是二维数组,所以使用zip时要将其展平,此外为了让子图大小自适应,可在subplots中添加参数constrained_layout=True
fig, axes = plt.subplots(4, 3, figsize=(15, 10),constrained_layout=True)
#create 1,000 data points, evenly spaced between -3 and 3
line = np.linspace(-3, 3, 1000).reshape(-1, 1)
for n_neighbors, ax in zip(range(1,11), axes.flat):
# make predictions using 1, 3, or 9 neighbors
reg = KNeighborsRegressor(n_neighbors=n_neighbors)
reg.fit(X_train, y_train)
ax.plot(line, reg.predict(line))
ax.plot(X_train, y_train, '^', c=mglearn.cm2(0), markersize=8)
ax.plot(X_test, y_test, 'v', c=mglearn.cm2(1), markersize=8)
ax.set_title(
"{} neighbor(s)\n train score: {:.2f} test score: {:.2f}".format(
n_neighbors, reg.score(X_train, y_train),
reg.score(X_test, y_test)))
ax.set_xlabel("Feature")
ax.set_ylabel("Target")
axes.flat[0].legend(["Model predictions", "Training data/target",
"Test data/target"], loc="best")