本笔记仅下载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
- 清华镜像:https://pypi.tuna.tsinghua.edu.cn/simple
- 阿里镜像: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成功!!!