ValueError:无法将输入数组从形状(2,5,2)广播到形状(5,2)

2024-05-20 21:37:52 发布

您现在位置:Python中文网/ 问答频道 /正文

初始化为的n维数组

features=np.empty(shape=(100,5,2), dtype=float)

我正在尝试将3D阵列作为

features[i,:] = features_next

特征_下一个具有形状(2,5,2)。 但这是错误的,

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

下面是一段代码:

   features=np.empty(shape=((historical*2),5,2), dtype=float)  
    i = 0
    while i < 50:
        state = self.getDictState(state_index)
        asks = state['asks']
        bids = state['bids']
        features_next = self.getNormalisedFeature(
            bids=bids,
            asks=asks,
            state_index=state_index,
            qty=qty,
            price=price,
            size=size,
            normalize=normalize,
            levels=levels
        )
        '''if i == 0:
            features = np.array(features_next)
        else:
            features = np.vstack((features, features_next))'''
        features[i,:] = features_next
        state_index = (state_index - 1)
    return features

注意:我试图用features[I,:]=features\u替换注释的“if条件”,以加快代码执行速度


Tags: selfindexnpfloatarraypriceemptynext
1条回答
网友
1楼 · 发布于 2024-05-20 21:37:52

它非常简单,只需一点就可以使features[i,:]具有形状(5,2),而特征_具有形状(2,5,2)。我想说的是,两者都是兼容的形状。但是广播是在较小的形状上进行的,而不是在较大的形状上。因为你做的是敬畏,所以有错误。还可以查看numpy文档上的广播

下一步,我想这个就行了

这并不能直接解决您的问题,但对您可以尝试的内容有一些想法,比如您可以在进入循环之前使用features.shape = (50, 2, 5, 2)对数组进行重塑

import numpy as np

features=np.empty(shape=(100,5,2), dtype=float)
features_next = np.random.random((2, 5, 2))

features.shape = ((50, 2, 5, 2)) 

features[:] = features_next
features.shape = (100, 5, 2)

相关问题 更多 >