TensorFlow Keras在期待一个预测的同时返回了多个预测 [英] TensorFlow Keras returning multiple predictions while expecting one

查看:118
本文介绍了TensorFlow Keras在期待一个预测的同时返回了多个预测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习TensorFlow和LSTM,并且想知道为什么我在训练预测输出返回一个值时为什么我的预测输出具有多个值.我的目标是在使用数组进行情感分析训练之后,获得介于0和1之间的单个值.

I'm learning TensorFlow and LSTM and I'm wondering why my prediction output has multiple values when I'm training it to return one. My goal is to get a single value between 0 and 1 after training it with arrays for sentiment analysis.

训练输入数据如下:

[[59, 21, ... 118, 194], ... [12, 110, ... 231, 127]]

所有输入数组的长度都相同,并用0填充.训练目标数据如下:

All input arrays are of the same length padded with 0. The training target data looks like:

[1.0, 0.5, 0.0, 1.0, 0.0 ...]

型号:

model = Sequential()
model.add(Embedding(input_length, 64, mask_zero=True))
model.add(LSTM(100))
model.add(Dense(1, activation=tf.nn.sigmoid))

为什么预测似乎一次评估每个单独的值,而不是整个数组?

model.predict([192])
# Returns [[0.5491102]]
model.predict([192, 25])
# Returns [[0.5491102, 0.4923803]]
model.predict([192, 25, 651])
# Returns [[0.5491102, 0.4923803, 0.53853387]]

我不想取输出的平均值,因为输入数组中的值之间的关系对于情感分析很重要.如果我正在训练预测单个值,那么我将不理解为什么不输出单个值.我是TensorFlow,Keras和分层神经网络的新手,所以我确定我缺少明显的东西.

I don't want to take an average of the output because the relationships between the values in the input arrays matter for sentiment analysis. If I'm training to predict a single value I'm not understanding why a single value isn't output. I'm new to TensorFlow, Keras, and layered neural networks, so I'm sure I'm missing something obvious.

推荐答案

编写时:

model.predict([192, 25, 651])

如果您要给模型提供三个输入样本,那么作为回报,您将获得三个输出,每个输入样本一个.相反,如果用[192, 25, 651]表示一个输入样本,则将其包装在两个列表中:

it is if you are giving the model three input samples and therefore in return you would get three outputs, one for each input sample. Instead, if by [192, 25, 651] you really mean one input sample, then you wrap it in two lists:

model.predict([[[192, 25, 651]]])

原因:最外面的列表对应于模型的所有输入层的所有输入数据的列表,此处为其中之一.第二个列表对应于第一个(也是唯一一个)输入层的数据,第三个列表对应一个输入样本.列表输入就是这种情况,因为多输入(和多输出)Keras模型应将输入数组的列表作为输入.一种更好的方法是改用numpy数组:

The reason: the most outer list corresponds to the list of all the input data for all the input layers of the model, which is one here. The second list corresponds to the data for the first (and only) input layer and the third list corresponds the one input sample. That's the case with list inputs, since multi-input (and multi-output) Keras models should take a list of input arrays as input. One better way is to use a numpy array instead:

model.predict(np.array([[192, 25, 651]]))

np.array([[192, 25, 651]])的形状为(1,3),表示一个长度为3的样本.

np.array([[192, 25, 651]]) has a shape of (1,3) which means one sample of length 3.

这篇关于TensorFlow Keras在期待一个预测的同时返回了多个预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