【问题标题】:Loss Increasing for model only for bigger data模型的损失增加仅适用于更大的数据
【发布时间】:2020-04-10 14:10:34
【问题描述】:

我使用张量流实现了一个简单的线性回归模型。然而,它仅适用于大约 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】:

    你的损失爆炸的原因是你的数据没有标准化。随着数据点数量的增加,输入数据的量级变得更大。

    我该如何解决它

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

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

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多