tensorflow_tutorials_01_basics

  • tf.Graph表示tf.Operations的集合,您可以通过写出方程来创建节点。默认情况下,有一个图:tf.get_default_graph(),并且任何新操作都会添加到此图中。tf.Operation的结果是tf.Tensor,它持有数值。
"""Summary of tensorflow basics.
Parag K. Mital, Jan 2016."""
# %% Import tensorflow and pyplot
import tensorflow as tf
import matplotlib.pyplot as plt

# %% tf.Graph represents a collection of tf.Operations
# You can create operations by writing out equations.
# By default, there is a graph: tf.get_default_graph()
# and any new operations are added to this graph.
# The result of a tf.Operation is a tf.Tensor, which holds
# the values.
  • 首先,创建一个张量,构造一个tf.Session来执行图,或者将会话传递给eval(fn)。
  • x.eval()不起作用,因为它需要一个会话!x.eval(session=sess)!
  • 如果我们不想继续通过会话,我们可以设置交互式会话。此时x.eval()是可以的。
# %% First a tf.Tensor
n_values = 32
x = tf.linspace(-3.0, 3.0, n_values)

# %% Construct a tf.Session to execute the graph.
sess = tf.Session()
result = sess.run(x)

# %% Alternatively pass a session to the eval(fn):
x.eval(session=sess)  # works!
# x.eval() does not work, as it requires a session!

# %% We can setup an interactive session if we don't
# want to keep passing the session around:
sess.close()
sess = tf.InteractiveSession()

# %% Now this will work!
x.eval()

# 测试
plt.plot(x.eval())

在这里插入图片描述

  • 然后,创建一个节点,我们将使用[-3,3]中的值来创建高斯分布,默认情况下,新操作将添加到默认图中。通过eval()和plt.plot()执行图形并绘制结果.
  • 一般,用tf.get_shape()得到张量形状。有时,我们可能直到它在图中被计算出来才能得到它的形状,在这种情况下,我们应该使用tf.shape(),它将返回一个可以被eval()的Tensor,而不是tf.Dimension的离散值。
  • 用tf.stack()组合张量
# %% Now a tf.Operation
# We'll use our values from [-3, 3] to create a Gaussian Distribution
sigma = 1.0
mean = 0.0
z = (tf.exp(tf.negative(tf.pow(x - mean, 2.0) /
                   (2.0 * tf.pow(sigma, 2.0)))) *
     (1.0 / (sigma * tf.sqrt(2.0 * 3.1415))))

# %% By default, new operations are added to the default Graph
assert z.graph is tf.get_default_graph()

# %% Execute the graph and plot the result
plt.plot(z.eval())

# %% We can find out the shape of a tensor like so:
print(z.get_shape())

# %% Or in a more friendly format
print(z.get_shape().as_list())

# %% Sometimes we may not know the shape of a tensor
# until it is computed in the graph.  In that case
# we should use the tf.shape(fn), which will return a
# Tensor which can be eval'ed, rather than a discrete
# value of tf.Dimension
print(tf.shape(z).eval())

# %% We can combine tensors like so:
print(tf.stack([tf.shape(z), tf.shape(z), [3], [4]]).eval())

