TensorFlow 操作简介

在TensorFlow中定义常数

import tensorflow as tf

a = tf.constant(1)
b = tf.constant(2)

sess = tf.Session()
sess.run(a)
sess.run(b)

进行算数运算:

with tf.Session() as sess:
  print("Addition matrix: %i" % sess.run(a + b))
  print("Multiplication matrix: %i" % sess.run(a * b))

定义函数

a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)

add = tf.add(a, b)
mul = tf.multiply(a, b)

with tf.Session() as sess:
    print("Addition with variables: %i" % sess.run(add, feed_dict={a:2, b:3}))
    print("Multiplication with variables: %i" % sess.run(mul, feed_dict = {a: 2, b: 3}))

矩阵乘法

matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.], [2.]])

mul = tf.matmul(matrix1, matrix2)

sess = tf.Session()
print(sess.run(mul))

可以看到上面的操作大多都需要 tf.Session(),显得有些累赘,此时可以利用Eager API简化操作

from __feature__ import absolute_import, division, print_function

import tensorflow as tf
import numpy as np


print("Setting Edge model...")
tf.enable_edger_execution()
tf.contrib.eager

print("Define constant eager")
a = tf.constant(2)
print("a = %i" % a)
b = tf.constant(3)
print("b = %i" % b)


print("Running operations, without tf.Session")
c = a + b
print("a + b = % i" % c)
d = a * b
print("a * b = % i" % d)

print("Mixing operations with tensors and numpy arrays")
a = tf.constant([[2., 1.], [1., 0.]], dtype = tf.float32)
print("Tensor: \n a = %s" % a)
b = np.array([[3., 0.], [5., 1.]], dtype = np.float32)
print("NumpyArray: \b b = %s" % b)

print("Running operations, without tf.Session")

c = a + b
print("a + b = %s" % c)

d = a * b
print("a * b = %s" % d)


print("Iterate through Tensor 'a' :")
for i in range (a.shape[0]):
  for j in range(a.shape[1]):
    print(a[i][j])

参考资料
https://github.com/aymericdamien/TensorFlow-Examples

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值