鱼C论坛

 找回密码
 立即注册
查看: 1339|回复: 3

list index out of range

[复制链接]
发表于 2023-10-13 21:49:23 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
发生异常: IndexError
list index out of range
  File "D:\0000可见光2\程序\InceptionTime\Test3.py", line 38, in __init__
    self.dataset_name = output_directory.split('/')[-2]
  File "D:\0000可见光2\程序\InceptionTime\Test3.py", line 133, in <module>
    model = Classifier_NNE(output_directory='output_directory', input_shape=X_train.shape[1:], nb_classes=8)
IndexError: list index out of range

  1. import keras
  2. import numpy as np
  3. from utils import calculate_metrics
  4. from utils import create_directory
  5. from utils import check_if_file_exits
  6. import gc
  7. from constants import UNIVARIATE_ARCHIVE_NAMES  as ARCHIVE_NAMES
  8. import time


  9. class Classifier_NNE:

  10.     def create_classifier(self, model_name, input_shape, nb_classes, output_directory, verbose=True,
  11.                           build=True):
  12.         if self.check_if_match('inception*', model_name):
  13.             import inception
  14.             return inception.Classifier_INCEPTION(output_directory, input_shape, nb_classes, verbose,
  15.                                                   build=build)

  16.     def check_if_match(self, rex, name2):
  17.         import re
  18.         pattern = re.compile(rex)
  19.         return pattern.match(name2)

  20.     def __init__(self, output_directory, input_shape, nb_classes, verbose=False, nb_iterations=5,
  21.                  clf_name='inception'):
  22.         self.classifiers = [clf_name]
  23.         out_add = ''
  24.         for cc in self.classifiers:
  25.             out_add = out_add + cc + '-'
  26.         self.archive_name = ARCHIVE_NAMES[0]
  27.         self.iterations_to_take = [i for i in range(nb_iterations)]
  28.         for cc in self.iterations_to_take:
  29.             out_add = out_add + str(cc) + '-'
  30.         self.output_directory = output_directory.replace('nne',
  31.                                                          'nne' + '/' + out_add)
  32.         create_directory(self.output_directory)
  33.         self.dataset_name = output_directory.split('/')[-2]
  34.         self.verbose = verbose
  35.         self.models_dir = output_directory.replace('nne', 'classifier')

  36.     def fit(self, x_train, y_train, x_test, y_test, y_true):
  37.         # no training since models are pre-trained
  38.         start_time = time.time()

  39.         y_pred = np.zeros(shape=y_test.shape)

  40.         ll = 0

  41.         # loop through all classifiers
  42.         for model_name in self.classifiers:
  43.             # loop through different initialization of classifiers
  44.             for itr in self.iterations_to_take:
  45.                 if itr == 0:
  46.                     itr_str = ''
  47.                 else:
  48.                     itr_str = '_itr_' + str(itr)

  49.                 curr_archive_name = self.archive_name + itr_str

  50.                 curr_dir = self.models_dir.replace('classifier', model_name).replace(
  51.                     self.archive_name, curr_archive_name)

  52.                 model = self.create_classifier(model_name, None, None,
  53.                                                curr_dir, build=False)

  54.                 predictions_file_name = curr_dir + 'y_pred.npy'
  55.                 # check if predictions already made
  56.                 if check_if_file_exits(predictions_file_name):
  57.                     # then load only the predictions from the file
  58.                     curr_y_pred = np.load(predictions_file_name)
  59.                 else:
  60.                     # then compute the predictions
  61.                     curr_y_pred = model.predict(x_test, y_true, x_train, y_train, y_test,
  62.                                                 return_df_metrics=False)
  63.                     keras.backend.clear_session()

  64.                     np.save(predictions_file_name, curr_y_pred)

  65.                 y_pred = y_pred + curr_y_pred

  66.                 ll += 1

  67.         # average predictions
  68.         y_pred = y_pred / ll

  69.         # save predictions
  70.         np.save(self.output_directory + 'y_pred.npy', y_pred)

  71.         # convert the predicted from binary to integer
  72.         y_pred = np.argmax(y_pred, axis=1)

  73.         duration = time.time() - start_time

  74.         df_metrics = calculate_metrics(y_true, y_pred, duration)

  75.         df_metrics.to_csv(self.output_directory + 'df_metrics.csv', index=False)

  76.         gc.collect()

  77. import numpy as np
  78. import pandas as pd
  79. from sklearn.model_selection import train_test_split
  80. import sklearn

  81. df1 = pd.read_csv("train.csv")
  82. df1 = np.array(df1)
  83. X = np.expand_dims(df1[:, 1:891].astype(float), axis=2)  # 对数据进行增维并转化为32为
  84. #X = np.expand_dims(df1[:, 1:891].astype(float), axis=1)
  85. Y = df1[:, 0]
  86. X_train, X_val, y_train, y_val = train_test_split(X, Y, test_size=0.2, random_state=42)

  87. #y_train, y_val = transform_labels(y_train, y_val)
  88. # save orignal y because later we will use binary
  89. y_true = y_val.astype(np.int64)
  90. y_true_train = y_train.astype(np.int64)
  91. # transform the labels from integers to one hot vectors
  92. enc = sklearn.preprocessing.OneHotEncoder()
  93. enc.fit(np.concatenate((y_train, y_val), axis=0).reshape(-1, 1))
  94. y_train = enc.transform(y_train.reshape(-1, 1)).toarray()
  95. y_val = enc.transform(y_val.reshape(-1, 1)).toarray()

  96. '''y_train = to_categorical(y_train)  # one-hot encoding
  97. y_val= to_categorical(y_val)
  98. y_true = y_val'''
  99. df2 = pd.read_csv("test.csv")
  100. df2 = np.array(df1)
  101. X_test = np.expand_dims(df2[:, 1:891].astype(float), axis=2)
  102. y_test=df2[:, 0]
  103. y_true1 = y_test.astype(np.int64)
  104. y_test = enc.transform(y_test.reshape(-1, 1)).toarray()
  105. # 创建模型
  106. model = Classifier_NNE(output_directory='output_directory', input_shape=X_train.shape[1:], nb_classes=8)

  107. # 训练模型
  108. model.fit(X_train, y_train, X_val, y_val,y_true)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-10-13 21:50:08 | 显示全部楼层
