使用Keras进行线性回归:模型预测不正确

0 投票
1 回答
26 浏览
提问于 2025-04-13 13:20

请帮我一下,我想知道为什么我的简单线性回归模型预测不准确。我正在尝试理解keras。

我想用keras来建立一个简单的线性回归模型。但是我预测的结果不对。请帮帮我。

import numpy as np
import tensorflow as tf
from tensorflow import keras

# Data
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# Define the model
model = Sequential()
model.add(Dense(units=1, input_shape=(1,)))
model.compile(optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.005), loss='mse')

model.fit(x,y, epochs=100, verbose=0)

x1=[11,12,13]
predy= model.predict(x1)

print(predy)

1 个回答

2

这里的问题是,你没有把损失函数降到最低。也就是说,你的模型还没有收敛。一个没有把损失函数降到最低的模型,是无法给出好的预测结果的。要注意,机器学习通常需要大量的数据。因为你的数据点比较少,所以你需要更多的迭代次数来降低损失。试着自己实现一下线性回归的梯度下降算法,你会发现收敛需要一些时间。给上面的机器学习代码同样的时间去运行。下面是代码:

# Data
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# Define the model
model = tf.keras.Sequential(
  [tf.keras.layers.Dense(units=1, input_shape=(1,))]
)

model.compile(optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.01), loss='mse')

model.fit(x,y, epochs=2000, verbose=0)

x1=[11,12,13]
predy= model.predict(x1)

print(predy)

[[110.059975]
 [120.06498 ]
 [130.06998 ]]

你可以通过查看一些指标来判断模型是否收敛。如果损失值离0还很远,那说明你还没有收敛。

model.get_metrics_result()['loss']
<tf.Tensor: shape=(), dtype=float32, numpy=0.0012610962>

试试这个方法在你的例子上,你会发现你有一个非常大的数字。

撰写回答