1. 计算加法
# -*- coding: utf-8 -*-
import tensorflow as tf
__author__ = 'Brown'
"""
计算加法
"""
x = tf.constant(1, name='x')
y = tf.Variable(x+9, name='y')
model = tf.initialize_all_variables()
with tf.Session() as session:
session.run(model)
print(session.run(y))
2. 测试tensorboard
# -*- coding: utf-8 -*-
import tensorflow as tf
__author__ = 'Brown'
"""
测试Tensor Board
"""
a = tf.constant(10, name='a')
b = tf.constant(90, name='b')
y = tf.Variable(a+b*2, name='y')
model = tf.initialize_all_variables()
with tf.Session() as session:
merged = tf.merge_all_summaries()
writer = tf.train.SummaryWriter('/tmp/tensorflowlogs', session.graph)
session.run(model)
print(session.run(y))
# 然后terminal输入以下命令:
# tensorboard --logdir=/tmp/tensorflowlogs
3. 测试切图片
# -*- coding: utf-8 -*-
import matplotlib.image as mp_image
import tensorflow as tf
import matplotlib.pyplot as plt
__author__ = 'Brown'
input_img = mp_image.imread('PacktLogo.jpg')
print(input_img.ndim)
print(input_img.shape)
my_img = tf.placeholder('uint8', [None, None, 3])
slice = tf.slice(my_img, [10, 0, 0], [16, -1, -1])
with tf.Session() as session:
result = session.run(slice, feed_dict={my_img: input_img})
print(result.shape)
plt.imshow(result)
plt.show()
4. 使用placeholder
# -*- coding: utf-8 -*-
import tensorflow as tf
__author__ = 'Brown'
"""
使用placeholder
"""
a = tf.placeholder("int32")
b = tf.placeholder("int32")
y = tf.mul(a, b)
with tf.Session() as session:
print(session.run(y, feed_dict={a: 2, b: 3}))
5. 测试计算梯度
# -*- coding: utf-8 -*-
import tensorflow as tf
__author__ = 'Brown'
x = tf.placeholder(tf.float32)
y = x*x*2
gradient = tf.gradients(y, x)
with tf.Session() as session:
print(session.run(gradient, feed_dict={x: 1}))
6. 测试生成随机数
# -*- coding: utf-8 -*-
import tensorflow as tf
import matplotlib.pyplot as plt
__author__ = 'Brown'
# 均匀分布
uniform = tf.random_uniform([100], minval=0, maxval=10, dtype=tf.int32)
with tf.Session() as session:
print(uniform.eval())
plt.hist(uniform.eval(), normed=True)
plt.show()
# 正态分布
norm = tf.random_normal([100], mean=0, stddev=1, dtype=tf.float32)
with tf.Session() as session:
norm_list = norm.eval()
plt.hist(norm_list, normed=True)
plt.show()
Ref:
《Get start with tensorflow》