Tensorflow学习笔记

Tensorflow学习笔记

  • tf.reshape:
  • tf.matmul:
  • tf.concat:
  • tf.ConfigProto:
  • ret, img = cv2.VideoCapture(path).read()
  • tf.nn.dropout(x, keep_prob, noise_shape, =None, seed=None, name=None):
  • tensorflow.python.tools.inspect_checkpoint
  • tf. Graph().as_default()
  • tf.summary.scalar
  • tensorflow结果可视化
  • 查看模型权重变化 tf.get_default_graph().get_tensor_by_name(name)
  • tf.ConfigProto()
  • os.walk
  • tf.cast
  • list[-5:][::-1]
  • 如何快速读取csv
  • L2 norm

初学tensorflow, 本博客将记录Tensorflow学习过程中一点一滴, 学习的过程讲究效率, 不在于你看了多少, 在于你收获了多少, slow down is speed up. 目前博客中许多内容直接复制与网络, 等我有空后一一按照自己的理解更新.

tf.reshape:

numpy.reshape 将数组改变结构
b=np.reshape(a,(2,-1))
reshape(t, [3, 3]) ==> [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

tensor ‘t’ is [[[1, 1], [2, 2]],
----------------[[3, 3], [4, 4]]]
tensor ‘t’ has shape [2, 2, 2]
reshape(t, [2, 4]) ==> [[1, 1, 2, 2],
[3, 3, 4, 4]]

tf.matmul:

a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) => [[1. 2. 3.]
[4. 5. 6.]]
b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) => [[7. 8.]
[9. 10.]
[11. 12.]]
c = tf.matmul(a, b) => [[58 64]
[139 154]]

tf.concat:

a = tf.constant([[1, 2, 3], [2, 3, 4]])
b = tf.constant([[4, 5, 6], [6, 7, 8]])
c = tf.concat([a,b],0) #0代表纵向,1代表横向
[[1 2 3]
[2 3 4]
[4 5 6]
[6 7 8]]

tf.ConfigProto:

一般用在创建session的时候。用来对session进行参数配置

with tf.Session(config = tf.ConfigProto(…),…)
#tf.ConfigProto()的参数
log_device_placement=True : 是否打印设备分配日志
allow_soft_placement=True : 如果你指定的设备不存在,允许TF自动分配设备
tf.ConfigProto(log_device_placement=True,allow_soft_placement=True)

Mini-batch梯度下降法
相对于随机梯度下降,Mini-batch梯度下降降低了收敛波动性,即降低了参数更新的方差,使得更新更加稳定。相对于全量梯度下降,其提高了每次学习的速度。并且其不用担心内存瓶颈从而可以利用矩阵运算进行高效计算。一般而言每次更新随机选择[50,256]个样本进行学习,但是也要根据具体问题而选择,实践中可以进行多次试验,选择一个更新速度与更次次数都较适合的样本数。mini-batch梯度下降可以保证收敛性,常用于神经网络中。

ret, img = cv2.VideoCapture(path).read()

第一个参数ret 为True 或者False,代表有没有读取到图片

第二个参数frame表示截取到一帧的图片

tf.nn.dropout(x, keep_prob, noise_shape, =None, seed=None, name=None):

dropout实际上是为了防止大型网络(小型网络可能不适用)过拟合,将大约(1-keep_prob)的参数变为0,并将不为0的元素乘以1/ keep_prob倍.

tensorflow.python.tools.inspect_checkpoint

打印tenorflow模型中所有tensor的变量名和值
import tensorflow as tf
from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file
latest_ckp = tf.train.latest_checkpoint(’./’)
print_tensors_in_checkpoint_file(latest_ckp, all_tensors=True, tensor_name=’’)

tf. Graph().as_default()

tf.Graph() 表示实例化了一个类,一个用于 tensorflow 计算和表示用的数据流图,通俗来讲就是:在代码中添加的操作(画中的结点)和数据(画中的线条)都是画在纸上的“画”,而图就是呈现这些画的纸,你可以利用很多线程生成很多张图,但是默认图就只有一张。

tf.Graph().as_default() 表示将这个类实例,也就是新生成的图作为整个 tensorflow 运行环境的默认图,如果只有一个主线程不写也没有关系,tensorflow 里面已经存好了一张默认图,可以使用tf.get_default_graph() 来调用(显示这张默认纸),当你有多个线程就可以创造多个tf.Graph(),就是你可以有一个画图本,有很多张图纸,这时候就会有一个默认图的概念了。

tf.summary.scalar

1.对标量数据汇总和记录使用tf.summary.scalar,函数格式如下:
tf.summary.scalar(tags, values, collections=None, name=None)
一般在画loss,accuary时会用到这个函数。

tensorflow结果可视化

