You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Keras编写Python脚本时遇IndexError:轴1索引越界问题求助

问题解决:IndexError 在 to_categorical 中的索引越界

错误根源

你的代码里,Tokenizer 默认会从1开始为字符分配索引(0被预留作填充位)。生成的data里是'a'和'b',所以tokenizer.word_index会是{'a':1, 'b':2}。当你用to_categorical(y, num_classes=2)时,要求类别索引只能是0和1,但y里存在值为2的元素,直接触发索引越界错误。

修复方案

方案1:调整编码为从0开始

在得到序列编码后,统一减1将索引映射到0-1范围:

import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense

# Generate a random list of 10 characters 'a' or 'b'
data = ['a' if x == 0 else 'b' for x in np.random.randint(2, size=10)]

# Initialize a tokenizer to encode the characters as integers
tokenizer = Tokenizer(filters='')  # 避免过滤任何字符
tokenizer.fit_on_texts(data)

# Encode the input data as integers, 并将索引从1-based转为0-based
X = tokenizer.texts_to_sequences(data)
X = np.array(X) - 1  # 关键:把1、2转为0、1
X = X.reshape(1, 10, 1)
y = np.roll(X, -1)
y = to_categorical(y, num_classes=2)  # 现在索引0、1都在范围内

方案2:跳过Tokenizer,手动映射(更简洁)

因为只有两个类别,直接手动转换比用Tokenizer更高效:

import numpy as np
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense

# Generate a random list of 10 characters 'a' or 'b'
data = ['a' if x == 0 else 'b' for x in np.random.randint(2, size=10)]

# 手动映射字符到0/1
X = np.array([0 if c == 'a' else 1 for c in data]).reshape(1, 10, 1)
y = np.roll(X, -1)
y = to_categorical(y, num_classes=2)

方案3:调整num_classes为3(不推荐)

如果一定要保留Tokenizer的1-based索引,可以把num_classes设为3,但这样会生成一个空的0类别,可能导致模型训练冗余:

y = to_categorical(y, num_classes=3)

内容的提问来源于stack exchange,提问作者Baka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 11:50:33