仅针对更大数据的模型损失增加

Loss Increasing for model only for bigger data

我使用 Tensor Flow 实现了一个简单的线性回归模型。但是它只适用于大约 10-15 个数据点。除此之外,损失函数开始急剧增加,直到达到无穷大。数据是正确的,因为我是综合生成的。 sklearn 线性回归模型非常适合相同的数据。

size = 8
x = np.float32(np.arange(size).reshape((size,1)))
y = x*8

class Linear_Model():
    def __init__(self,input_dim,lr=0.01):
        self.w = tf.Variable(tf.ones(shape=(input_dim,1)))
        self.b= tf.Variable(tf.zeros(shape=(input_dim)))
        self.lr = lr
    def predict(self,x):
        return tf.matmul(x,self.w) + self.b 

    def compute_loss(self,label,predictions):
        return tf.reduce_mean(tf.square(label-predictions))

    def train(self,x,y,epochs=12,batch_size=64):
        dataset = tf.data.Dataset.from_tensor_slices((x,y))
        dataset = dataset.shuffle(buffer_size=1024).batch(batch_size)
        for i in range(epochs):
            start = time.time()
            for step,(x,y) in enumerate(dataset):
                with tf.GradientTape() as tape:
                    preds = self.predict(x)
                    loss = self.compute_loss(y,preds)
                    dw,db = tape.gradient(loss,[self.w,self.b])
                    self.w.assign_sub(self.lr*dw)
                    self.b.assign_sub(self.lr*db)
                    print("Epoch %d : loss = %.4f time taken = %.3f s"% (i,float(loss),time.time()-start))
model = Linear_Model(1,0.01)
model.train(x,y,epochs=15)

编辑 - 通过研究学习率,我发现 0.01 的学习率太大了。然而,对于我在网络上看到的所有实现,这都不是问题。这里发生了什么?

你的损失激增的原因是你的数据没有规范化。当您增加数据点的数量时,输入数据的量级会变大。

我该如何解决?

在输入模型之前标准化您的数据:

x = (x - x.min()) / (x.max() - x.min())
y = (y - y.min()) / (y.max() - y.min())