keras ValueError:基数为16的int()的文字无效:'间隙'

nqwrtyyt  于 2022-11-24  发布在  其他
关注(0)|答案(2)|浏览(144)

我想把下面的字符串转换成分类形式或一个热编码。

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'
2nbm6dog

2nbm6dog1#

从逻辑上讲,错误是将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)
xmq68pz9

xmq68pz92#

Tensorflow已经清楚地提到了here,即tf.keras.utils.to_categorical是用于将类向量(整数)转换为二进制类矩阵的。
您的data变量包含字符串类型元素,这与integer不同,因此出现错误。

相关问题