形状不匹配:无法将对象广播到单个形状如何解决python中的此类错误?

Posted

技术标签:

【中文标题】形状不匹配:无法将对象广播到单个形状如何解决python中的此类错误?【英文标题】:shape mismatch: objects cannot be broadcast to a single shape how to solve this type of error in python? 【发布时间】:2021-08-06 19:18:38 【问题描述】:

如何在python中解决这种类型的错误??

“ValueError:形状不匹配:对象不能广播到单个形状”,我​​的代码是:

代码:

X_train, X_test, y_train, y_test = train_test_split(
    cancer.data, cancer.target, random_state=0)
forest = RandomForestClassifier(n_estimators=100, random_state=0)
forest.fit(X_train, y_train)

print("Accuracy on training set: :.3f".format(forest.score(X_train, y_train)))
print("Accuracy on test set: :.3f".format(forest.score(X_test, y_test)))
plot_feature_importances_cancer(forest)

【问题讨论】:

【参考方案1】:

我不确定你在哪里得到错误。 我可以使用您的代码运行它,但请尝试复制以下内容。

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
import matplotlib.pyplot as plt

def plot_feature_importances_cancer(model):
    n_features = cancer.data.shape[1]
    plt.barh(range(n_features), model.feature_importances_, align='center')
    plt.yticks(np.arange(n_features),  cancer.feature_names)
    plt.xlabel("Feature importtances")
    plt.ylabel("Feature")

cancer = load_breast_cancer()

X_train, X_test, y_train, y_test = train_test_split(
    cancer.data, cancer.target, random_state=0)
forest = RandomForestClassifier(n_estimators=100, random_state=0)
forest.fit(X_train, y_train)

print("Accuracy on training set: :.3f".format(forest.score(X_train, y_train)))
print("Accuracy on test set: :.3f".format(forest.score(X_test, y_test)))

plot_feature_importances_cancer(forest)

【讨论】:

谢谢。运行到代码时出现这个错误:plot_feature_importances_cancer(forest),你知道为什么 可能是运行 matplotlib 时 x 轴和 y 轴的长度不均匀。你可以在函数代码中运行printshape,边走边检查:D

以上是关于形状不匹配:无法将对象广播到单个形状如何解决python中的此类错误?的主要内容,如果未能解决你的问题,请参考以下文章

对象不能广播到单个形状(条形图)

Matplotlib:形状不匹配:对象不能广播到单个形状

形状不匹配:索引数组无法与形状一起广播

尝试绘制堆积条形图时收到形状不匹配错误消息

使用 fastT5 将 T5 模型导出到 onnx 时,得到“RuntimeError:形状 [5, 8, 1, 2] 的输出与广播形状 [5, 8, 2, 2] 不匹配”

如何将 RGB ImageItem 添加到 pyqtgraph ViewBox? ValueError:无法将输入数组从形状(256,256,4)广播到形状(256,256)