TensorFlow 初级教程(三)

TensorFlow基本操作

import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 使用TensorFlow输出Hello

# 创建一个常量操作( Constant op )
# 这个 op 会被作为一个节点( node )添加到默认计算图上.
#
# 该构造函数返回的值就是常量节点(Constant op)的输出.
hello = tf.constant('Hello, TensorFlow!')

# 启动TensorFlow会话
sess = tf.Session()


# 运行 hello 节点
print(sess.run(hello))
'''
TensorFlow library 的基本操作.
'''
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 基本常量操作
# T构造函数返回的值就是常量节点(Constant op)的输出.
a = tf.constant(2)
b = tf.constant(3)

# 启动默认的计算图
with tf.Session() as sess:
    print("a=2, b=3")
    print("常量节点相加: %i" % sess.run(a+b))
    print("常量节点相乘: %i" % sess.run(a*b))

# 使用变量(variable)作为计算图的输入
# 构造函数返回的值代表了Variable op的输出 (session运行的时候,为session提供输入)
# tf Graph input
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)

# 定义一些操作
add = tf.add(a, b)
mul = tf.multiply(a, b)

# 启动默认会话
with tf.Session() as sess:
    # 把运行每一个操作,把变量输入进去
    print("变量相加: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
    print("变量相乘: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))


# 矩阵相乘(Matrix Multiplication)
# 创建一个 Constant op ,产生 1x2 matrix.
# 该op会作为一个节点被加入到默认的计算图
# 构造器返回的值 代表了Constant op的输出
matrix1 = tf.constant([[3., 3.]])
# 创建另一个 Constant op 产生  2x1 矩阵.
matrix2 = tf.constant([[2.],[2.]])
# 创建一个 Matmul op 以 'matrix1''matrix2' 作为输入.
# 返回的值, 'product', 表达了矩阵相乘的结果
product = tf.matmul(matrix1, matrix2)
# 为了运行 matmul op 我们调用 session 的 'run()' 方法, 传入 'product'
# ‘product’表达了 matmul op的输出. 这表明我们想要取回(fetch back)matmul op的输出
# op 需要的所有输入都会由session自动运行. 某些过程可以自动并行执行
#
# 调用 'run(product)' 就会引起计算图上三个节点的执行:2个 constants 和一个 matmul.
# ‘product’op 的输出会返回到 'result':一个 numpy `ndarray` 对象.
with tf.Session() as sess:
    result = sess.run(product)
    print('矩阵相乘的结果:', result)
    # ==> [[ 12.]]

#保存计算图
writer = tf.summary.FileWriter(logdir='logs', graph=tf.get_default_graph())
writer.flush()

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

这是log日志级别设置

import os  
os.environ["TF_CPP_MIN_LOG_LEVEL"]='1' # 这是默认的显示等级,显示所有信息  
os.environ["TF_CPP_MIN_LOG_LEVEL"]='2' # 只显示 warning 和 Error   
os.environ["TF_CPP_MIN_LOG_LEVEL"]='3' # 只显示 Error

a = tf.placeholder(tf.int16)

b = tf.placeholder(tf.int16)

这里a,b是作变量处理。tf.placeholder()是占位符,会要求指定变量类型(相当于预先定义),之后会把值传入进去。

print("变量相加: %i" % sess.run(add, feed_dict={a: 2, b: 3}))

print("变量相乘: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))

如上面这段代码所示,在tf.Session.run()中使用feed_dict来传入tensor.feed_dict也可以同时传入多个tensor。

思考:tf.placehold()和tf.Variable()有什么区别呢?

tf.Variable适合一些需要初始化或被训练而变化的权重或参数,而tf.placeholder适合通常不会改变的被训练的数据集。


Variable:主要是用于训练变量之类的。比如我们经常使用的网络权重,偏置。
值得注意的是Variable在声明是必须赋予初始值。在训练过程中该值很可能会进行不断的加减操作变化。
名称的真实含义,在于变量,也即在真实训练时,其值是会改变的,自然事先需要指定初始值;
placeholder:也是用于存储数据,但是主要用于feed_dict的配合,接收输入数据用于训练模型等。placeholder值在训练过程中会不断地被赋予新的值,用于批训练,基本上其值是不会轻易进行加减操作。

placeholder在命名时是不会需要赋予值得,其被赋予值得时间实在feed_dict时。其命名的原因所在,仅仅作为一种占位符;

tf.placeholder(dtype, shape=None, name=None)

此函数可以理解为形参,用于定义过程,在执行的时候再赋具体的值

参数:
dtype:数据类型。常用的是tf.float32,tf.float64等数值类型
shape:数据形状。默认是None,就是一维值,也可以是多维,比如[2,3], [None, 3]表示列是3,行不定
name:名称。

参考文献:http://blog.csdn.net/hhtnan/article/details/78990618


product = tf.matmul(matrix1, matrix2)

为了运行 matmul op 我们调用 session 的 'run()' 方法, 传入 'product' # ‘product’表达了 matmul op的输出. 这表明我们想要取回(fetch back)matmul op的输出。op 需要的所有输入都会由session自动运行. 某些过程可以自动并行执行。调用 'run(product)' 就会引起计算图上三个节点的执行:2个 constants 和一个 matmul。 ‘product’op 的输出会返回到 'result':一个 numpy `ndarray` 对象.

 

 

保存计算图

writer = tf.summary.FileWriter(logdir='logs', graph=tf.get_default_graph())

writer.flush()#强制写入

将你的event存储在logs_dir中,然后在terminal中输入tensorboard --logdir=logs_dir 打开tensorboard

 

Tensorflow实现K近邻分类器

import numpy as np
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 导入MNIST数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("mnist_data/", one_hot=True)

# 我们对MNIST数据集做一个数量限制,
Xtrain, Ytrain = mnist.train.next_batch(5000) #5000 用于训练(nn candidates)
Xtest, Ytest = mnist.test.next_batch(200) #200 用于测试
print('Xtrain.shape: ', Xtrain.shape, ', Xtest.shape: ',Xtest.shape)
print('Ytrain.shape: ', Ytrain.shape, ', Ytest.shape: ',Ytest.shape)

# 计算图输入占位符
xtrain = tf.placeholder("float", [None, 784])
xtest = tf.placeholder("float", [784])

# 使用L1距离进行最近邻计算
# 计算L1距离
distance = tf.reduce_sum(tf.abs(tf.add(xtrain, tf.negative(xtest))), axis=1)
# 预测: 获得最小距离的索引 (根据最近邻的类标签进行判断)
pred = tf.arg_min(distance, 0)
#评估:判断给定的一条测试样本是否预测正确

# 初始化节点
init = tf.global_variables_initializer()

#最近邻分类器的准确率
accuracy = 0.

# 启动会话
with tf.Session() as sess:
    sess.run(init)
    Ntest = len(Xtest)  #测试样本的数量
    # 在测试集上进行循环
    for i in range(Ntest):
        # 获取当前测试样本的最近邻
        nn_index = sess.run(pred, feed_dict={xtrain: Xtrain, xtest: Xtest[i, :]})
        # 获得最近邻预测标签,然后与真实的类标签比较
        pred_class_label = np.argmax(Ytrain[nn_index])
        true_class_label = np.argmax(Ytest[i])
        print("Test", i, "Predicted Class Label:", pred_class_label,
              "True Class Label:", true_class_label)
        # 计算准确率
        if pred_class_label == true_class_label:
            accuracy += 1
    print("Done!")
    accuracy /= Ntest
    print("Accuracy:", accuracy)

 

tf.reduce_sum()

官方给的api

reduce_sum(
    input_tensor,
    axis=None,
    keep_dims=False,
    name=None,
    reduction_indices=None
)

input_tensor:表示输入
axis:表示在那个维度进行sum操作。当axis=0表示按列相加,当axis=1表示按行相加
keep_dims:表示是否保留原始数据的维度,False相当于执行完后原始数据就会少一个维度。
reduction_indices:为了跟旧版本的兼容,现在已经不使用了。

 

tf.arg_min

官方api

tf.argmin
argmin(
    input,
    axis=None,
    name=None,
    dimension=None,
    output_type=tf.int64
)

Returns the index with the smallest value across axes of a tensor. (deprecated arguments)
返回在所给轴(axis)上最小值的索引
SOME ARGUMENTS ARE DEPRECATED. They will be removed in a future version. Instructions for updating: Use the axis argument instead Note that in case of ties the identity of the return value is not guaranteed.
有一些是过时的。他们将在未来的版本中删除。说明:使用轴参数代替注意的返回值的身份是没有保证的情况下。

参考文献:http://blog.csdn.net/NockinOnHeavensDoor/article/details/78853142

np.argmin

numpy.argmax(a, axis=None, out=None)[source]           Returns the indices of the maximum values along an axis.

Parameters:

       a : array_like

             Input array.

       axis : int, optional

          By default, the index is into the flattened array, otherwise along the specified axis.

       out : array, optional

        If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.

Returns:

       index_array : ndarray of ints

       Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

posted @ 2018-01-10 11:41  彼岸花杀是条狗  阅读(473)  评论(0编辑  收藏  举报