Tensorflow tensor操作代码片

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》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值