The error you're encountering, IndexError: list index out of range, is due to trying to access an index in a list that doesn't exist. In your case, the error is occurring at this line:

  1. self.dataset_name = output_directory.split('/')[-2]
复制代码


Here, you're trying to split the output_directory string by the '/' character and access the second last element. If the output_directory string doesn't contain enough '/' characters, you'll get an IndexError.

To fix this, you need to ensure that output_directory contains at least two '/' characters. If you're not sure whether output_directory will always contain enough '/' characters, you can add a check before this line to prevent the error:

  1. split_directory = output_directory.split('/')
  2. if len(split_directory) >= 2:
  3.     self.dataset_name = split_directory[-2]
  4. else:
  5.     # Handle the case where output_directory doesn't contain enough '/' characters
  6.     # For example, you could set self.dataset_name to a default value
  7.     self.dataset_name = "default"
复制代码


This code will prevent the IndexError by checking that split_directory contains enough elements before trying to access the second last element. If split_directory doesn't contain enough elements, self.dataset_name is set to a default value. You should replace \"default\" with a value that makes sense in your context.
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-10-13 21:51:09 | 显示全部楼层
这个错误通常表示您正在尝试访问列表中不存在的索引。在这种情况下,错误发生在第133行,因为您的output_directory参数是一个字符串,而不是列表。您需要检查代码中是否有任何错误,确保您正在使用正确的参数类型。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-10-13 21:51:35 | 显示全部楼层
陶远航 发表于 2023-10-13 21:50
The error you're encountering, IndexError: list index out of range, is due to trying to access an in ...

谢谢哥 都没翻译 热乎的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-22 20:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表