AllenOR灵感 发表于5个月前

• 发表于 5个月前
• 阅读 0
• 收藏 0
• 评论 0

``````# 定义输入层到隐藏层之间的连接矩阵
w_layer_1 = init_weights([784, 625])

# 定义隐藏层到输出层之间的连接矩阵
w_layer_2 = init_weights([625, 10])

def model(X, w_layer_1, w_layer_2):
# 我们采用 sigmoid 函数来作为激活函数
h = tf.nn.sigmoid(tf.matmul(X, w_layer_1))
return tf.matmul(h, w_layer_2)``````

``````# 训练模型，我们计算交叉熵的平均值和采用梯度下降法来训练
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(py_x, Y))
learning_rate = 0.01

``````#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
import tensorflow as tf
import input_data

def init_weights(shape):
return tf.Variable(tf.random_normal(shape, stddev = 0.01))

def model(X, w_layer_1, w_layer_2):

# 我们采用 sigmoid 函数来作为激活函数
h = tf.nn.sigmoid(tf.matmul(X, w_layer_1))
return tf.matmul(h, w_layer_2)

# 导入数据
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels

X = tf.placeholder("float", [None, 784])
Y = tf.placeholder("float", [None, 10])

# 定义输入层到隐藏层之间的连接矩阵
w_layer_1 = init_weights([784, 625])

# 定义隐藏层到输出层之间的连接矩阵
w_layer_2 = init_weights([625, 10])

# 搭建模型
py_x = model(X, w_layer_1, w_layer_2)

# 训练模型，我们计算交叉熵的平均值和采用梯度下降法来训练
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(py_x, Y))
learning_rate = 0.01
predict_op = tf.argmax(py_x, 1)

with tf.Session() as sess:

init = tf.initialize_all_variables()
sess.run(init)

for i in xrange(100):
for start, end in zip(range(0, len(trX), 128), range(128, len(trX), 128)):
sess.run(train_op, feed_dict = {X: trX[start:end], Y: trY[start:end]})
print i, np.mean(np.argmax(teY, axis = 1) == sess.run(predict_op, feed_dict = {X: teX, Y: teY}))``````

×