仅针对较大数据,模型损失增加

问题描述 投票:0回答:1

我使用张量流实现了一个简单的线性回归模型。但是,它仅适用于大约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太大了。但是,这对于我在网络上看到的所有实现都不是问题。这是怎么回事?

tensorflow linear-regression gradient-descent
1个回答
3
投票

您的损失激增的原因是您的数据未规范化。随着数据点数量的增加,输入数据的大小将变大。

我该如何修复

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

x = (x - x.min()) / (x.max() - x.min())
y = (y - y.min()) / (y.max() - y.min())
© www.soinside.com 2019 - 2024. All rights reserved.