我收到ValueError:没有为任何变量提供渐变

时间:2020-07-31 19:04:18

标签: python tensorflow

尝试使我的代码正常工作遇到麻烦

import tensorflow as tf
from tensorflow import keras
import numpy as np
import pandas as pd
import csv
from sklearn.model_selection import train_test_split

batch_size = 1

csv = "EmergeSync.csv"
val_csv = "EmergeSync.csv"

dataframe = pd.read_csv(csv)

#Split the data
train, test_ds = train_test_split(dataframe, train_size=0.8, test_size=0.2)
train_ds, val_ds = train_test_split(train, train_size=0.8, test_size=0.2)

#Building the model
model = keras.Sequential()

units = 7

model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(units=units, activation='linear'))
model.add(keras.layers.Dense(units=units, activation='linear'))
model.add(keras.layers.Dense(units=units, activation='linear'))

model.compile(optimizer="adam", loss="mean_squared_error", metrics=["accuracy"])

num_epochs = 2

history = model.fit(train_ds, epochs=num_epochs, steps_per_epoch=5, batch_size=batch_size, shuffle=True, validation_data=val_ds, verbose=1)
print(history)

我收到以下错误:

ValueError: No gradients provided for any variable: ['sequential/dense/kernel:0', 'sequential/dense/bias:0', 'sequential/dense_1/kernel:0', 'sequential/dense_1/bias:0', 'sequential/dense_2/kernel:0', 'sequential/dense_2/bias:0'].

我不知道是什么导致了此错误。如果有人可以帮助我,那就太好了!

1 个答案:

答案 0 :(得分:0)

因此基本上该错误是正确的,优化器未找到渐变,并且无法再更新您的网络。

现在,您需要问自己如何计算梯度。通过将损失函数w.r.t的偏导数乘以所有参数来计算。

您的损失函数为mean_square_error,因此看起来像(y-y')**2

这里y是您的原始期望值,y'是模型输出的结果。

如果不存在两者之一,则无法计算梯度。

在您的情况下,您没有为模型提供y,因此,它无法计算梯度并且无法更新参数值。

您将必须执行以下操作。

history = model.fit(x=train_ds, y=np.zeros((10880,7)), epochs=num_epochs, steps_per_epoch=5, batch_size=batch_size, shuffle=True, validation_data=val_ds, verbose=1)

我不知道您的y,所以我获取了伪数据,但是您将不得不以上述方式调用fit API。

我已经尝试过您的代码,并且可以在我的系统上运行。希望这个答案对您有帮助。