Mac-M1安装Tensorflow

mtain 2022年04月22日 894次浏览

一、 说明

Apple官方安装文档:https://developer.apple.com/metal/tensorflow-plugin/

GitHub:https://github.com/apple/tensorflow_macos

二、环境安装

1. conda创建tensorflow虚拟环境

创建opencv虚拟环境
conda create -n tensorflow python=3.9.10

激活环境
conda activate tensorflow

安装tensorflow
conda install -c apple tensorflow-deps==2.6.0

python -m pip install tensorflow-macos

python -m pip install tensorflow-metal

退出当前环境
conda deactivate

移除环境
conda remove -n your_env_name --all

2. 测试

vi tensorflow_hello.py

import tensorflow as tf
import numpy as np
from tensorflow import keras
#定义和编译一个神经网络
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
# 编译 并指定 loss optimizer
model.compile(optimizer='sgd', loss='mean_squared_error')
#提供数据
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-2.0, 1.0, 4.0, 7.0, 10.0, 13.0], dtype=float)
#培训
model.fit(xs, ys, epochs=500)
#预测
print(model.predict([10.0]))

运行:python tensorflow_hello.py

三、 运行模型实例

1. TensorFlow2.0-Examples

https://github.com/YunYang1994/TensorFlow2.0-Examples

python 

2. 预训练模型-Transformers

自然语言处理transformers工具包

Github

Transformers:https://github.com/huggingface/transformers

TensorFlow examples: https://github.com/huggingface/transformers/tree/main/examples/tensorflow

运行BERT模型

# conda安装Transformers 
conda install -c huggingface transformers
# 验证安装是否成功
python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('hello world'))"


git checkout v4.10.3-release

cd examples/tensorflow/summarization/

python run_summarization.py  \
--model_name_or_path facebook/bart-base \
--dataset_name cnn_dailymail \
--dataset_config "3.0.0" \
--output_dir /tmp/tst-summarization  \
--per_device_train_batch_size 8 \
--per_device_eval_batch_size 16 \
--num_train_epochs 3 \
--do_train \
--do_eval

报错解决

安装缺失的库
pip install datasets nltk

scikit-learn是基于Python语言的机器学习库,具有:

简单高效的数据分析工具
可在多种环境中重复使用
建立在Numpy,Scipy以及matplotlib等数据科学库之上
开源且可商用的-基于BSD许可

https://www.sklearncn.cn/

datasets是sklearn的数据集库