python 报ValueError could not broadcast input array from shape或 Can‘t convert non-rectangular

numpy报ValueError: could not broadcast input array from shape
tensorflow报ValueError: Can’t convert non-rectangular Python sequence to Tensor.

这两个错误都是一样的的原因。

在使用numpy和tensorflow将list转为array或tensor的时候报错

弹出错误的代码:

a = np.array([[1.1,1.2],[2.1,2.2]])
b = np.array([[1.1,1.2,1.3],[2.1,2.2,2.3]])
c = [a,b]
d = np.array(c)

错误信息描述

ValueError: could not broadcast input array from shape (2,2) into shape (2)

问题分析
出现这个问题的主要原因是因为list中array的shape不一致造成的,所以发生这个问题的时候,先将list中数组的shape全部打印出来观察一下

print(a.shape,b.shape)

输出信息

(2, 2) (2, 3)

解决问题

对于这种问题主要有三种解决办法,第1种是改为使用字典。第2种就是将list中的array全部都展开,第3种就是利用mask来使得数组的shape一致

就是用字典分开存储每个列表,可以转为将每个列表转为tensorflow或numpy的数据格式
如果之后操作时变量c的话,推荐这种方式

a = np.array([[1.1,1.2],[2.1,2.2]])
b = np.array([[1.1,1.2,1.3],[2.1,2.2,2.3]])
c = {'a':tf.constant(a),'b':tf.constant(b)}
print(c)
{'a': <tf.Tensor: id=0, shape=(2, 2), dtype=float64, numpy=
array([[1.1, 1.2],
       [2.1, 2.2]])>, 'b': <tf.Tensor: id=1, shape=(2, 3), dtype=float64, numpy=
array([[1.1, 1.2, 1.3],
       [2.1, 2.2, 2.3]])>}

使用时只需要按字典使用就可以。

在使用这种方法的时候需要满足数组的行或列一致,只能有一个维度不同,不然没法还原数组

a = np.array([[1.1,1.2],[2.1,2.2]])
b = np.array([[1.1,1.2,1.3],[2.1,2.2,2.3]])
c = np.array([a.ravel(),b.ravel()])
print(c)
for arr in c:
    print(arr.reshape(2,-1))

输出信息

[array([1.1, 1.2, 2.1, 2.2]) array([1.1, 1.2, 1.3, 2.1, 2.2, 2.3])]

[[1.1 1.2]
 [2.1 2.2]]
[[1.1 1.2 1.3]
 [2.1 2.2 2.3]]

这种方法主要是应用图片上,通常以图片的最大尺寸作为模板,当然如果是图片的话你也可以通过resize来使得它们的shape一致,只是使用resize的话可能会导致图片发生形变影响图片表达的信息

import copy
a = np.array([[1.1,1.2],[2.1,2.2]])
b = np.array([[1.1,1.2,1.3],[2.1,2.2,2.3]])
mask = np.zeros((2,3))
a_mask = copy.deepcopy(mask)
a_mask[:a.shape[0],:a.shape[1]] = a
b_mask = copy.deepcopy(mask)
b_mask[:b.shape[0],:b.shape[1]] = b
c = np.array([a_mask,b_mask])
print(c)

输出信息

[[[1.1 1.2 0. ]
  [2.1 2.2 0. ]]

 [[1.1 1.2 1.3]
  [2.1 2.2 2.3]]]

Original: https://blog.csdn.net/qq_38463737/article/details/119332319
Author: 集电极
Title: python 报ValueError could not broadcast input array from shape或 Can‘t convert non-rectangular

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/758995/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球