TensorFlow学习过程笔记

TensorFlow学习过程遇见的问题

1.版本不兼容问题

TensorFlow 2 不兼容TensorFlow 1 ,所以很多时候就会出现一些问题,如下:

AttributeError: module ‘tensorflow’ has no attribute ‘global_variables_initializer’

AttributeError                            Traceback (most recent call last)
Cell In[50], line 7
      4 loss = tf.Variable((y - y_hat)**2, name='loss')  # Create a variable for the loss
      6 # 这里有一个版本的问题需要将init = tf.global_variables_initializer()改成如下
----> 7 init = tf.global_variables_initializer()         # When init is run later (session.run(init)),
      9 # the loss variable will be initialized and ready to be computed
     10 with tf.compat.v1.Session() as session:                    # Create a session and print the output

AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'

或者是出现:AttributeError: module ‘tensorflow’ has no attribute ‘global_variables_initializer’

AttributeError                            Traceback (most recent call last)
Cell In[52], line 7
      4 loss = tf.compat.v1.Variable((y - y_hat)**2, name='loss')  # Create a variable for the loss
      6 # 这里有一个版本的问题需要将init = tf.global_variables_initializer()改成如下
----> 7 init = tf.global_variables_initializer()        # When init is run later (session.run(init)),
      9 # the loss variable will be initialized and ready to be computed
     10 with tf.compat.v1.Session() as session:                    # Create a session and print the output

AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'

上述说tensorflow中不存在attribute的问题,大都是版本不兼容,我使用的是TensorFlow 2,但是上述代码中报错说缺失的属性都是TensorFlow 1中的,所以要对代码进行修改,解决办法如下:

# 报错代码
loss = tf.Variable((y - y_hat)**2, name='loss') 
# 修改后的代码
loss = tf.compat.v1.Variable((y - y_hat)**2, name='loss') 

还有的属性在TF2中已经改成另外的属性名称了,可以百度找到TF1中对应于TF2的属性
我们如果每一行代码都去修改添加 ‘tf.compat.v1.’ 这样的话比较麻烦,我们可以在导入tensorflow包的时候这样操作:

import tensorflow.compat.v1 as tf
import tensorflow as tf2

这样操作的话,tf导入的是TensorFlow1,tf2导入的时TensorFlow2


TensorFlow的入门学习是跟着吴恩达老师深度学习P2Week3中的讲解才有的初步接触,吴老师这周中的编程作业就需要使用TensorFlow搭建一个神经网络,作业内容可以详参这篇博文TensorFlow入门


你可能感兴趣的:(深度学习,tensorflow,学习,人工智能,笔记)