在我编译和预测模型之前,如何将logits传递给sigmoid_cross_entropy_with_logits?

由于我需要训练一个多标签模型,我需要使用损失函数tf.nn.sigmoid_cross_entropy_with_logits。这个函数有两个参数:logitslabels

参数logits是否是预测的y值?我如何在编译模型之前传递这个值呢?我在编译和拟合模型之前无法预测y,对吗?

这是我的代码:

import tensorflow as tffrom tensorflow import kerasmodel = keras.Sequential([keras.layers.Dense(50, activation='tanh', input_shape=[100]),                             keras.layers.Dense(30, activation='relu'),                            keras.layers.Dense(50, activation='tanh'),                            keras.layers.Dense(100, activation='relu'),                            keras.layers.Dense(8)])model.compile(optimizer='rmsprop',               loss=tf.nn.sigmoid_cross_entropy_with_logits(logits=y_pred), labels=y),   # <---如何在这里确定y_pred?              metrics=['accuracy'])model.fit(x, y, epochs=10, batch_size=32)y_pred = model.predict(x)  # <--- 现在我已经在编译、拟合和预测之后得到了y_pred

我使用的是TensorFlow v2.1.0


回答:

这些参数(labelslogits)被传递到Keras实现的损失函数中。要使您的代码正常工作,可以这样做:

import tensorflow as tffrom tensorflow import kerasdef loss_fn(y_true, y_pred):    return tf.nn.sigmoid_cross_entropy_with_logits(labels=y_true, logits=y_pred)model = keras.Sequential([keras.layers.Dense(50, activation='tanh', input_shape=[100]),                           keras.layers.Dense(30, activation='relu'),                          keras.layers.Dense(50, activation='tanh'),                          keras.layers.Dense(100, activation='relu'),                          keras.layers.Dense(8)])model.compile(optimizer='rmsprop',               loss=loss_fn,              metrics=['accuracy'])x = np.random.normal(0, 1, (64, 100))y = np.random.randint(0, 2, (64, 8)).astype('float32')model.fit(x, y, epochs=10, batch_size=32)y_pred = model.predict(x)

不过,建议的方法是使用Keras的损失函数实现。在您的情况下,应该这样做:

model = keras.Sequential([keras.layers.Dense(50, activation='tanh', input_shape=[100]),                           keras.layers.Dense(30, activation='relu'),                          keras.layers.Dense(50, activation='tanh'),                          keras.layers.Dense(100, activation='relu'),                          keras.layers.Dense(8)])model.compile(optimizer='rmsprop',               loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),              metrics=['accuracy'])x = np.random.normal(0, 1, (64, 100))y = np.random.randint(0, 2, (64, 8)).astype('float32')model.fit(x, y, epochs=10, batch_size=32)y_pred = model.predict(x)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注