# 测试
z.get_shape(): 
(32,)
z.get_shape().as_list():
[32]
tf.shape(z).eval(): 
[32]
tf.stack([tf.shape(z), tf.shape(z), [3], [4]]:
 [[32]
  [32]
  [ 3]
  [ 4]]

在这里插入图片描述

  • 用tf.matmul()将两者相乘得到2d高斯函数,即gauss_kernel。
# %% Let's multiply the two to get a 2d gaussian
z_2d = tf.matmul(tf.reshape(z, [n_values, 1]), tf.reshape(z, [1, n_values]))  # gauss_kernel

# %% Execute the graph and store the value that `out` represents in `result`.
plt.imshow(z_2d.eval())

在这里插入图片描述

  • gabor patch,此时是正弦二维函数。
# %% For fun let's create a gabor patch:
x = tf.reshape(tf.sin(tf.linspace(-3.0, 3.0, n_values)), [n_values, 1])
y = tf.reshape(tf.ones_like(x), [1, n_values])
z = tf.multiply(tf.matmul(x, y), z_2d)
plt.imshow(z.eval())

在这里插入图片描述

  • 打印所有节点名称
# %% We can also list all the operations of a graph:
ops = tf.get_default_graph().get_operations()
print([op.name for op in ops])

# 控制台
['LinSpace/start', 'LinSpace/stop', 'LinSpace/num', 'LinSpace', ..., 'Reshape_3/shape', 'Reshape_3', 'MatMul_1', 'Mul_3']
  • 创建一个通用函数来计算同样的东西:gabor
# %% Lets try creating a generic function for computing the same thing:
def gabor(n_values=32, sigma=1.0, mean=0.0):
    x = tf.linspace(-3.0, 3.0, n_values)
    z = (tf.exp(tf.negative(tf.pow(x - mean, 2.0) /
                       (2.0 * tf.pow(sigma, 2.0)))) *
         (1.0 / (sigma * tf.sqrt(2.0 * 3.1415))))
    gauss_kernel = tf.matmul(
        tf.reshape(z, [n_values, 1]), tf.reshape(z, [1, n_values]))
    x = tf.reshape(tf.sin(tf.linspace(-3.0, 3.0, n_values)), [n_values, 1])
    y = tf.reshape(tf.ones_like(x), [1, n_values])
    gabor_kernel = tf.multiply(tf.matmul(x, y), gauss_kernel)
    return gabor_kernel

# %% Confirm this does something:
plt.imshow(gabor().eval())
  • 创建另一个可以卷积的函数。
  • W矩阵仅能为2d的,但是conv2d需要一个4d的张量:height x, width x, n_input x, n_output
  • 如果img仅有长宽两个尺寸,则需在前后分别加一个维度:张数,通道。
  • 如果img有长宽通道三个尺寸,则只需在前加一个维度:张数。
  • 如果图像是3个通道,则需要为每个输入通道重复我们的卷积内核。
  • Stride是要跳过num,height,width,channels维度的值,此处只是[1, 1, 1, 1]。
# %% And another function which can convolve
def convolve(img, W):
    # The W matrix is only 2D
    # But conv2d will need a tensor which is 4d:
    # height x width x n_input x n_output
    if len(W.get_shape()) == 2:
        dims = W.get_shape().as_list() + [1, 1]
        W = tf.reshape(W, dims)

    if len(img.get_shape()) == 2:
        # num x height x width x channels
        dims = [1] + img.get_shape().as_list() + [1]
        img = tf.reshape(img, dims)
    elif len(img.get_shape()) == 3:
        dims = [1] + img.get_shape().as_list()
        img = tf.reshape(img, dims)
        # if the image is 3 channels, then our convolution
        # kernel needs to be repeated for each input channel
        W = tf.concat(axis=2, values=[W, W, W])

    # Stride is how many values to skip for the dimensions of
    # num, height, width, channels
    convolved = tf.nn.conv2d(img, W,
                             strides=[1, 1, 1, 1], padding='SAME')
    return convolved
  • 用skimage加载内置图片
# %% Load up an image:
from skimage import data
img = data.astronaut()
plt.imshow(img)
print(img.shape)
  • 为图创建一个占位符,可以存储任何输入。
  • 还有一个可以用gabor卷积我们的图像的图。
  • 最后,将图像推送到图中并计算结果。
  • tf.squeeze(input)函数返回一个张量,这个张量是将原始input中所有维度为1的那些维都删掉的结果axis可以用来指定要删掉的为1的维度。
# %% Now create a placeholder for our graph which can store any input:
x = tf.placeholder(tf.float32, shape=img.shape)

# %% And a graph which can convolve our image with a gabor
out = convolve(x, gabor())

# %% Now send the image into the graph and compute the result
result = tf.squeeze(out).eval(feed_dict={x: img})
plt.imshow(result)

在这里插入图片描述

使用tf.pow()导致的错误

z只有16-32的值!因为前16个变成NAN了。
z
z_2d的图像
在这里插入图片描述
gabor patch的图像,也只有1/4块。
在这里插入图片描述
当n_values=32时result图:
在这里插入图片描述

错误原因:

got Nan when powered float32 tensors
在这里插入图片描述
将tf.pow()改成tf.multiply()即可。

z = (tf.exp(tf.negative(tf.multiply(x - mean, x - mean) /
                       (2.0 * tf.multiply(sigma, sigma)))) *
         (1.0 / (sigma * tf.sqrt(2.0 * 3.1415))))

可见二维高斯函数与图像做卷积, 形成了一种渐变映射的效果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章