【问题标题】:IndexError: too many indices for array when creating a train test splitIndexError:创建训练测试拆分时数组的索引过多
【发布时间】:2018-12-22 18:22:01
【问题描述】:

我正在创建一个神经网络,目前我正在研究; train, test split 但我收到错误 IndexError: too many indices for array 我的代码是:

import csv
import math
import numpy as np 
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
import datetime
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split

X1 = Values[1:16801] #16,800 values
Y1 = P1[1:16801]#16,800 values

train_size = int(len(X1) * 0.67)
test_size = len(X1) - train_size

train, test = X1[0:train_size,], X1[train_size:len(X1),]
def Data(X1, look_back=1):
     dataX, dataY = [], []
     for i in range(len(X1)-look_back-1):
         a = X1[i:(i+look_back), 0]
         dataX.append(a)
         dataY.append(Y1[i + look_back, 0])
     return numpy.array(dataX), numpy.array(dataY)

look_back = 1
trainX, testX = Data(train, look_back)

testX, testY = Data(test, look_back)

look_back = 1
trainX, testX = Data(train, look_back)

testX, testY = Data(test, look_back)

我有 16,800 个 X1 值,如下所示:

[0.03454225 0.02062136 0.00186715 ... 0.92857565 0.64930691 0.20325924]

我的 Y1 数据看起来像:[ 2.25226244 1.44078451 0.99174488 ... 12.8397099 9.75722427 7.98525797]

我的回溯错误信息是:

IndexError                                Traceback (most recent call last)
<ipython-input-11-afedcaa56e0b> in <module>()
     86 
     87 look_back = 1
---> 88 trainX, testX = Data_split(train, look_back)
     89 
     90 testX, testY = Data_split(test, look_back)

<ipython-input-11-afedcaa56e0b> in Data(X1, look_back)
     78     dataX, dataY = [], []
     79     for i in range(len(X1)-look_back-1):
---> 80         a = X1[i:(i+look_back), 0]
     81         dataX.append(a)
     82         dataY.append(Y1[i + look_back, 0])

IndexError: too many indices for array

我之前问过一个非常相似的question 并得到了答案,但不幸的是我无法将该解决方案应用于此错误

【问题讨论】:

    标签: python machine-learning index-error


    【解决方案1】:

    问题在于数组的维度。您正在尝试使用不存在的多个维度索引访问元素。查看第 80 行。

     a = X1[i:(i+look_back), 0]   in your case metrics is just single dimention.
    

    示例 2d 度量表示 (,)

    "," 是对具有行和列的二维数组的引用,但不幸的是,您将 X1 作为 ndarray。

    [0.03454225 0.02062136 0.00186715 ... 0.92857565 0.64930691 0.20325924]
    

    类似问题示例:-

    >>> np.ndarray(4)
    array([2.0e-323, 1.5e-323, 2.0e-323, 1.5e-323])
    >>> a[1:2,0]
    Traceback (most recent call last):
      File "<pyshell#38>", line 1, in <module>
        a[1:2,0]
    IndexError: too many indices for array
    >>> a[1:2]
    array([-2.68156159e+154])
    >>> 
    

    【讨论】:

    • 谢谢,我删除了突出显示的逗号,它已经工作了
    猜你喜欢
    • 1970-01-01
    • 2019-05-07
    • 2018-12-14
    • 2016-06-07
    • 2017-12-26
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    相关资源
    最近更新 更多