python给出的数组是一维的,但有2个被索引错误
我已经为miniBatchGradientDescent编写了mini_批处理创建者代码 代码如下:python给出的数组是一维的,但有2个被索引错误,python,python-3.x,numpy,machine-learning,Python,Python 3.x,Numpy,Machine Learning,我已经为miniBatchGradientDescent编写了mini_批处理创建者代码 代码如下: # function to create a list containing mini-batches def create_mini_batches(X,y, batch_size): print(X.shape, y.shape) # gives (280, 34) (280,) splitData=[] splitDataResults=[] batch
# function to create a list containing mini-batches
def create_mini_batches(X,y, batch_size):
print(X.shape, y.shape) # gives (280, 34) (280,)
splitData=[]
splitDataResults=[]
batchCount=X.shape[0] // batch_size #using floor division for getting indexes integer form
for i in range(batchCount):
splitData.append(X[(i) * batch_size : (i+1) * batch_size, :])
splitDataResults.append(y[(i) * batch_size : (i+1) * batch_size, :]) # GIVES ERROR
splitData=np.asarray(splitData)
splitDataResults=np.asarray(splitDataResults)
return splitData, splitDataResults, batchCount
错误显示:
splitDataResults.append(y[(i) * batch_size : (i+1) * batch_size, :])
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
我确信这个形状是正确的,但它给了我一个错误。有什么问题吗?尝试重新塑造y:
print(X.shape, y.shape) # gives (280, 34) (280,)
y = y.reshape(-1, 1)
这将解决您的问题,因为y将变成二维是的,谢谢。这解决了我的问题。你能解释一下为什么会解决这个问题吗?y形是(280),这是一个1D NumPy数组,所以你不能像在引发异常的那一行那样使用[i,j]来索引,你试图索引到一个1D数组的二维。完成重塑后,它将变为(280,1),因此它是一个二维数组,并且索引工作正常