首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >tensorflow中的2层神经网络

tensorflow中的2层神经网络
EN

Stack Overflow用户
提问于 2017-09-04 06:54:31
回答 1查看 235关注 0票数 1

我是tensorflow的新手,并试图训练以下两层网络。它似乎不工作,因为交叉熵不是随着迭代而减少的。我想我把隐藏层和输出层的连接搞砸了。如果你能看到问题,请帮帮我,

代码语言:javascript
复制
import tensorflow as tf
from scipy.io import loadmat
import numpy as np
import sys

x = loadmat('../mnist_data/ex4data1.mat')
X = x['X']

# one hot conversion
y_temp = x['y']
y_temp = np.reshape(y_temp, (len(y_temp),))
y = np.zeros((len(y_temp),10))
y[np.arange(len(y_temp)), y_temp-1] = 1.



input_size = 400
hidden1_size = 25
output_size = 10
num_iters = 50
reg_alpha = 0.05


x = tf.placeholder(tf.float32, [None, input_size], name='data')
W1 = tf.Variable(tf.zeros([hidden1_size, input_size], tf.float32, name='weights_1st_layer'))
b1 = tf.Variable(tf.zeros([hidden1_size], tf.float32), name='bias_layer_1')
W2 = tf.Variable(tf.zeros([output_size, hidden1_size], tf.float32, name='weights_2nd_layer'))
b2 = tf.Variable(tf.zeros([output_size], tf.float32), name='bias_layer_2')


hidden_op = tf.nn.relu(tf.add(tf.matmul(x, W1, transpose_b=True), b1))
output_op = tf.matmul(hidden_op, W2, transpose_b=True) + b2
pred = tf.nn.softmax(output_op) 

y_ = tf.placeholder(tf.float32, [None, 10], name='actual_labels')


cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    labels=y_, logits=output_op))
train_step = tf.train.GradientDescentOptimizer(reg_alpha).minimize(cross_entropy)

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

for _ in range(50):
    print ('training..', _)
    print (sess.run([train_step, cross_entropy], feed_dict={x : X, y_ : y}))

corr_pred = tf.equal(tf.argmax(pred, axis=1), tf.argmax(y_, axis=1))
acc = tf.reduce_mean(tf.cast(corr_pred, tf.float32))
print (sess.run(acc, feed_dict={x:X, y_:y}))
sess.close()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-04 07:12:22

试着把你的重量初始化为随机,而不是零。

因此,与其:

代码语言:javascript
复制
W1 = tf.Variable(tf.zeros([hidden1_size, input_size], tf.float32, name='weights_1st_layer'))
W2 = tf.Variable(tf.zeros([output_size, hidden1_size], tf.float32, name='weights_2nd_layer'))

用途:

代码语言:javascript
复制
W1 = tf.Variable(tf.truncated_normal([hidden1_size, input_size], tf.float32, name='weights_1st_layer'), stddev=0.1))
W2 = tf.Variable(tf.truncated_normal([output_size, hidden1_size], tf.float32, name='weights_2nd_layer'), stddev=0.1))

检查很好的总结,为什么初始化所有权重为零会阻止网络的培训。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46031736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档