np.frombufferとnp.zerosで前者がエラーとなる。

前提

同じ長さのnumpy配列で2種類の値の設定方法(case1、case2)で実行すると
case2の場合は正常だが、case1の場合はエラーとなります。
case1はファイルからnp.frombufferで読みます
case2は同じサイズだけnp.zerosで確保したものです。
print(y.shape)で比べても同じです。yの値の内容によって違う処理はありません。ファイル読み込みの全体の長さに対してメモリは十分です。
ファイル読み込みなので簡単に他の環境でテストできないことが残念です。

発生している問題・エラーメッセージ

File "C:\Users\\.conda\envs\py38tfkr\lib\site-packages\keras\utils\np_utils.py", line 71, in to_categorical categorical[np.arange(n), y] = 1 IndexError: index 4377 is out of bounds for axis 1 with size 15

該当のソースコード

python

import sys import numpy as np import tensorflow as tf from tensorflow import keras ncat=15 # カテゴリー数bat = 1000 #ベクトル個数 #case1 """ root = './data' file_path = "data/val.byte" with open("data/val.byte", 'rb') as f: y = np.frombuffer(f.read(), np.int16, offset=0) """ #case2y=np.zeros(144000).astype('int16') #y設定後 print("y.shape",y.shape) l_y = np.zeros((bat)) cl_y = np.zeros((bat,ncat))print("shape l_y",l_y.shape,"cl_y",cl_y.shape,"l_y.szie",l_y.size,"cl_y.size",cl_y.size) for i in range(0, bat): l_y[i] = y[i+1] cl_y = tf.keras.utils.to_categorical(l_y, ncat)

試したこと

コンソール出力

case1実行時

y.shape (144000,) dtype int16 shape l_y (1000,) cl_y (1000, 15) l_y.szie 1000 cl_y.size 15000 Traceback (most recent call last): File "C:\Users\\.conda\envs\py38tfkr\lib\site-packages\spyder_kernels\py3compat.py", line 356, in compat_exec exec(code, globals, locals) File "c:\book\rnn1\rnn4test.py", line 27, in <module> cl_y = tf.keras.utils.to_categorical(l_y, ncat) File "C:\Users\\.conda\envs\py38tfkr\lib\site-packages\keras\utils\np_utils.py", line 71, in to_categorical categorical[np.arange(n), y] = 1 IndexError: index 4377 is out of bounds for axis 1 with size 15

case2実行時

runfile('C:/book/rnn1/RNN4test.py', wdir='C:/book/rnn1') y.shape (144000,) dtype int16 shape l_y (1000,) cl_y (1000, 15) l_y.szie 1000 cl_y.size 15000

コメントを投稿

0 コメント