TensorFlow值错误:层顺序的输入0与图层不兼容

发布于 2025-02-11 18:51:12 字数 2115 浏览 0 评论 0原文

我正在尝试建立一个模型,用于使用S& p 500的Kaggle数据进行练习,但是当我尝试选择最佳学习率时收到以下错误:

ValueError: Input 0 of layer sequential_8 is incompatible with the layer: : expected min_ndim=3, found ndim=2. Full shape received: (None, None)

这是我清理的数据:

#Creating np array 
def data_split(arr,split_ratio):
    spt = round(len(arr)*split_ratio)
    arr_train = arr[:spt]
    arr_valid = arr[spt:]
    return arr_train,arr_valid

date = stock['Date'].to_numpy()
close = stock['Close'].to_numpy()
date_train,date_valid = data_split(date,0.7)
close_train,close_valid = data_split(close,0.7)

#Creating Tensorflow data set
import tensorflow as tf
from tensorflow import keras 

def window(arr,window_size,batch_size,shuffle):
    dataset = tf.data.Dataset.from_tensor_slices(arr)
    dataset = dataset.window(window_size+1,shift=1,drop_remainder = True)
    dataset = dataset.flat_map(lambda window:window.batch(window_size+1))
    dataset = dataset.map(lambda window:(window[:-1],window[-1]))
    dataset = dataset.shuffle(shuffle)
    dataset = dataset.batch(batch_size).prefetch(1)
    return dataset

window_size = 40
batch_size = 80
shuffle_buffer_size = 10000

train_data = window(close_train,window_size,batch_size,shuffle_buffer_size)

这是我的模型:我的尝试:

model = tf.keras.models.Sequential([
tf.keras.layers.Conv1D(filters=80,kernel_size=3,activation='relu',padding='causal',input_shape=[window_size, 1]),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(40,return_sequences=True)),
tf.keras.layers.LSTM(20),
tf.keras.layers.Dense(20,activation='relu'),
tf.keras.layers.Dense(10,activation='relu'),
tf.keras.layers.Dense(1)

我的尝试:用LRSCHEDULER pich最好的LR:

#Learning Rate Optimization 
init_weights = model.get_weights()

lr_schedule = tf.keras.callbacks.LearningRateScheduler(
    lambda epoch:1e-8*10**(epoch/20))

optimizer = tf.keras.optimizers.SGD(momentum=0.9)

model.compile(loss=tf.keras.losses.Huber(),optimizer=optimizer)

history = model.fit(train_data,epochs=100, callbacks=[lr_schedule])

有人可以让我知道怎么了,我该如何解决?

I am trying to build a model for practicing with the S&P 500 data on Kaggle, but received the following error when I am trying to pick the optimal Learning rate:

ValueError: Input 0 of layer sequential_8 is incompatible with the layer: : expected min_ndim=3, found ndim=2. Full shape received: (None, None)

Here is the data I cleansed:

#Creating np array 
def data_split(arr,split_ratio):
    spt = round(len(arr)*split_ratio)
    arr_train = arr[:spt]
    arr_valid = arr[spt:]
    return arr_train,arr_valid

date = stock['Date'].to_numpy()
close = stock['Close'].to_numpy()
date_train,date_valid = data_split(date,0.7)
close_train,close_valid = data_split(close,0.7)

#Creating Tensorflow data set
import tensorflow as tf
from tensorflow import keras 

def window(arr,window_size,batch_size,shuffle):
    dataset = tf.data.Dataset.from_tensor_slices(arr)
    dataset = dataset.window(window_size+1,shift=1,drop_remainder = True)
    dataset = dataset.flat_map(lambda window:window.batch(window_size+1))
    dataset = dataset.map(lambda window:(window[:-1],window[-1]))
    dataset = dataset.shuffle(shuffle)
    dataset = dataset.batch(batch_size).prefetch(1)
    return dataset

window_size = 40
batch_size = 80
shuffle_buffer_size = 10000

train_data = window(close_train,window_size,batch_size,shuffle_buffer_size)

Here is my model:

model = tf.keras.models.Sequential([
tf.keras.layers.Conv1D(filters=80,kernel_size=3,activation='relu',padding='causal',input_shape=[window_size, 1]),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(40,return_sequences=True)),
tf.keras.layers.LSTM(20),
tf.keras.layers.Dense(20,activation='relu'),
tf.keras.layers.Dense(10,activation='relu'),
tf.keras.layers.Dense(1)

and my attempt to pich the best lr with lrscheduler:

#Learning Rate Optimization 
init_weights = model.get_weights()

lr_schedule = tf.keras.callbacks.LearningRateScheduler(
    lambda epoch:1e-8*10**(epoch/20))

optimizer = tf.keras.optimizers.SGD(momentum=0.9)

model.compile(loss=tf.keras.losses.Huber(),optimizer=optimizer)

history = model.fit(train_data,epochs=100, callbacks=[lr_schedule])

Could anyone let me know what is wrong and how can I solve it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

野侃 2025-02-18 18:51:12

错误是由于维度不匹配。扩展数据的尺寸将有助于避免错误。

def window(arr,window_size,batch_size,shuffle):
  
  # Expanding the dimensions
  arr = tf.expand_dims(arr, axis=-1)

  dataset = tf.data.Dataset.from_tensor_slices(arr)
  dataset = dataset.window(window_size+1,shift=1,drop_remainder = True)
  dataset = dataset.flat_map(lambda window:window.batch(window_size+1))
  dataset = dataset.map(lambda window:(window[:-1],window[-1]))
  dataset = dataset.shuffle(shuffle)
  dataset = dataset.batch(batch_size).prefetch(1)
  return dataset   

The error is because of the dimension mismatch. Expanding the dimensions of the data will help in avoiding the error.

def window(arr,window_size,batch_size,shuffle):
  
  # Expanding the dimensions
  arr = tf.expand_dims(arr, axis=-1)

  dataset = tf.data.Dataset.from_tensor_slices(arr)
  dataset = dataset.window(window_size+1,shift=1,drop_remainder = True)
  dataset = dataset.flat_map(lambda window:window.batch(window_size+1))
  dataset = dataset.map(lambda window:(window[:-1],window[-1]))
  dataset = dataset.shuffle(shuffle)
  dataset = dataset.batch(batch_size).prefetch(1)
  return dataset   
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文