Tensorflow 简单 softmax 模型的参数值没有变化
Tensorflow no change in parameter value for a simple softmax model
我正在尝试在我的图像数据上使用 tensorflow 构建一个 softmax 模型,灵感来自 MNIST 示例。当我尝试训练模型时,我发现损失没有减少。我还看到第一次迭代后参数 (W,b) 值没有变化。我是否需要在每次迭代后显式更新我的参数值?
代码:-
######### Model Graph ###################
with tf.device('/cpu:0'):
x = tf.placeholder(tf.float32,shape = [None, IMAGE_HEIGHT, IMAGE_WIDTH, 3])
y_ = tf.placeholder(tf.float32,shape = [None,35])
########### Weight for each softmax sigmod function##############
initialW = tf.truncated_normal([IMAGE_HEIGHT*IMAGE_WIDTH*3, 35], stddev=0.1)
W = tf.Variable(initialW,trainable=True);
b = tf.Variable(tf.zeros([35]),trainable=True)
x_flat = tf.reshape(x, [-1,IMAGE_HEIGHT*IMAGE_WIDTH*3])
y=tf.nn.softmax(tf.matmul(x_flat,W)+b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y+1e-10),reduction_indices=[1]))
cross_entropy = tf.Print(cross_entropy, [cross_entropy], "cost") #print to the console tensorflow
#train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
train_step = tf.train.AdamOptimizer(0.1).minimize(cross_entropy)
#### Model evaluation ######### Evaluating model
is_predicted_correctly = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(is_predicted_correctly,tf.float32))
ops = tf.initialize_all_variables();
### Running graph ###
### Initialzing variable ####
config = tf.ConfigProto()
config.log_device_placement=True
sess = tf.Session(config=config)
sess.run(ops)
###Training####
for it in range(nIterations):
labels, images = d.getNextBatch(nBatchSize)
while(images is not None):
sess.run(train_step, feed_dict = {x: images, y_ : labels})
labels, images = d.getNextBatch(nBatchSize)
成本始终保持相似:
I tensorflow/core/kernels/logging_ops.cc:79] cost[22.211819]
I tensorflow/core/kernels/logging_ops.cc:79] cost[22.095526]
I tensorflow/core/kernels/logging_ops.cc:79] cost[22.676987]
I tensorflow/core/kernels/logging_ops.cc:79] cost[22.563032]
更新:批量大小的代码
def getNextBatch(self,cnt):
if(self.dataSet is None):
return None, None;
if(self.curr>=len(self.dataSet)):
return None, None
end = self.curr+cnt;
if(end>len(self.dataSet)):
end = len(self.dataSet)
batchData = self.dataSet[self.curr:end]
labelRaw = [];
images = [];
for dataPoint in batchData:
try:
image = self.getImageFromPath(dataPoint['image']);
if(not self.isSizeCorrect(image)):
print("Wrong image shape:"+str(image.shape));
raise ValueError("Wrong image shape");
labelRaw.append(dataPoint['label']);
images.append(image);
except (OSError, ValueError):
k=0;
labels = self.onEnc.transform((self.lEnc.transform(labelRaw)).reshape(-1,1))
self.curr = end
return labels, np.array(images)
def getImageFromPath(self,imageFile):
img = misc.imread(imageFile)
resizedImg = misc.imresize(img,(IMAGE_HEIGHT,IMAGE_WIDTH))
return resizedImg;
我终于能够解决我的问题了。问题是我的特征和权重的乘积很大(千分之一)导致 soft-max 中的指数值膨胀(想象一下 e^30000)。
因此,我的梯度始终为零,因此没有更新参数。
我尝试了以下方法来解决这个问题:-
- Normalized my image data(pixel values from 0-to-255 to 0-to-1)
- Initialized parameter vectors with very small values around 10e-3
- Reduced the learning rate of my optimization algorithm.
这导致指数较小且梯度值非零。终于可以训练模型了。
我正在尝试在我的图像数据上使用 tensorflow 构建一个 softmax 模型,灵感来自 MNIST 示例。当我尝试训练模型时,我发现损失没有减少。我还看到第一次迭代后参数 (W,b) 值没有变化。我是否需要在每次迭代后显式更新我的参数值?
代码:-
######### Model Graph ###################
with tf.device('/cpu:0'):
x = tf.placeholder(tf.float32,shape = [None, IMAGE_HEIGHT, IMAGE_WIDTH, 3])
y_ = tf.placeholder(tf.float32,shape = [None,35])
########### Weight for each softmax sigmod function##############
initialW = tf.truncated_normal([IMAGE_HEIGHT*IMAGE_WIDTH*3, 35], stddev=0.1)
W = tf.Variable(initialW,trainable=True);
b = tf.Variable(tf.zeros([35]),trainable=True)
x_flat = tf.reshape(x, [-1,IMAGE_HEIGHT*IMAGE_WIDTH*3])
y=tf.nn.softmax(tf.matmul(x_flat,W)+b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y+1e-10),reduction_indices=[1]))
cross_entropy = tf.Print(cross_entropy, [cross_entropy], "cost") #print to the console tensorflow
#train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
train_step = tf.train.AdamOptimizer(0.1).minimize(cross_entropy)
#### Model evaluation ######### Evaluating model
is_predicted_correctly = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(is_predicted_correctly,tf.float32))
ops = tf.initialize_all_variables();
### Running graph ###
### Initialzing variable ####
config = tf.ConfigProto()
config.log_device_placement=True
sess = tf.Session(config=config)
sess.run(ops)
###Training####
for it in range(nIterations):
labels, images = d.getNextBatch(nBatchSize)
while(images is not None):
sess.run(train_step, feed_dict = {x: images, y_ : labels})
labels, images = d.getNextBatch(nBatchSize)
成本始终保持相似:
I tensorflow/core/kernels/logging_ops.cc:79] cost[22.211819]
I tensorflow/core/kernels/logging_ops.cc:79] cost[22.095526]
I tensorflow/core/kernels/logging_ops.cc:79] cost[22.676987]
I tensorflow/core/kernels/logging_ops.cc:79] cost[22.563032]
更新:批量大小的代码
def getNextBatch(self,cnt):
if(self.dataSet is None):
return None, None;
if(self.curr>=len(self.dataSet)):
return None, None
end = self.curr+cnt;
if(end>len(self.dataSet)):
end = len(self.dataSet)
batchData = self.dataSet[self.curr:end]
labelRaw = [];
images = [];
for dataPoint in batchData:
try:
image = self.getImageFromPath(dataPoint['image']);
if(not self.isSizeCorrect(image)):
print("Wrong image shape:"+str(image.shape));
raise ValueError("Wrong image shape");
labelRaw.append(dataPoint['label']);
images.append(image);
except (OSError, ValueError):
k=0;
labels = self.onEnc.transform((self.lEnc.transform(labelRaw)).reshape(-1,1))
self.curr = end
return labels, np.array(images)
def getImageFromPath(self,imageFile):
img = misc.imread(imageFile)
resizedImg = misc.imresize(img,(IMAGE_HEIGHT,IMAGE_WIDTH))
return resizedImg;
我终于能够解决我的问题了。问题是我的特征和权重的乘积很大(千分之一)导致 soft-max 中的指数值膨胀(想象一下 e^30000)。
因此,我的梯度始终为零,因此没有更新参数。
我尝试了以下方法来解决这个问题:-
- Normalized my image data(pixel values from 0-to-255 to 0-to-1)
- Initialized parameter vectors with very small values around 10e-3
- Reduced the learning rate of my optimization algorithm.
这导致指数较小且梯度值非零。终于可以训练模型了。