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多线程操作(四)—— GCD核心概念

    GCD全称Grand Central Dispatch.可译为"大派发中枢调度器",以纯C语言写成,提供了很多很强大的函数.GCD是苹果公司为多核的并行运算提出的解决方式,它能够自 ...

  2. Spring 应用外部属性文件 配置 context 错误

    在Spring配置文件中出现通配符的匹配很全面, 但无法找到元素 'context:property-placeholder' 的声明这个错误,其实主要是我们在引入命名空间时没有正确引入它的DTD解析 ...

  3. Cookie-Parser是怎样解析签名后的cookie的(同一时候对cookie和cookie-signature进行说明)

    第一步:我们来学习一下cookie-signature: var cookie=require('./index'); var val = cookie.sign('hello', 'tobiisco ...

  4. jsp页面用java代码取随机数

    <%int seconds = (int) (System.currentTimeMillis() / 1000); %> 然后在需要随机数的地方加上下面的代码: <input na ...

  5. Atitit.业务系统的新特性 开发平台 新特性的来源总结

    Atitit.业务系统的新特性 开发平台 新特性的来源总结 1.1. 语言新特性(java c# php js python lisp c++ oc swift ruby  go dart1 1.2. ...

  6. freemarker在xml文件中遍历list数据

    delete   from pub_channelpackage   where channelcode = :channelcode   and channeltype = :channeltype ...

  7. iOS 获取LaunchImage启动图

    iOS开发中,LaunchImage图片会根据手机机型的不同,自动匹配对应的图片,而我们如果想要拿到对应的图片,无法直接通过图片的名字获取该启动图,而需要通过以下方式 + (NSString *)ge ...

  8. VS2012删除选项卡菜单中的"关闭所有文档"

    delete the "close all documents" item of tab menu in vs2012 Tools -> Customize -> Co ...

  9. nl 命令

    nl命令在linux系统中用来计算文件中行号.nl 可以将输出的文件内容自动的加上行号!其默认的结果与 cat -n 有点不太一样, nl 可以将行号做比较多的显示设计,包括位数与是否自动补齐 0 等 ...

  10. delphi 无边框窗体常见问题

    实现无边框窗体很简单,直接将窗体的BorderStyle属性设置为bsNone即可.但是这样会引起2个问题: 1.在xp系统下,任务栏鼠标右键点击无法弹出菜单 解决办法:在FormShow中加入这个过 ...