TensorFlow基本操作

import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '' # 使用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'] = '' # 基本常量操作
# T构造函数返回的值就是常量节点(Constant op)的输出.
a = tf.constant()
b = tf.constant() # 启动默认的计算图
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: , b: }))
print("变量相乘: %i" % sess.run(mul, feed_dict={a: , b: })) # 矩阵相乘(Matrix Multiplication)
# 创建一个 Constant op ,产生 1x2 matrix.
# 该op会作为一个节点被加入到默认的计算图
# 构造器返回的值 代表了Constant op的输出
matrix1 = tf.constant([[., .]])
# 创建另一个 Constant op 产生 2x1 矩阵.
matrix2 = tf.constant([[.],[.]])
# 创建一个 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)
# ==> [[ .]] #保存计算图
writer = tf.summary.FileWriter(logdir='logs', graph=tf.get_default_graph())
writer.flush()

os.environ['TF_CPP_MIN_LOG_LEVEL'] = ''

这是log日志级别设置

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

a = tf.placeholder(tf.int16)

b = tf.placeholder(tf.int16)

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

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

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

如上面这段代码所示,在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'] = '' # 导入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() # 用于训练(nn candidates)
Xtest, Ytest = mnist.test.next_batch() # 用于测试
print('Xtrain.shape: ', Xtrain.shape, ', Xtest.shape: ',Xtest.shape)
print('Ytrain.shape: ', Ytrain.shape, ', Ytest.shape: ',Ytest.shape) # 计算图输入占位符
xtrain = tf.placeholder("float", [None, ])
xtest = tf.placeholder("float", []) # 使用L1距离进行最近邻计算
# 计算L1距离
distance = tf.reduce_sum(tf.abs(tf.add(xtrain, tf.negative(xtest))), axis=)
# 预测: 获得最小距离的索引 (根据最近邻的类标签进行判断)
pred = tf.arg_min(distance, )
#评估:判断给定的一条测试样本是否预测正确 # 初始化节点
init = tf.global_variables_initializer() #最近邻分类器的准确率
accuracy = . # 启动会话
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 +=
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.

TensorFlow 初级教程(三)的更多相关文章

  1. Tensorflow 初级教程(二)

    一.Tensorflow 扩展功能 1.自动求导 2.子图的执行 3.计算图控制流 4.队列/容器 Tensorflow 自动求导 当计算tensor C关于tensor W的梯度时,会先寻找从W到C ...

  2. Tensorflow 初级教程(一)

    初步介绍 Google 于2011年推出人工深度学习系统——DistBelief.通过DistBelief,Google能够扫描数据中心数以千计的核心,并建立更大的神经网络.Google 的这个系统将 ...

  3. Android初级教程三个Dialog对话框小案例

    这里把三个对话框形式写在一个项目程序里面,用三个按钮控制显示什么样式的对话框. 先看布局文件代码: <LinearLayout xmlns:android="http://schema ...

  4. 密码学初级教程(三)公钥密码RSA

    密码学家工具箱中的6个重要的工具: 对称密码 公钥密码 单向散列函数 消息认证码 数字签名 伪随机数生成器 公钥密码(非对称密码) 问题: 公钥认证问题 处理速度是对称密码的几百分之一 求离散对数非常 ...

  5. Laravel初级教程浅显易懂适合入门

    整理了一些Laravel初级教程,浅显易懂,特适合入门,留给刚学习laravel想快速上手有需要的朋友 最适合入门的laravel初级教程(一)序言 最适合入门的laravel初级教程(二)安装使用 ...

  6. shellKali Linux Web 渗透测试— 初级教程(第三课)

    shellKali Linux Web 渗透测试— 初级教程(第三课) 文/玄魂 目录 shellKali Linux Web 渗透测试—初级教程(第三课) 课程目录 通过google hack寻找测 ...

  7. 黄聪:Microsoft Enterprise Library 5.0 系列教程(三) Validation Application Block (初级)

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(三) Validation Application Block (初级) 企业库提供了一个很强大的验证应用程序模 ...

  8. Android初级教程理论知识(第三章测试&数据存储&界面展现)

    首先介绍单元测试,我在javaweb部分有详细介绍单元测试框架的一篇文章. 可以先看在javaweb中的单元测试详解篇http://blog.csdn.net/qq_32059827/article/ ...

  9. Mac OS X Terminal 101:终端使用初级教程

    Mac OS X Terminal 101:终端使用初级教程 发表于 2012 年 7 月 29 日 由 Renfei Song | 文章目录 1 为什么要使用命令行/如何开启命令行? 2 初识Com ...

随机推荐

  1. iOS学习(项目中遇到的错误1)

    1.[AppModel copyWithZone:]: unrecognized selector sent to instance 0x7ffda9f4cf70 *** Terminating ap ...

  2. mysql常用命令和函数

    一.DROP IF EXISTS DROP FUNCTION IF EXISTS fun;DROP TABLE IF EXISTS table; 二.数据表1.建立表CREATE TABLE test ...

  3. Linux下, Eclipse C/C++ IDE下编辑好C/C++源程序之后要先保存!!!否则,就会……

    注意:Linux下, Eclipse C/C++ IDE下编辑好C/C++源程序之后要先保存! ! ! 然后Project-->Build All/Build Project,再点绿箭头执行.否 ...

  4. java游戏开发之基础

    © 版权声明:本文为博主原创文章,转载请注明出处 游戏图形界面开发基础 AWT:(Abstract Window Toolkit,抽象窗口工具集) AWT中包含图形界面编程的基本类库,是Java语言G ...

  5. 【Hadoop基础教程】4、Hadoop之完全分布式环境搭建

    上一篇blog我们完成了Hadoop伪分布式环境的搭建,伪分布式模式也叫单节点集群模式, NameNode.SecondaryNameNode.DataNode.JobTracker.TaskTrac ...

  6. JavaFX打包到Android上

    让JavaFX执行到移动平台一直是社区努力完毕的事.  当然,眼下已经能够让JavaFX执行到Android和IOS平台了,以下我们来看看怎样打包自己的JavaFX项目到Android平台.  首先下 ...

  7. POI 实现合并单元格以及列自适应宽度

    POI是apache提供的一个读写Excel文档的开源组件,在操作excel时常要合并单元格,合并单元格的方法是: sheet.addMergedRegion(new CellRangeAddress ...

  8. nginx的proxy_pass到$host的问题

    今天在配置一个location的时候,希望使用一个变量如$host来指示nginx代理: location /test/ { proxy_pass http://$host; } 如你想不到,这个配置 ...

  9. 在eclipse创建和myeclipse一样结构的web项目

    之前一直使用myeclipse,现在换成eclipse,但是创建的新项目让我很不习惯,下面这个方法可以解决. 创建好的项目结构如下图所示,不过看着还是很别扭,我们window→show view→ot ...

  10. spring AOP pointcut expression表达式解析

    Pointcut 是指那些方法需要被执行"AOP",是由"Pointcut Expression"来描述的.Pointcut可以有下列方式来定义或者通过& ...