keras 如何在python中将一维numpy数组标签编码为二维

txu3uszq  于 2023-04-30  发布在  Python
关注(0)|答案(1)|浏览(119)

我正在用 backbone 数据构建一个人类行为识别的注意力模型。我想让数据集和标签适合模型,但我的标签是一维的。以下是我的数据和标签维度:
x_train.shape =(431,779)
x_test.shape =(430,779)
y_train.shape =(431,)
y_test.shape =(430,)
为了拟合模型,所有x_trian、x_test、y_train和y_test都应该有两个维度。
这是我的模型:

import tensorflow as tf
from tensorflow import keras

inputs = keras.Input(shape=(x_train.shape[0], x_train.shape[1]))
lstm = keras.layers.LSTM(128, return_sequences=True)(inputs)
attention = keras.layers.Attention()([lstm, lstm], return_attention_scores=True)
attention_output = attention[0]
dense = keras.layers.Dense(64, activation='relu')(attention_output)
outputs = keras.layers.Dense(num_classes, activation='softmax')(dense)
model = keras.Model(inputs=inputs, outputs=outputs)

但标签的尺寸应为:(431,27)因为我们有27个行为要认识。
我使用下面的代码转换标签的尺寸,但我得到了错误:

from tensorflow.keras.utils import to_categorical

num_classes = 27

y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)

ValueError:invalid literal for int()with base 10:'a10'
我如何将我的标签编码到具有多个动作类的二维中?如果有人能帮助我,我将不胜感激。

b1zrtrql

b1zrtrql1#

如果标签在列之间应该是相同的(你只想把第二维度增加到27列),我们可以使用numpyappend函数:

import numpy as np
y_train = np.zeros(431).astype(float)
print(f'original shape: {y_train.shape}')
_y_train = y_train
_y_train.shape += (1,)
for _ in range(26):
    _y_train = np.append(_y_train, y_train, axis=1)
print(f'new shape: {_y_train.shape}')

输出:

original shape: (431,)
new shape: (431, 27)

或者,如果第二维27 col umns不应该只是重复标签,并且您想要填充它:

import numpy as np
_y_train = np.zeros((431, 27)).astype(float)
for row in range(_y_train.shape[0]):
    for col in range(_y_train.shape[1]):
        _y_train[row, col] = ...

相关问题