我想将下面的字符串转换为分类形式或热编码。
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'
逻辑上错误提示您将str类型转换为int。
Like int('20') = 20 - Correct
int('Interstitial') - ValueError: invalid literal for int() with base 16: 'Interstitial'
这是因为
keras只支持对已经存在的数据进行单热编码integer-encoded .
在这种情况下,您可以使用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)
Tensorflow在这里已经明确提到,tf.keras.utils.to_categorical
是用于将类向量(整数)转换为二进制类矩阵的。
您的data
变量包含字符串类型元素,这与integer
不同,因此出现错误。