如何使用 python 3 在 tensorflow 中进行自定义列表分类?

how to make custom list classification in tensorflow with python 3?

如何使用 python 3 在 tensorflow 中进行自定义列表分类?

我正在尝试使用此代码制作自定义数据集

import tensorflow as tf
# make the custom dataset
dataset_data = [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[3, 2, 1], [3, 2, 1], [3, 2, 1]], [[3, 2, 1], [5, 2, 1], [3, 2, 1]]]
dataset_label = ['A', 'A', 'B', 'C']
dataset_tf = tf.data.Dataset.from_tensor_slices((dataset_data, dataset_label))

之后,我尝试用这段代码制作模型

# make model
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(128, input_shape=(3,)))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Dense(128))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Dense(1))

之后,我尝试用这段代码编译模型

# compile model
model.compile(optimizer='adam', loss='mse')

之后,我尝试用这段代码训练模型

# fit model
model.fit(dataset_tf, epochs=10)

之后,我尝试用这段代码预测数据

# predict
predict_data = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
prediction = model.predict(predict_data)
print(prediction)

之后,我收到了这样的错误信息

ValueError: slice index 0 of dimension 0 out of bounds. for '{{node strided_slice}} = StridedSlice[Index=DT_INT32, T=DT_INT32, begin_mask=0, ellipsis_mask=0, end_mask=0, new_axis_mask=0, shrink_axis_mask=1](Shape, strided_slice/stack, strided_slice/stack_1, strided_slice/stack_2)' with input shapes: [0], [1], [1], [1] and with computed input tensors: input[1] = <0>, input[2] = <1>, input[3] = <1>.

我该怎么办?为什么会出现此错误?

我的环境

感谢帮助

您可能需要将目标字符串标签编码为整数标签。并且可能需要向训练对添加批处理轴。试试下面的代码。

dataset_data = [[[1, 2, 3], [1, 2, 3], [1, 2, 3]],
                [[1, 2, 3], [1, 2, 3], [1, 2, 3]], 
                [[3, 2, 1], [3, 2, 1], [3, 2, 1]], 
                [[3, 2, 1], [5, 2, 1], [3, 2, 1]]]
                
# dataset_label = ['A', 'A', 'B', 'C']
dataset_label = [0, 1, 2, 3] # decode later

dataset_tf = tf.data.Dataset.from_tensor_slices((dataset_data, dataset_label))
# add batch axis
dataset_tf = dataset_tf.map(lambda x, y: (x[None, ...], y[None, ...]) )
dataset_tf.element_spec
(TensorSpec(shape=(1, 3, 3), dtype=tf.int32, name=None),
 TensorSpec(shape=(1,), dtype=tf.int32, name=None))
model = tf.keras.Sequential()
# input shape (None, 3, 3)
model.add(tf.keras.layers.Dense(128, input_shape=(3,3))) 
model.add(tf.keras.layers.Activation('relu'))

model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(1))

model.compile(optimizer='adam', loss='mse')
model.summary()

model.fit(dataset_tf, epochs=1) # OK
4/4 [==============================] - 0s 2ms/step - loss: 3.1034
<keras.callbacks.History at 0x7f0c7ac0db10>
predict_data = tf.constant([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
prediction = model.predict(predict_data[None, ...])
print(prediction) # OK
[[0.47527248]]