python - 带有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 和预测时,我看到这些值以某种方式缩放。
有人可以理解我做错了什么吗?
解决方案
您正在设置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
推荐阅读
- reactjs - React,如何通过重新选择停止重新渲染应用程序?
- java - 文件中的 Rserve 错误(文件名,“r”,编码 = 编码):无法打开连接
- javascript - 如何根据 laravel 中的选择选项动态地完成输入?
- aframe - 为什么这个 A-frame 代码在 Glitch.com 中有效,但在我的网站上无效?
- javascript - 如何测试具有特定名称的组件是否在 Composition API (Vue 3) 中注册
- python - 在正则表达式中组合括号和单词边界
- xcode - ld: 找不到 -lSystem 的库,试图编译telldus源
- java - 如何使微调器中的第一项作为占位符?
- javascript - 如何通过 js-sumo-logger 中的节点服务器发送批量 Sumo Logic 日志
- string - Haskell 字符串解码