Я хочу преобразовать приведенную ниже строку в категориальную форму или одну горячую кодировку.
string1 = "Interstitial markings are diffusely prominent throughout both lungs. Heart size is normal. Pulmonary XXXX normal."
st1 = string1.split()
Я использую приведенный ниже код, но он генерирует ошибку.
from numpy import array
from numpy import argmax
from keras.utils import to_categorical
# define example
data = array(st1)
print(data)
encoded = to_categorical(data)
print(encoded)
# invert encoding
inverted = argmax(encoded[0])
print(inverted)
ошибка
['Interstitial' 'markings' 'are' 'diffusely' 'prominent' 'throughout' 'both' 'lungs.' 'Heart' 'size' 'is' 'normal.' 'Pulmonary' 'XXXX''normal.']
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-b034d9393342> in <module>
5 data = array(st1)
6 print(data)
----> 7 encoded = to_categorical(data)
8 print(encoded)
9 # invert encoding
/usr/local/lib/python3.7/dist-packages/keras/utils/np_utils.py in to_categorical(y, num_classes, dtype)
60 [0. 0. 0. 0.]
61 """
---> 62 y = np.array(y, dtype='int')
63 input_shape = y.shape
64 if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
ValueError: invalid literal for int() with base 10: 'Interstitial'
Tensorflow четко упомянул здесь, что tf.keras.utils.to_categorical
предназначен для преобразования вектора класса (целые числа) в бинарную матрицу класса.
Ваша переменная data
содержит элементы строкового типа, которые не совпадают с integer
, отсюда и ошибка.
Логически ошибка говорит, что вы приводите тип str к int.
Like int('20') = 20 - Correct
Нравиться
int('Interstitial') - ValueError: invalid literal for int() with base 16: 'Interstitial'
Это потому что
keras поддерживает однократное горячее кодирование только для данных, которые уже были целочисленное кодирование.
В таких случаях вы можете использовать LabelEncoder
следующим образом.
string1 = "Interstitial markings are diffusely prominent throughout both lungs. Heart size is normal. Pulmonary XXXX normal."
st1 = string1.split()
from sklearn.preprocessing import LabelEncoder
import numpy as np
data = np.array(st1)
label_encoder = LabelEncoder()
data = label_encoder.fit_transform(data)
print(data)
##
##
##From here encode according next part of your code using to_categorical(data)
Дает #
array([ 1, 9, 4, 6, 11, 13, 5, 8, 0, 12, 7, 10, 2, 3, 10],
dtype=int64)