# 常数
b = tf.constant(1.0)
# 变量
value = tf.Variable(0, name="value")
# 占位符
x = tf.placeholder(tf.float32,[1],name='x')
# 取回图内数据
import tensorflow as tf
with tf.Session() as sess:
x = tf.placeholder(tf.float32,[1],name='x')
y = tf.placeholder(tf.float32,[1],name='y')
z = tf.constant(1.0)
y = x * z
x_in = [100]
x, y_output, z = sess.run([x ,y, z], {x:x_in}) # 取回图内数据
print(x, y_output, z)
## [100.] [100.] 1.0
# 神经网络形状:(特征数*none)=(shape[1],) ;与数组(样本*特征)相反
## 激活函数
### sigmoid分类器(二分类)
Y1 = tf.nn.sigmoid(tf.matmul(XX,W1)+B1)
### softmax分类器
Y1 = tf.nn.softmax(tf.matmul(XX,W1)+B1)
### ReLU分类器
Y1 = tf.nn.relu(tf.matmul(XX,W1)+B1)
### dropout优化
droppout_ratio = tf.placeholder(tf.float32)
Y1 = tf.nn.relu(tf.matmul(XX,W1)+B1)
Y1d = tf.nn.dropout(Y1, dropout_ratio)
### 卷积与最大池化
conv1 = tf.nn.conv2d(X, w, strides=[1,1,1,1], padding='SAME') # SAME表示输入图像边界被0填充,以保证输出大小一致
conv1 = tf.nn.relu(conv1)
### 最大池化
conv1 = tf.nn.max_pool(conv1, ksize=[1,2,2,1], strides = [1,2,2,1], padding = 'SAME')
conv1 = tf.nn.dropout(conv1, p_keep_conv)
# 保存模型
save = tf.train.Saver()
save_path = saver.save(sess,"soft_mnist")
print("model saved to %s" % save_path)
# 还原模型
import matplotlib.pyplot as plt
import tensorflow as tf
import input_data
import numpy as np
import mnist_data
# 添加MNIST数据集
mnist = mnist_data.read_data_sets('data',one_hot=True)
# 实现迭代窗口
sess = tf.InteractiveSession()
# 导入保存的计算图元数据,包含模型的所有拓扑结构及相应变量
new_saver = tf.train.import_meta_graph('softmax_mnist.ckpt.meta')
# 导入检验点文件,包含训练过程中的权重值
new_saver.restore(sess, 'softmax_mnist.ckpt')
#若要运行已载入的模型,需要计算图
tf.get_default_graph()
# 返回当前线程中所用的默认图
tf.get_default_graph().as_graph_def()
# 定义x和y_conv变量,并将它们和我们需要处理的节点相连,以实现网络的输出
x = sess.graph.get_tensor_by_name('input:0')
y_conv = sess.graph.get_tensor_by_name('output:0')
# 为测试保存模型,从mnist数据库中取一个图像
imae_b = mnist.test.image[100]
# 在选定的输入上运行保存的模型
result = sess.run(y_conv, feed_dict={x:image_b})
print(result) # 每一个数字对应的概率
print(sess.run(tf.argmax(result,1))) # 预测的数字
# 展示图片
plt.imshow(image_b.reshape([28,28], cmap='Greys'))
plt.show()