tensorflow - 感知损失函数没有给出任何梯度张量流
问题描述
我正在尝试在张量流中实现感知损失函数,这里是
loss_model = tf.keras.models.Sequential()
for eachLayer in base_model.layers[:12]:
eachLayer.trainable=False
loss_model.add(eachLayer)
def meanSquaredLoss(y_true,y_pred):
return tf.reduce_mean(tf.keras.losses.MSE(y_true,y_pred))
def featureLoss(image):
predicted_image = model(image,training=False)
activatedModelVal = loss_model(predicted_image,training=False)
actualModelVal = loss_model(image,training=False)
return meanSquaredLoss(actualModelVal,activatedModelVal)
这是由下式给出的样式损失函数:
def gram_matrix(input_tensor):
result = tf.linalg.einsum('bijc,bijd->bcd', input_tensor, input_tensor)
input_shape = tf.shape(input_tensor)
num_locations = tf.cast(input_shape[1]*input_shape[2], tf.float32)
return result/(num_locations)
def styleLoss(image):
predicted_image = model(image,training=False)
activatedModelVal = loss_model(predicted_image,training=False)
actualModelVal = loss_model(image,training=False)
return meanSquaredLoss(gram_matrix(actualModelVal),gram_matrix(activatedModelVal))
所以现在我有两个损失,这就是我为优化和东西所做的!
opt = tf.keras.optimizers.Adam(0.02)
def each_train_step(image,showImage=False):
predicted_image = model(image,training=False)
loss = tf.reduce_sum(featureLoss(predicted_image,image)+styleLoss(predicted_image,image))
with tf.GradientTape() as tape:
grad = tape.gradient(loss, model.trainable_variables)
print(grad)
# opt.apply_gradients(zip(grad, model.trainable_variables))
if showImage:
plt.imshow(predicted_image)
问题是 grad 对象正在获取列表,None
我不知道为什么!为什么梯度返回列表None?任何获得实际梯度的解决方案?
解决方案
推荐阅读
- joomla - Joomla - 无法在已停用插件的仪表板插件页面中包含 CSS
- android - 同一设备上的两个用户 | 设置用户 ID 行为
- c# - 如何淘汰.Net框架中的现有方法?
- hadoop - JAVA_HOME 未设置且无法找到。安装 HADOOP 时出错
- leptonica - JavaCPP Leptonica:如何清除 pixClone 句柄的内存
- android - 用于屏幕锁定的 Android API
- java - 如何在代理后面使用 resttemplate 进行多重身份验证
- python - 将 Windows 文件夹权限更改为从 Python 只读
- cuda - 获取 cuda 上下文的内存使用情况
- javascript - reactJS中如何管理多标签注销?