Python ValueError: operands could not be broadcast together with shapes - 形状不匹配错误调试

在使用 Python 进行机器学习模型预测时,你可能会遇到 'ValueError: operands could not be broadcast together with shapes' 错误。这个错误通常是由于输入数据的形状与模型预期的形状不匹配导致的。

错误分析

让我们以你的错误信息为例:pythonTraceback (most recent call last): File '/Users/mac/PycharmProjects/pythonProject19/main.py', line 155, in feature = model.predict(current_data.reshape(1, -1)) # 使用模型预测特征 File '/Users/mac/PycharmProjects/pythonProject19/main.py', line 45, in predict xg_test = self.gaussian_feature(X_test, self.centers, self.delta) File '/Users/mac/PycharmProjects/pythonProject19/main.py', line 67, in gaussian_feature tmp_k = 0 - np.sum((data - centers[i, :]) ** 2 /ValueError: operands could not be broadcast together with shapes (1,3) (4,)

错误信息指出,在 __gaussian_feature__ 函数中计算 tmp_k 时,操作数的形状不匹配。具体来说,data - centers[i, :] 的结果形状为 (1, 3),而 delta[i, :] 的形状为 (4,),这导致了广播错误。

解决方案

为了解决这个问题,你需要确保参与运算的数组形状兼容。根据你的代码,centersdelta 的形状应该与输入数据的特征数相匹配。

一种可能的解决方案是将 centersdelta 的形状转换为 (1, 4),以便与 data 的形状 (1, 3) 兼容。你可以尝试修改 __gaussian_feature__ 方法中的代码,如下所示:pythondef gaussian_feature(self, data, centers, delta): n_cluster = self.n_cluster n_samples = data.shape[0] mu_a = np.zeros([n_samples, n_cluster]) for i in range(n_cluster): # 将 centers[i, :] 和 delta[i, :] 的形状转换为 (1, 4) tmp_k = 0 - np.sum((data - centers[i, :].reshape(1, -1)) ** 2 / delta[i, :].reshape(1, -1), axis=1) mu_a[:, i] = np.exp(tmp_k) mu_a = mu_a / np.sum(mu_a, axis=1, keepdims=True) data_1 = np.concatenate((data, np.ones([n_samples, 1])), axis=1) zt = [] for i in range(n_cluster): zt.append(data_1 * mu_a[:, i].reshape(-1, 1)) data_fs = np.concatenate(zt, axis=1) data_fs = np.where(data_fs != data_fs, 1e-5, data_fs) return data_fs

总结

'ValueError: operands could not be broadcast together with shapes' 错误在 Python 数据处理中很常见。了解错误信息并仔细检查数组形状是解决此类问题的关键。通过确保参与运算的数组形状兼容,你可以避免此类错误并成功运行你的代码。


原文地址: https://www.cveoy.top/t/topic/7xw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录