使用 Keras 进行简单预测

数据挖掘 Python 喀拉斯 预测建模 预言
2021-10-01 03:50:31

我想用 Keras 做简单的预测,但我不确定我是否做对了。我的数据如下所示:

col1,col2
1.68,237537
1.69,240104
1.70,244885
1.71,246196
1.72,246527
1.73,254588
1.74,255112
1.75,259035
1.76,267229
1.77,267314
1.78,268931
1.79,273497
1.80,273900
1.81,277132
1.82,278066

现在,我想预测col2col1这就是我的做法:

df = pandas.read_csv('data.csv', usecols=[0, 1], header=None)
X = df.iloc[:, :-1].values.astype(np.float64)
y = df.iloc[:, -1:].values.astype(np.float64)
scalarX, scalarY = MinMaxScaler(), MinMaxScaler()
标量X.fit(X)
scalarY.fit(y.reshape(len(y),1))
X = 标量X.transform(X)
y = scalarY.transform(y.reshape(len(y),1))

模型=顺序()
model.add(密集(4,input_dim=1,激活='relu'))
model.add(密集(4,激活='relu'))
model.add(密集(1,激活='线性'))
model.compile(损失='mse',优化器='adam')
model.fit(x=X, y=y, epochs=3, 详细=1)
对于范围内的 num(1, 21):
    Xnew = np.array([[float(Decimal('2.{}'.format(num)))]])
    ynew = model.predict(Xnew)
    print("X=%s, 预测=%s" % (Xnew[0], ynew[0]))
1个回答

您在这里尝试做的是预测时间序列的未来值。这是一个预测问题,未来值将取决于许多潜在因素。正如您的问题所表明的那样,我将假设我们可以访问的只是该系列的历史数据。

如果您想预测时间序列的未来值,您不仅应该使用当前值作为输入,还应该使用大量历史数据。由于您有 18,000,000 个实例,这很多,您可以使您的网络非常复杂,以便捕获隐藏在数据中的一些潜在趋势,这有助于预测未来价值。预测时间值我们将使用ķ以前的值。这个超参数需要有效地调整。

重构数据

我们将构建数据,使得特征Xķ 以前的时间测量和输出目标 是当前时间测量。模型正在估计的那个。

k = 3
X, Y = [], []
for i in range(len(col1) - k):
    X.append(col2[i:i+k])
    Y.append(col2[i+k])

X = np.asarray(X)
Y = np.asarray(Y)

拆分数据

from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.33)

在 Keras 模型中使用数据

这是一个简单的 Keras 模型,应该作为第一个迭代步骤。但是,由于您提供给我们的数据量很少,训练后我无法获得任何有意义的结果。

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv1D, MaxPooling1D, Reshape
from keras.callbacks import ModelCheckpoint
from keras.models import model_from_json
from keras import backend as K

x_train = x_train.reshape(len(x_train), k, )
x_test = x_test.reshape(len(x_test), k, )

input_shape  = (k,)

model = Sequential()
model.add(Dense(32, activation='tanh',
                 input_shape=input_shape))
model.add(Dense(32, activation='tanh'))
model.add(Dense(1, activation='linear'))

model.compile(loss=keras.losses.mean_squared_error,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.summary()

epochs = 10
batch_size = 128
# Fit the model weights.
history = model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))