TensorFlow1---------神经网络举例

# 常数
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()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值