tensorflow
来源:互联网 发布:网络品牌塑造策略 编辑:程序博客网 时间:2024/05/19 22:24
https://pypi.python.org/pypi/tensorflow
install tensorflow in ubuntu14.04
first install anaconda, then input:
conda install tensorflow
done
http://blog.csdn.net/u014114990/article/details/51125776
多通道(比如RGB三通道)卷积过程:
一般介绍卷积过程好像是对 一个通道的图像进行卷积, 比如10个卷积核,得到10个feature map, 那么输入图像为RGB三个通道呢, 输出的个数依然是 卷积核的个数。
同一个卷积核在每一个通道上的卷积结果相加然后再取激活函数值得到的
http://blog.csdn.net/u014595019/article/details/52759104 介绍了一些基础的概念
self._new_lr = tf.placeholder( tf.float32, shape=[], name="new_learning_rate") self._lr_update = tf.assign(self._lr, self._new_lr) def assign_lr(self, session, lr_value): session.run(self._lr_update, feed_dict={self._new_lr: lr_value})
session.run(self._lr_update, feed_dict={self._new_lr: lr_value})
运行时self._new_lr这个张量会先被填充成lr_value里的值
tf.nn.softmax(Aout2dim): 输出和和输入shape相同。
tf.nn.softmax_cross_entropy_with_logits
self.loss = tf.nn.softmax_cross_entropy_with_logits(z, self.target)
假如z的shape是[batchSize, sampleDim], self.target的shape和z要相同,且target的每一行里只能有一个为1,表示真实的标签的位置;其他都为0。
则函数输出的shape为(batchSize,), 即loss里的每个元素代表一个训练样本的Cross-entropy值。
这个函数执行了softmax和entropy两个操作
with tf.name_scope("output"): W = tf.get_variable( "W", shape=[num_filters_total, num_classes], initializer=tf.contrib.layers.xavier_initializer() ) b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b") l2_loss += tf.nn.l2_loss(W) l2_loss += tf.nn.l2_loss(b) #tf.nn.xw_plus_b is a convenience wrapper to perform the #Wx + b matrix multiplication self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores") self.predictions = tf.argmax(self.scores, 1, name="predictions")# CalculateMean cross-entropy losswith tf.name_scope("loss"): losses = tf.nn.softmax_cross_entropy_with_logits(self.scores, self.input_y) self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss
self.scores的shape为[batch, num_classes],每一行的每个元素代表取指定输出类的概率,这里还没有归一化,也就是说一行里的所有值相加不等于1,要经过softmax操作后才等于1。
self.predictions是一个列表,shape为[batch,],记录每一行里的最大值所对应的index
input_y的shape为[batch,num_classes],每一行里只要一个1
losses的shape为一个列表[batch,],tf.reduce_mean(losses)为对列表求和取平均.
tf.nn.l2_loss(W): Computes half the L2 norm of a tensor without the sqrt
:output = sum(W** 2) / 2. 也就是求W矩阵中的每个元素的2次方相加后除以2
tf.argmax
x = tf.constant([[1,2,3,4],[4,3,2,1]]) predictions = tf.argmax(x, 0, name="predictions") sess = tf.Session() result = sess.run(predictions) print(result)
输出:[1 1 0 0]
tf.argmax输出的是指定维度上最大值所对应的索引,也就是预测值对应的索引。
下面的东西转载自:http://blog.csdn.net/toormi/article/details/53609245
基本概念
使用TensorFlow前必须明白的基本概念:
图(Graph):图描述了计算的过程,TensorFlow使用图来表示计算任务。
张量(Tensor):TensorFlow使用tensor表示数据。每个Tensor是一个类型化的多维数组。
操作(op):图中的节点被称为op(opearation的缩写),一个op获得0个或多个Tensor,执行计算,产生0个或多个Tensor。
会话(Session):图必须在称之为“会话”的上下文中执行。会话将图的op分发到诸如CPU或GPU之类的设备上执行。
变量(Variable):运行过程中可以被改变,用于维护状态。
计算图(The computation graph)
Tensorflow程序通常被组织成一个构建阶段和一个执行阶段。在构建阶段,op的执行步骤被描述成一个图。在执行阶段,使用会话执行图中的op。
构建图
构建图的第一步是创建源op(sources op)。源op不需要任何输入,例如常量(Constant)。源op的输出张量被传递给其他op做运算。
op构造器的返回值代表这个op的输出张量。这些返回值可以作为输入传递给其他op构造器。
TensorFlow的Python库中包含了一个默认的graph,可以在上面添加节点。如果你的程序需要多个graph那就需要使用Graph类管理多个graph。
import tensorflow as tf# 创建一个常量 op, 产生一个 1x2 矩阵. 这个 op 被作为一个节点# 加到默认图中.## 构造器的返回值代表该常量 op 的返回值.matrix1 = tf.constant([[3., 3.]])# 创建另外一个常量 op, 产生一个 2x1 矩阵.matrix2 = tf.constant([[2.],[2.]])# 创建一个矩阵乘法 matmul op , 把 'matrix1' 和 'matrix2' 作为输入.# 返回值 'product' 代表矩阵乘法的结果.product = tf.matmul(matrix1, matrix2)
默认图中包含了3个OP节点:两个constant() op和一个matmul() op。为了真正的执行矩阵相乘运算,并得到矩阵乘法的结果,你必须在会话中启动这个图。
启动图
构造阶段完成后,才能在会话中启动图。启动图的第一步是创建一个Session对象。如果没有任何参数,会话构造器将启动默认图。
# 启动默认图.sess = tf.Session()# 调用 sess 的 'run()' 方法来执行矩阵乘法 op, 传入 'product' 作为该方法的参数.# 上面提到, 'product' 代表了矩阵乘法 op 的输出, 传入它是向方法表明, 我们希望取回# 矩阵乘法 op 的输出.## 整个执行过程是自动化的, 会话负责传递 op 所需的全部输入. op 通常是并发执行的.## 函数调用 'run(product)' 触发了图中三个 op (两个常量 op 和一个矩阵乘法 op) 的执行.## 返回值 'result' 是一个 numpy `ndarray` 对象.result = sess.run(product)print result# ==> [[ 12.]]# 任务完成, 关闭会话.sess.close()
Session对象在使用完成或需要关闭以释放资源。除了明确调用close外,也可以使用“with”代码块来自动完成关闭动作。
with tf.Session() as sess:result = sess.run([product])print result
Tensor
Tensorflow使用tensor数据结构来代表所有的数据。计算图的操作之间仅能传递tensor。你可以把tensor当作多维数组或列表。每一个tensor包含有一个类型成员,一个rank和一个shape。想了解更多TensorFlow是如何操作这些概念的,参考Rank, Shape, and Type
变量
变量维持图计算过程中的状态信息。下面的例子演示了如何使用变量作为一个简单的计数器。
# Create a Variable, that will be initialized to the scalar value 0.state = tf.Variable(0, name="counter")# Create an Op to add one to `state`.one = tf.constant(1)new_value = tf.add(state, one)update = tf.assign(state, new_value)# Variables must be initialized by running an `init` Op after having# launched the graph. We first have to add the `init` Op to the graph.init_op = tf.global_variables_initializer()# Launch the graph and run the ops.with tf.Session() as sess:# Run the 'init' opsess.run(init_op)# Print the initial value of 'state'print(sess.run(state))# Run the op that updates 'state' and print 'state'.for _ in range(3):sess.run(update)print(sess.run(state))# output:# 0# 1# 2# 3
通常可以将一个统计模型中的参数表示为一组变量。例如,你可以将一个神经网络的权重当作一个tensor存储在变量中。在训练图的重复运行过程中去更新这个tensor。
Fetch
为了取回操作里多个OP的输出内容,在使用Session对象的run()方法执行图时,传入这些OP的输出tensor,这些tensor会帮你取回结果。之前的例子中,我们只取回了state节点,但是你也可以取回多个tensor:
input1 = tf.constant(3.0)input2 = tf.constant(2.0)input3 = tf.constant(5.0)intermed = tf.add(input2, input3)mul = tf.mul(input1, intermed)with tf.Session():result = sess.run([mul, intermed])print result# 输出:# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]
需要获取的多个 tensor 值,在 op 的一次运行中一起获得(而不是逐个去获取 tensor)。
Feed
上面的例子中展示了在计算图中引入tensor,以常量和变量的形式存储。TensorFlow还提供了feed机制,该机制可以临时替换图中的tensor。
feed使用一个tensor值临时替换一个操作的输出。可以把feed数据作为参数提供给run()方法。标记的方法是使用tf.placeholder()为这些操作创建占位符。
input1 = tf.placeholder(tf.types.float32)input2 = tf.placeholder(tf.types.float32)output = tf.mul(input1, input2)with tf.Session() as sess:print sess.run([output], feed_dict={input1:[7.], input2:[2.]})# 输出:# [array([ 14.], dtype=float32)]
tf.expand_dims(Tensor, dim)
使张量在指定的位置增加一维,这一多出来的维度的size维1
import tensorflow as tffrom numpy import *sess = tf.InteractiveSession()labels = [1,2,3]x = tf.expand_dims(labels, 1)y=sess.run(x)print(sess.run(x))print(y.shape)输出[[1] [2] [3]](3, 1)----------import tensorflow as tffrom numpy import *sess = tf.InteractiveSession()labels = [[1,2,3],[1,2,3]]x = tf.expand_dims(labels, 0)y=sess.run(x)print(sess.run(x))print(y.shape)输出:[[[1 2 3] [1 2 3]]](1, 2, 3)----------import tensorflow as tffrom numpy import *sess = tf.InteractiveSession()labels = [[1,2,3],[1,2,3]]x = tf.expand_dims(labels, 1)y=sess.run(x)print(sess.run(x))print(y.shape)输出:[[[1 2 3]] [[1 2 3]]](2, 1, 3)----------import tensorflow as tffrom numpy import *sess = tf.InteractiveSession()labels = [[1,2,3],[1,2,3]]x = tf.expand_dims(labels, -1)y=sess.run(x)print(sess.run(x))print(y.shape)输出:[[[1] [2] [3]] [[1] [2] [3]]](2, 3, 1)
tf.matmul
tf.matmul(output, softmax_w)output的shape为[batch_size, size]softmax_w的shape为[size, vocab_size]output的第二维的大小和softmax_w第一维的大小相同。得出的结果的shape为[batch_size, vocab_size]
tf.nn.conv2d
在 [http://stackoverflow.com/questions/34619177/what-does-tf-nn-conv2d-do-in-tensorflow](conv)有一个很好的解释filter_shape = [filter_size, embedding_size, 1, num_filters]W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")conv = tf.nn.conv2d( self.embedded_chars_expanded, W, strides=[1, 1, 1, 1], padding="VALID", name="conv")#b长度和conv最后一维的长度要相同,即和filter的个数相同h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
各参数的解释如下
1、self.embedded_chars_expanded是卷积网络的输入,是句子通过embeding矩阵后得到的,其shape为:
[batch, inputHeight, inputWidth, in_channels]
2、W为卷积map,in_channels为输入channel的数量,output_channels为卷积核的个数。W的shape为:[filter_height , filter_width, in_channels, output_channels]
计算时将w 变为[filter_height * filter_width,* in_channels, output_channels],然后从输入中每次选取一个patch,这个patch里有filter_height * filter_width,* in_channels个元素,将patch和w做element wise相乘再相加就得到最终的结果,
3、strides=[1, 1, 1, 1]滑动窗口时在input的四个维度上的步长。一般strides[0]=strides[3]=1,why?
4、padding=”VALID”表示对输入不填充
输出的shape为:
[batch,inputHeight-filter_height+1, inputWidth-filter_width+1, output_channels]
tf.nn.max_pool
pooled = tf.nn.max_pool( h, ksize=[1, sequence_length - filter_size + 1, 1, 1], strides=[1, 1, 1, 1], padding='VALID', name="pool")pooled_outputs.append(pooled)
各参数的解释:
1、h为输入,shape为[batch,height,width,channel]
2、ksize为MAX poll操作窗口在input各维度上的大小,一般第一和第四维都是1,第二维为窗口的高度,第三维为窗口的宽度
3、strides=[1, 1, 1, 1]滑动窗口时在input的四个维度上的步长
4、padding=”VALID”表示对输入不填充
输出shape
[batch,inputHeight-filter_height+1, inputWidth-filter_width+1, output_channels]
tf.concat
self.h_pool = tf.concat(3, pooled_outputs)
pooled_outputs是一个列表,列表里的每个元素为一个四维矩阵,这个操作表示将列表里的元素沿着第3维方向(维度是从索引0开始)连起来得到一个四维矩阵。
在r1.0版本里有变化,将两个张量沿着某一个轴连接称为一个张量。
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat([t1, t2], 0) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
tf.concat([t1, t2], 1) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]
可以用来串联有Bidirectional 网络生成的张量
encoder_outputs, encoder_states = \ tf.nn.bidirectional_dynamic_rnn( cell, cell, encoder_inputs_emb, sequence_length=self.encoder_len, dtype=dtype)
返回值的解释如下
Bidirectional return A tuple (outputs, output_states) where: outputs: A tuple (output_fw, output_bw) containing the forward and the backward rnn output `Tensor`. If time_major == False (default), output_fw will be a `Tensor` shaped: `[batch_size, max_time, cell_fw.output_size]` and output_bw will be a `Tensor` shaped: `[batch_size, max_time, cell_bw.output_size]`. If time_major == True, output_fw will be a `Tensor` shaped: `[max_time, batch_size, cell_fw.output_size]` and output_bw will be a `Tensor` shaped: `[max_time, batch_size, cell_bw.output_size]`. It returns a tuple instead of a single concatenated `Tensor`, unlike in the `bidirectional_rnn`. If the concatenated one is preferred, the forward and backward outputs can be concatenated as `tf.concat(outputs, 2)`. output_states: A tuple (output_state_fw, output_state_bw) containing the forward and the backward final states of bidirectional rnn.
将两个最后状态连接起来,生成的就是[batch, 2乘以hidden]的张量,这里先将encoder_states分成两个张量,然后沿着每个长老的第二维方向连接
tf.concat(encoder_states, 1)
通过下面的操作将每一步的forward和back hidden连接起来
tf.concat(encoder_outputs, 2)
tf.slice
函数原型 tf.slice(inputs,begin,size,name=”)
用来从input中切片,begin和size都是个N维数组,和input的shape是一样的。
输入begin = [a, b]时 表示第一维方向从index=a位置开始,第二维方向从index=b开始抽取。参数size表示从begin位置开始每一维上取多少个元素
import tensorflow as tf import numpy as np x=[[1,2,3],[4,5,6]] sess=tf.Session() begin_x=[1,0] #第一个1,决定了从x的第二行[4,5,6]开始,第二个0,决定了从[4,5,6] 中的4开始抽取 size_x=[1,2] # 第一个1决定了,从第二行以起始位置抽取1行,也就是只抽取[4,5,6] 这一行,在这一行中从4开始抽取2个元素 out=tf.slice(x,begin_x,size_x) print sess.run(out) # 结果:[[4 5]]
tf.reshape
self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])
假设self.h_pool为一个四维矩阵,shape为[batch,1,1,num_filters_total], 这个函数会得出一个[batch,num_filters_total]的矩阵。
tf.nn.dropout
with tf.name_scope("dropout"): self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)
self.h_pool_flat最后一维方向上每个节点保留下来的概率为self.dropout_keep_prob。
tf.train.slice_input_producer(tensor_list, num_epochs=None, shuffle=True, seed=None, capacity=32, name=None)
Returns:
A list of tensors, one for each element of tensor_list. If the tensor in tensor_list has shape [N, a, b, .., z], then the corresponding output tensor will have shape [a, b, …, z].
tf.train.range_input_producer(limit, num_epochs=None, shuffle=True, seed=None, capacity=32, name=None)
Produces the integers from 0 to limit-1 in a queue.
Returns:
A Queue with the output integers. A QueueRunner for the Queue is added to the current Graph’s QUEUE_RUNNER collection.
返回一个队列,队列的输出值为整数。这个队列的QueueRunner 被加入到当前计算图的QUEUE_RUNNER集合里。
- tensorflow
- TensorFlow
- TensorFlow
- tensorflow
- tensorflow
- tensorflow
- Tensorflow
- Tensorflow
- tensorFlow
- tensorflow
- Tensorflow
- TensorFlow
- tensorflow
- Tensorflow
- TensorFlow
- TensorFlow
- tensorflow
- TensorFlow
- 顶丰某个客户死机的计算过程
- 单元总结(2)
- 17 - 01 - 10 计算机导论基础知识
- 经典算法(三):插入排序
- ZCMU-1750
- tensorflow
- 码农成长记——innerHTML
- 判断给定字符串(包含标点符号和空格)是否为回文
- Cattle 学航模,每天一点航模知识(1)
- Python 第四天
- redis--主从、哨兵、集群
- win10取消微软帐户绑定使用本地账户登录的解决方法
- 为什么使用Linux
- jQuery——子选择器与可见性选择器