You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码末尾报'unexpected EOF while parsing'错误,请求排查

解决Python代码中的unexpected EOF while parsing错误

你遇到的unexpected EOF while parsing错误是因为代码存在语法不完整问题,具体出现在最后一行:

原代码最后一行:

Image(graph.create_png()

这里缺少了一个闭合括号,Python解释器无法识别语句结尾,因此抛出该错误。

修正后的完整代码:

import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

# 加载数据
wine = load_wine()
X = wine.data
y = wine.target

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.02, random_state=42)

# 查看数据形状
print(X_train.shape)
print(X_test.shape)

# 训练模型
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# 评估模型
print(model.score(X_test, y_test))

# 查看特征重要性
print(model.feature_importances_)
print(wine.feature_names)

# 绘制决策树(matplotlib方式)
from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
plt.figure(figsize=(25,20))
plot_tree(model.estimators_[0], filled=True, rounded=True, class_names=wine.target_names, feature_names=wine.feature_names)
plt.show()

# 使用graphviz可视化决策树(Jupyter Notebook中显示)
from IPython.display import Image  
from six import StringIO
from sklearn.tree import export_graphviz
import pydotplus, graphviz
dot_data = StringIO()  
# 导出为dot文件
export_graphviz(model.estimators_[0], out_file=dot_data, 
                filled=True, rounded=True,
                feature_names=wine.feature_names, 
                class_names=wine.target_names)
# 在Jupyter Notebook中显示
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
Image(graph.create_png())  # 补上缺失的闭合括号

内容的提问来源于stack exchange,提问作者Alex Karam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 06:25:06