Python虚拟环境安装Tensorflow

本笔记仅下载cpu版本 不考虑gpu版本~

虚拟环境搭建参考上一篇笔记:Python配置虚拟环境---使用venv_俩小歪的博客-CSDN博客

 

Step1:查看pip版

(xuni1) D:\python_venv\xuni1\Scripts>pip --version

我创建的虚拟环境继承了全局的pip包:19.2.3 版本 


有的笔记说最好升级到最新版(写笔记时pip最新版是23.2.1,我试了用最新版去安装tensorflow 报错了 后来又把版本降回来了...)   可能中间有错 不确定


Step2:通过镜像安装Tensorflow

  1. 清华镜像:https://pypi.tuna.tsinghua.edu.cn/simple
  2. 阿里镜像:https://mirrors.aliyun.com/pypi/simple/

TIPS: tensorflow和python版本对应:查看tensorflow官网在 Windows 环境中从源代码构建  |  TensorFlow

下图仅展示cpu版本的部分对应,GPU版以及详细CPU版查看上面链接 


我的python是3.8 对应我选择 tensorflow==2.3 :

(xuni1) D:\python_venv\xuni1\Scripts>pip install tensorflow==2.3 -i https://pypi.tuna.tsinghua.edu.cn/simple

注意:需要激活(activate)虚拟环境并在Scripts路径下进行pip

 安装需要几分钟...

Step3:测试Tensorflow 

1.可以直接在IDE里面查看:

注意:在创建虚拟环境时 最好不要继承全局包(非常容易冲突!!!

2.在终端进行测试


报错:protobuf版本过高 (默认protobuf==4.24.2)

TypeError: Descriptors cannot not be created directly.
If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0.
If you cannot immediately regenerate your protos, some other possible workarounds are:
 1. Downgrade the protobuf package to 3.20.x or lower.
 2. Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and will be much slower).

解决方案:重新装 protobuf == 3.19.0

结果:

ERROR: tensorboard 2.14.0 has requirement protobuf>=3.19.6, but you'll have protobuf 3.19.0 which is incompatible.

 那就直接下载protobuf==3.19.6  解决!


运行官网最简单代码:

import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)

结果:运行成功 即安装tensorflow成功!!!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值