【TensorFlow2.0】TensorFlow2.0与1.0对比

文章目录

  • 一、TensorFlow优势
      • 1.1 GPU加速
      • 1.2 自动求导
      • 1.3神经网络API
  • 二、TensorFlow2.0与1.0对比

一、TensorFlow优势

1.1 GPU加速

import tensorflow as tf
import timeit
cpu_data = []
gpu_data = []
for n in range(9):
	n = 10**n
	# 创建在CPU上运算的2个矩阵
	with tf.device('/cpu:0'):
		cpu_a = tf.random.normal([1, n])
		cpu_b = tf.random.normal([n, 1])
		print(cpu_a.device, cpu_b.device)
	# 创建使用GPU运算的2个矩阵
	with tf.device('/gpu:0'):
		gpu_a = tf.random.normal([1, n])
		gpu_b = tf.random.normal([n, 1])
		print(gpu_a.device, gpu_b.device)

	def cpu_run():
		with tf.device('/cpu:0'):
			c = tf.matmul(cpu_a, cpu_b)
		return c 

	def gpu_run():
		with tf.device('/gpu:0'):
			c = tf.matmul(gpu_a, gpu_b)
		return c 

	# 第一次计算需要热身,避免将初始化阶段时间结算在内
	cpu_time = timeit.timeit(cpu_run, number=10)
	gpu_time = timeit.timeit(gpu_run, number=10)
	print('warmup:', cpu_time, gpu_time)
	# 正式计算10次,取平均时间
	cpu_time = timeit.timeit(cpu_run, number=10)
	gpu_time = timeit.timeit(gpu_run, number=10)
	print('run time:', cpu_time, gpu_time)
	cpu_data.append(cpu_time/10)
	gpu_data.append(gpu_time/10)
	print(cpu_data,gpu_data)

1.2 自动求导

import tensorflow as tf 
# 创建4个张量
a = tf.constant(1.)
b = tf.constant(2.)
c = tf.constant(3.)
w = tf.constant(4.)
with tf.GradientTape() as tape:# 构建梯度环境
	tape.watch([w]) # 将w加入梯度跟踪列表
	# 构建计算过程
	y = a * w**2 + b * w + c
# 求导
[dy_dw] = tape.gradient(y, [w])
print(dy_dw)

1.3神经网络API

【TensorFlow2.0】TensorFlow2.0与1.0对比_第1张图片

二、TensorFlow2.0与1.0对比

  TensorFlow1.0运行案例

#TensorFlow为2.0版本,为了在2.0版本下运行1.0版本的功能执行下面操作
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior() # 使用静态图模式运行以下代码
assert tf.__version__.startswith('2.')
# 1.创建计算图阶段
# 为变量创建占位符,后续用来传入数据
a_ph = tf.placeholder(tf.float32, name='variable_a')
b_ph = tf.placeholder(tf.float32, name='variable_b')
# 变量操作
c_op = tf.add(a_ph, b_ph, name='variable_c')
# 2.运行计算图阶段
# 创建运行环境
sess = tf.InteractiveSession()
# 初始化变量
init = tf.global_variables_initializer()
sess.run(init) # 运行初始化操作,完成初始化
# 运行计算图,将数据参入变量的占位符。
c_numpy = sess.run(c_op, feed_dict={a_ph: 2., b_ph: 4.})
# 运算完才能得到数值类型的c_numpy
print('a+b=',c_numpy)

  tensorflow2.0运行案例

#%%
import tensorflow as tf
assert tf.__version__.startswith('2.')
# 1.创建输入张量
a = tf.constant(2.)
b = tf.constant(4.)
# 2.直接计算并打印
print('a+b=',a+b)
'''tensorflow2.0没有了session会话,代码十分简洁,如同pytorch'''



你可能感兴趣的:(TensorFlow,tensorflow)