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. search-a-2d-matrix——二维矩阵找数

    题目描述 Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the ...

  2. STL学习笔记(排序算法)

    STL提供了好几种算法对区间内的元素排序.出来完全排序外,还支持局部排序. 对所有元素排序 void sort(RandomAccessIterator beg,RandomAccessIterato ...

  3. 【VBA】设置Excle最近使用文件清单数量

    打开Excle,点击"文件"------"最近使用的文件",如下图: 根据上图可以看到,最近使用的文件数目为11个,那么是怎么实现的呢?具体代码如下: Publ ...

  4. C# 反编译工具

    justdecompile http://down.51cto.com/data/2067031 ILSpy http://www.fishlee.net/soft/ilspy_chs/

  5. 25个经典的Spring面试问答

    1.什么是Spring框架?Spring框架有哪些主要模块? Spring框架是一个为Java应用程序的开发提供了综合.广泛的基础性支持的Java平台.Spring帮助开发者解决了开发中基础性的问题, ...

  6. MYSQL数据插入、更新及删除

    上文讲到创建数据表,本文介绍create table后的数据插入: 一.通过insert into ...values...插入 insert into tablename (column1,colu ...

  7. UITextView 设置边框

        UITextView * txtView = [[UITextView alloc] initWithFrame:CGRectMake(10, 50, 200, 50)];     txtVi ...

  8. c#实现记事本

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  9. 转:使用rsync在linux(服务端)与windows(客户端)之间同步

    转自:http://blog.csdn.net/old_imp/article/details/8826396 一 在linux(我用的是centos系统)上安装rsync和xinetd前先查看lin ...

  10. cdn日志统一下载程序

    最近实现了网宿cdn,阿里云cdn,腾讯cdn的日志统一格式下载程序,使用简单方便,有需要详见代码: https://github.com/mikeluwen/CdnLogDownload