tensorflow是当前最流行的深度学习框架,在这里记录和分享一些tf入门的基本姿势。
国际惯例,代码的第一行输出献给“Hello,World!”。
"""
HelloWorld example using TensorFlow.
"""
from __future__ import print_function
import datetime
import tensorflow as tf
print('Start at: ', datetime.datetime.now()) # 开始时间
hello = tf.constant('Hello, World!') # 定义一个常量
sess = tf.Session() # 开始执行tensorflow的会话
# 打印输出
print(sess.run(hello)) # b'Hello, World!'
print('End at: ', datetime.datetime.now()) # 结束时间
基本运算操作
"""
Basic constant operations example using TensorFlow.
"""
from __future__ import print_function
import tensorflow as tf
# Method1:定义常量后执行
# 定义常量
a = tf.constant(3)
b = tf.constant(5)
# 执行默认图操作
with tf.Session() as sess:
print("a=3, b=5")
print("常量相加: %i" % sess.run(a + b)) # 8
print("常量相乘: %i" % sess.run(a * b)) # 15
# Method2:定义类型、输入值后再执行
# 定义输入类型
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("变量相加: %i" % sess.run(add, feed_dict={a: 3, b: 5})) # 8
print("变量相乘: %i" % sess.run(mul, feed_dict={a: 3, b: 5})) # 15
# 矩阵乘法
# 定义一个1x2矩阵
matrix1 = tf.constant([[1., 4.]])
# 定义一个2x1矩阵
matrix2 = tf.constant([[3.], [2.]])
# 定义运算
product = tf.matmul(matrix1, matrix2)
# 执行
with tf.Session() as sess:
result = sess.run(product)
print(result) # [[ 11.]]
更多内容请访问:IT源点
注意:本文归作者所有,未经作者允许,不得转载