(1)运行整个程序,在程序中定义的summary node就会将要记录的信息全部保存在指定的logdir路径中了,训练的记录会存一份文件,测试的记录会存一份文件。
(2)进入linux命令行,运行以下代码,等号后面加上summary日志保存的路径(在程序第一步中就事先自定义了)
tensorboard --logdir=
执行命令之后会出现一条信息,上面有网址,将网址在浏览器中打开就可以看到我们定义的可视化信息了。:
Starting TensorBoard 41 on port 6006
(You can navigate to http://127.0.1.1:6006)
将http://127.0.1.1:6006在浏览器中打开,成功的话如下:

查看模型权重变化 tf.get_default_graph().get_tensor_by_name(name)

name为权重名, 能够通过tensorflow.python.tools.inspect_checkpoint查得. 在sess中运行该行代码既能将name的值输出, 为了更好的可视化可以将各个权重的差值做一个表格或图像, 等之后有空了贴出代码.
该方法能够创建一个node, 用session在每一轮计算中将其输出即可. For example:

import tensorflow as tf
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d, name='example')
with tf.Session() as sess:
    test =  sess.run(e)
    print e.name #example:0
    test = tf.get_default_graph().get_tensor_by_name("example:0")
    print test #Tensor("example:0", shape=(2, 2), dtype=float32)

tf.ConfigProto()

tf.ConfigProto()函数用在创建session的时候,用来对session进行参数配置:
config = tf.ConfigProto(allow_soft_placement=True, allow_soft_placement=True)
config.gpu_options.per_process_gpu_memory_fraction = 0.4 #占用40%显存
sess = tf.Session(config=config)

  1. 记录设备指派情况:tf.ConfigProto(log_device_placement=True)

设置tf.ConfigProto()中参数log_device_placement = True ,可以获取到 operations 和 Tensor 被指派到哪个设备(几号CPU或几号GPU)上运行,会在终端打印出各项操作是在哪个设备上运行的。

  1. 自动选择运行设备 : tf.ConfigProto(allow_soft_placement=True)

在tf中,通过命令 “with tf.device(’/cpu:0’):”,允许手动设置操作运行的设备。如果手动设置的设备不存在或者不可用,就会导致tf程序等待或异常,为了防止这种情况,可以设置tf.ConfigProto()中参数allow_soft_placement=True,允许tf自动选择一个存在并且可用的设备来运行操作。

  1. 限制GPU资源使用:

为了加快运行效率,TensorFlow在初始化时会尝试分配所有可用的GPU显存资源给自己,这在多人使用的服务器上工作就会导致GPU占用,别人无法使用GPU工作的情况。
tf提供了两种控制GPU资源使用的方法,一是让TensorFlow在运行过程中动态申请显存,需要多少就申请多少;第二种方式就是限制GPU的使用率。
一、动态申请显存

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
二、限制GPU使用率

config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.4 #占用40%显存
session = tf.Session(config=config)
或者

gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.4)
config=tf.ConfigProto(gpu_options=gpu_options)
session = tf.Session(config=config)
4.设置使用哪块GPU
方法一、在python程序中设置:

#在程序开头
os.environ[‘CUDA_VISIBLE_DEVICES’] = ‘0’ #使用 GPU 0
os.environ[‘CUDA_VISIBLE_DEVICES’] = ‘0,1’ # 使用 GPU 0,1
方法二、在执行python程序时候:

CUDA_VISIBLE_DEVICE=0,1 python yourcode.py

推荐使用更灵活一点的第二种方法。

os.walk

walk()方法语法格式如下:
os.walk(top[, topdown=True[, οnerrοr=None[, followlinks=False]]])
参数
top – 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)。
root 所指的是当前正在遍历的这个文件夹的本身的地址
dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
topdown --可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果 topdown 参数为 True,walk 会遍历top文件夹,与top 文件夹中每一个子目录。
onerror – 可选, 需要一个 callable 对象,当 walk 需要异常时,会调用。
followlinks – 可选, 如果为 True,则会遍历目录下的快捷方式(linux 下是 symbolic link)实际所指的目录(默认关闭)。

import os
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))

tf.cast

tf.cast:用于改变某个张量的数据类型
例如:
import tensorflow as tf;
import numpy as np;

A = tf.convert_to_tensor(np.array([[1,1,2,4], [3,4,8,5]]))

with tf.Session() as sess:
print A.dtype
b = tf.cast(A, tf.float32)
print b.dtype输出:

list[-5:][::-1]

[-5:] 表示list中倒数第五个数到最后一个数;
[::-1] 表示倒序

如何快速读取csv

import pandas as pd
data = pd.read_csv('path')

L2 norm

The L2 norm is known to be prone to large estimation error if there are outliers in the training sample.

It is also well known that other norms lead to much more robust estimators. One of such distance metrics is the L1 -norm

你可能感兴趣的:(学习笔记)