最近在自定义损失函数来优化LSTM模型,想预测未来五天的股票收盘价格,然后根据预测的价格确定这五天什么时候买入,什么时候卖出,比如未来五天是[1,2,3,2,5]那么就是在第一天买入,第三天卖出,在第四天买入,第五天卖出,这样能获得最大的收益。那么根据预测的价格就确定了具体的买入卖出时间,然后根据这个时间在真实价格上进行操作,就计算得到预测的最大收益。那么真实的收益就自然是根据相同的策略在真实价格上进行操作。
具体代码如下
def strategy(fivedayprice):
actlist=[]
label=False
for i in range(4):
if fivedayprice[i+1]>fivedayprice[i] and label==False:
actlist.append(1)
label=True
elif fivedayprice[i+1]<fivedayprice[i] and label==True:
actlist.append(-1)
label=False
elif fivedayprice[i+1]<fivedayprice[i] and label==False:
actlist.append(0)
elif fivedayprice[i+1]>fivedayprice[i] and label==True:
actlist.append(0)
if label ==True:
actlist.append(-1)
if label ==False:
actlist.append(0)
return actlist
def get_profit(y_pred,y_true):
labellist=[]
profitlist=[]
num=len(y_pred)
for i in range(num):
labellist.append(strategy(y_pred[i]))
for j in range(len(labellist)):
profit=0
for n in range(5):
if labellist[j][n]==1:
profit=profit-y_true[j][n]
elif labellist[j][n]==0:
pass
elif labellist[j][n]==-1:
profit =profit+y_true[j][n]
profitlist.append(profit)
return profitlist
import tensorflow.keras.backend as K
def profitloss(y_true, y_pred):
y_true = tf.convert_to_tensor(y_true)
y_pred = tf.convert_to_tensor(y_pred)
trueprofitlist = tf.convert_to_tensor(get_profit(y_true, y_true))
predprofitlist = tf.convert_to_tensor(get_profit(y_pred, y_true))
loss=K.mean(K.square(trueprofitlist-predprofitlist))
return loss
最后在训练模型的时候报错没有梯度
ValueError: No gradients provided for any variable: (['lstm_62/lstm_cell/kernel:0', 'lstm_62/lstm_cell/recurrent_kernel:0', 'lstm_62/lstm_cell/bias:0', 'lstm_63/lstm_cell/kernel:0', 'lstm_63/lstm_cell/recurrent_kernel:0', 'lstm_63/lstm_cell/bias:0', 'dense_62/kernel:0', 'dense_62/bias:0', 'dense_63/kernel:0', 'dense_63/bias:0'],). Provided `grads_and_vars` is ((None, <tf.Variable 'lstm_62/lstm_cell/kernel:0' shape=(9, 512) dtype=float32>), (None, <tf.Variable 'lstm_62/lstm_cell/recurrent_kernel:0' shape=(128, 512) dtype=float32>), (None, <tf.Variable 'lstm_62/lstm_cell/bias:0' shape=(512,) dtype=float32>), (None, <tf.Variable 'lstm_63/lstm_cell/kernel:0' shape=(128, 512) dtype=float32>), (None, <tf.Variable 'lstm_63/lstm_cell/recurrent_kernel:0' shape=(128, 512) dtype=float32>), (None, <tf.Variable 'lstm_63/lstm_cell/bias:0' shape=(512,) dtype=float32>), (None, <tf.Variable 'dense_62/kernel:0' shape=(128, 10) dtype=float32>), (None, <tf.Variable 'dense_62/bias:0' shape=(10,) dtype=float32>), (None, <tf.Variable 'dense_63/kernel:0' shape=(10, 5) dtype=float32>), (None, <tf.Variable 'dense_63/bias:0' shape=(5,) dtype=float32>)).
请问怎么解决啊