【问题标题】:TensorFlow - why doesn't this sofmax regression learn anything?TensorFlow - 为什么这个 sofmax 回归没有学到任何东西?
【发布时间】:2016-02-26 06:54:16
【问题描述】:

我的目标是用 TensorFlow 做大事,但我试图从小事做起。

我有小灰度方块(有一点噪点),我想根据颜色对它们进行分类(例如 3 个类别:黑色、灰色、白色)。我编写了一个 Python 小类来生成正方形和 1-hot 向量,并修改了它们的基本 MNIST 示例来输入它们。

但它不会学到任何东西 - 例如。对于 3 个类别,它总是猜测 ≈33% 正确。

import tensorflow as tf
import generate_data.generate_greyscale

data_generator = generate_data.generate_greyscale.GenerateGreyScale(28, 28, 3, 0.05)
ds = data_generator.generate_data(10000)
ds_validation = data_generator.generate_data(500)
xs = ds[0]
ys = ds[1]
num_categories = data_generator.num_categories

x = tf.placeholder("float", [None, 28*28])
W = tf.Variable(tf.zeros([28*28, num_categories]))
b = tf.Variable(tf.zeros([num_categories]))
y = tf.nn.softmax(tf.matmul(x,W) + b)
y_ = tf.placeholder("float", [None,num_categories])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

# let batch_size = 100 --> therefore there are 100 batches of training data
xs = xs.reshape(100, 100, 28*28) # reshape into 100 minibatches of size 100
ys = ys.reshape((100, 100, num_categories)) # reshape into 100 minibatches of size 100

for i in range(100):
  batch_xs = xs[i]
  batch_ys = ys[i]
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

xs_validation = ds_validation[0]
ys_validation = ds_validation[1]
print sess.run(accuracy, feed_dict={x: xs_validation, y_: ys_validation})

我的数据生成器如下所示:

import numpy as np
import random

class GenerateGreyScale():
    def __init__(self, num_rows, num_cols, num_categories, noise):
        self.num_rows = num_rows
        self.num_cols = num_cols
        self.num_categories = num_categories
        # set a level of noisiness for the data
        self.noise = noise

    def generate_label(self):
        lab = np.zeros(self.num_categories)
        lab[random.randint(0, self.num_categories-1)] = 1
        return lab

    def generate_datum(self, lab):
        i = np.where(lab==1)[0][0]
        frac = float(1)/(self.num_categories-1) * i
        arr = np.random.uniform(max(0, frac-self.noise), min(1, frac+self.noise), self.num_rows*self.num_cols)
        return arr

    def generate_data(self, num):
        data_arr = np.zeros((num, self.num_rows*self.num_cols))
        label_arr = np.zeros((num, self.num_categories))
        for i in range(0, num):
            label = self.generate_label()
            datum = self.generate_datum(label)
            data_arr[i] = datum
            label_arr[i] = label
        #data_arr = data_arr.astype(np.float32)
        #label_arr = label_arr.astype(np.float32)
        return data_arr, label_arr

【问题讨论】:

    标签: python machine-learning computer-vision tensorflow


    【解决方案1】:

    对于初学者,请尝试使用随机值而不是零来初始化 W 矩阵 - 当所有输入的输出全为零时,您不会给优化器任何可使用的东西。

    代替:

    W = tf.Variable(tf.zeros([28*28, num_categories]))
    

    试试:

    W = tf.Variable(tf.truncated_normal([28*28, num_categories],
                                        stddev=0.1))
    

    【讨论】:

    • 我现在使用tf.truncated_normal() 和tf.constant() 作为您和他们的tutorial 建议的权重和偏差。但仍然没有变化:随机猜测 y。 :(
    • 您确定您的数据没有错误吗? ds[0] 是 100 项吗? ds = data_generator.generate_data(10000) xs = ds[0] xs = xs.reshape(100, 100, 28*28) 如果 xs 在你重塑之前有正确的数字,我会更舒服...
    • 嗨。 nparray xs 以形状 (10000, 784) 开始,然后调整为 (100, 100, 784)。我更改了我的帖子以包含创建数据的类,因此您可以根据需要尝试一下。谢谢!
    • 我也一直在研究正方形的大小——对于非常小的灰度正方形(低于大约 7x7 像素),softmax 回归的误差为 0%。然后将宽度或高度增加 1 个像素,它会跳回到 66% 的错误。
    【解决方案2】:

    您的问题是您的梯度无限增加/减少,导致损失函数变为 nan。

    看看这个问题:Why does TensorFlow example fail when increasing batch size?

    此外,请确保您运行模型的步数足够多。您只在您的训练数据集上运行一次(100 次 * 100 个示例),这还不足以使其收敛。至少将其增加到 2000 左右(通过您的数据集运行 20 次)。

    编辑(无法评论,所以我会在这里添加我的想法): 我链接的帖子的重点是您可以使用GradientDescentOptimizer,只要您将学习率设置为 0.001 左右。这就是问题所在,你的学习率对于你使用的损失函数来说太高了。

    或者,使用不同的损失函数,它不会增加/减少梯度。在crossEntropy 的定义中使用tf.reduce_mean 而不是tf.reduce_sum。

    【讨论】:

      【解决方案3】:

      虽然 dga 和 syncd 的响应很有帮助,但我尝试使用非零权重初始化和更大的数据集,但无济于事。最终奏效的是使用不同的优化算法。

      我换了:

      train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

      与

      train_step = tf.train.AdamOptimizer(0.0005).minimize(cross_entropy)

      我还将 for 循环的训练嵌入到另一个 for 循环中以训练几个 epoch,从而产生如下收敛:

       ===# EPOCH 0 #===
      Error: 0.370000004768
       ===# EPOCH 1 #===
      Error: 0.333999991417
       ===# EPOCH 2 #===
      Error: 0.282000005245
       ===# EPOCH 3 #===
      Error: 0.222000002861
       ===# EPOCH 4 #===
      Error: 0.152000010014
       ===# EPOCH 5 #===
      Error: 0.111999988556
       ===# EPOCH 6 #===
      Error: 0.0680000185966
       ===# EPOCH 7 #===
      Error: 0.0239999890327
       ===# EPOCH 8 #===
      Error: 0.00999999046326
       ===# EPOCH 9 #===
      Error: 0.00400000810623
      

      编辑 - 为什么会这样:我想问题是我没有手动选择一个好的学习率计划,而 Adam 能够自动生成一个更好的计划。

      【讨论】:

        【解决方案4】:

        当我遇到类似问题时发现了这个问题。我通过缩放功能修复了我的问题。

        一点背景知识:我正在关注 tensorflow 教程,但是我想使用来自 Kaggle(see data here) 的数据进行建模,但一开始我一直遇到同样的问题:模型只是没有学习..经过几轮故障排除,我意识到 Kaggle 数据的规模完全不同。因此,我对数据进行了缩放,使其与 tensorflow 的 MNIST 数据集具有相同的 scale(0,1)。

        只是想我会在这里加两分钱..以防一些尝试遵循教程设置的初学者像我一样卡住=)

        【讨论】:

        • 是的 - 对于迁移学习,必须检查您的新数据是否以与您正在迁移的模型的原始训练数据相同的方式进行预处理。请注意,我遇到的这个问题与学习率有关,我正在使用区间 [0, 1] 生成的人工数据从头开始训练模型。
        猜你喜欢
        • 1970-01-01
        • 2015-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-07
        • 2017-10-30
        相关资源
        最近更新 更多