Форма y_train
- 1D
. Вы должны сделать его горячим закодированным. Что-то типа
y_train = tf.keras.utils.to_categorical(y_train , num_classes=9)
То же самое касается и y_test
.
Обновлять
Согласно документу,
tf.keras.utils.to_categorical(y, num_classes=None, dtype="float32")
Здесь y: вектор класса, который нужно преобразовать в матрицу (целые числа от 0
до num_classes
). Как и в вашем случае, y_train
это что-то вроде [1,2,..]
. Вам нужно сделать следующее:
y_train = tf.keras.utils.to_categorical(y_train - 1, num_classes=9)
Вот пример для справки. Если мы сделаем
class_vector = np.array([1, 1, 2, 3, 5, 1, 4, 2])
print(class_vector)
output_matrix = tf.keras.utils.to_categorical(class_vector,
num_classes = 5, dtype ="float32")
print(output_matrix)
[1 1 2 3 5 1 4 2]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-15-69c8be7a0f1a> in <module>()
6 print(class_vector)
7
----> 8 output_matrix = tf.keras.utils.to_categorical(class_vector, num_classes = 5, dtype ="float32")
9 print(output_matrix)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/utils/np_utils.py in to_categorical(y, num_classes, dtype)
76 n = y.shape[0]
77 categorical = np.zeros((n, num_classes), dtype=dtype)
---> 78 categorical[np.arange(n), y] = 1
79 output_shape = input_shape + (num_classes,)
80 categorical = np.reshape(categorical, output_shape)
IndexError: index 5 is out of bounds for axis 1 with size 5
Чтобы решить эту проблему, мы конвертируем данные в формат с отсчетом от нуля.
output_matrix = tf.keras.utils.to_categorical(class_vector - 1,
num_classes = 5, dtype ="float32")
print(output_matrix)
[[1. 0. 0. 0. 0.]
[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1.]
[1. 0. 0. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 1. 0. 0. 0.]]
person
M.Innat
schedule
04.04.2021