我正在尝试建立一个机器学习模型,它可以从一系列数字中预测单个数字。我正在使用Tensorflow的keras API中的顺序模型。
你可以想象我的数据集是这样的:
<表类>
指数
x数据
y数据
tbody><<tr>0 1 2 3 … … … 表类>
np.ndarray(shape (1209278,) )
numpy.float32
np.ndarray(shape (1211140,) )
numpy.float32
np.ndarray(shape (1418411,) )
numpy.float32
np.ndarray(shape (1077132,) )
numpy.float32
试试这样:
import numpy as np
import tensorflow as tf
# add additional dimension for lstm layer
x_train = np.asarray(train_set["x data"].values))[..., None]
y_train = np.asarray(train_set["y data"]).astype(np.float32)
model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(units=32))
model.add(tf.keras.layers.Dense(units=1))
model.compile(loss="mean_squared_error", optimizer="adam", metrics="mse")
model.fit(x=x_train,y=y_train,epochs=10)
或使用不同序列长度的不规则输入:
x_train = tf.ragged.constant(train_set["x data"].values[..., None]) # add additional dimension for lstm layer
y_train = np.asarray(train_set["y data"]).astype(np.float32)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Input(shape=[None, x_train.bounding_shape()[-1]], batch_size=2, dtype=tf.float32, ragged=True))
model.add(tf.keras.layers.LSTM(units=32))
model.add(tf.keras.layers.Dense(units=1))
model.compile(loss="mean_squared_error", optimizer="adam", metrics="mse")
model.fit(x=x_train,y=y_train,epochs=10)
或:
x_train = tf.ragged.constant([np.array(list(v))[..., None] for v in train_set["x data"].values]) # add additional dimension for lstm layer