coef1 = pd.DataFrame() for alpha in np.linspace(0.0001,0.2,20): lasso_clf = Lasso(alpha=alpha) lasso_clf.fit(X_train[features_without_ones],y_train) df = pd.DataFrame([lasso_clf.coef_],columns=X_train[features_without_ones].columns) df['alpha'] = alpha coef1 = pd.concat([coef1,df],ignore_index=True) coef1.head() plt.figure(figure=(9,6),dpi=600) for feature in X_train.columns[:-1]: plt.plot('alpha',feature,data=coef1) plt.legend(loc='upper right') plt.xlabel(r'$\alpha$',fontsize=15) plt.ylabel("coefficient",fontsize=15) plt.show() RuntimeError: Can not put single artist in more than one figure Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
时间: 2023-06-19 08:05:27 浏览: 228
这个错误提示是因为您的代码中存在多个 figure 对象,而一个 artist 对象(如 plot)只能被添加到一个 figure 中,因此出现了运行时错误。
您可以尝试将 plt.figure() 函数的参数 figure 改为 figsize,因为 figure 参数是用来指定已有的 figure 对象,而 figsize 是用来创建新的 figure 对象的参数。另外,您也可以在绘制图形之前使用 plt.clf() 或 plt.close() 函数来清空已有的 figure 对象。
以下是修改后的示例代码:
```
coef1 = pd.DataFrame()
for alpha in np.linspace(0.0001,0.2,20):
lasso_clf = Lasso(alpha=alpha)
lasso_clf.fit(X_train[features_without_ones],y_train)
df = pd.DataFrame([lasso_clf.coef_],columns=X_train[features_without_ones].columns)
df['alpha'] = alpha
coef1 = pd.concat([coef1,df],ignore_index=True)
plt.figure(figsize=(9,6),dpi=600)
for feature in X_train.columns[:-1]:
plt.plot('alpha',feature,data=coef1)
plt.legend(loc='upper right')
plt.xlabel(r'$\alpha$',fontsize=15)
plt.ylabel("coefficient",fontsize=15)
plt.show()
```
希望能帮助到您!
阅读全文