tensorflow - 模型的损失增加仅适用于更大的数据
问题描述
我使用张量流实现了一个简单的线性回归模型。然而,它仅适用于大约 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())
推荐阅读
- java - 使用相同的 appender 回溯几个记录器
- ruby-on-rails - 我可以在really_destroy 之后重新创建一个对象!它 ?我不想恢复它,而是用相同的电子邮件创建一个新对象
- python - 将 R GET 方法转换为 Python
- json - 如何使用 Jackson ObjectMapper 转义无效的 Mongo 字段名称字符?
- java - Firebase 数据库快照以动态回收查看数组列表
- javascript - 如何将项目按顺序放入数组中?(javascript)
- java - 无法在 build.gradle 中初始化 flyway{}
- c# - 使用转换器按 DataGrid 列中的值更改 DataGrid 行颜色
- c# - 如何在特定打印机中打印文件?
- android - Android Studio - 关闭浮动 Logcat 窗口的快捷方式?