首页 > 解决方案 > 带有keras的回归模型

问题描述

我正在尝试使用 Keras 构建我的第一个回归模型,而我所看到的对我来说毫无意义。我的代码:

import pandas as pd

from keras.models import Sequential
from keras.layers import Dense

def build_model(X, y):
    display(X.shape)

    model = Sequential()

    model.add(Dense(8, activation='relu', input_shape=(X.shape[1],)))
    model.add(Dense(1))

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

    model.fit(X, y, epochs=20)

    _, accuracy = model.evaluate(X, y)
    print('Accuracy: %.2f' % (accuracy*100))

    return model

X=pd.DataFrame({'a':[1,2,3,4,5], 'b':[2,3,4,5,6]})
y=pd.Series([3,4,5,6,7])

model = build_model(X, y)

df = pd.DataFrame({'y': y, 'predict_y': [x for [x] in model.predict(X)]})

print(df)
print(df.corr())

打印类似:

(5, 2)
Epoch 1/20
5/5 [==============================] - 0s 13ms/step - loss: 20.8061 - accuracy: 0.0000e+00
Epoch 2/20
5/5 [==============================] - 0s 351us/step - loss: 20.6125 - accuracy: 0.0000e+00
...
Epoch 19/20
5/5 [==============================] - 0s 314us/step - loss: 17.5301 - accuracy: 0.0000e+00
Epoch 20/20
5/5 [==============================] - 0s 216us/step - loss: 17.3576 - accuracy: 0.0000e+00
5/5 [==============================] - 0s 3ms/step
Accuracy: 0.00
   y  predict_y
0  3   0.525354
1  4   0.775924
2  5   1.003626
3  6   1.231329
4  7   1.459031
                  y  predict_y
y          1.000000   0.999806
predict_y  0.999806   1.000000

在相关矩阵上看起来都不错,几乎 100% 相关。当我转储 y 和预测时,我看到这些值以某种方式缩放。

有人可以理解我做错了什么吗?

标签: pythonpandaskeras

解决方案


您正在设置accuracy为您的指标,即使您的损失函数设置为mean_squared_error.

再次运行,但随后 withmetrics=['mse']应该会给你更好的结果:

   y  predict_y
0  3   1.753360
1  4   2.771525
2  5   3.788639
3  6   4.803446
4  7   5.818252
             y  predict_y
y          1.0        1.0
predict_y  1.0        1.0

推荐阅读