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入门


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值