M1 Pro芯片Mac(Ventura13.1)运行TensorFlow训练代码报错求助
解决M1 Pro上TensorFlow Metal训练MNIST报错"could not find registered platform with id"的方案
1. 锁定TensorFlow相关依赖版本到兼容组合
M1系列Mac的TensorFlow Metal对版本匹配要求严格,强制指定以下适配Ventura 13.1的版本组合:
tensorflow-macos==2.12.0tensorflow-metal==0.8.0numpy==1.23.5
执行以下命令重装依赖:
pip uninstall tensorflow-macos tensorflow-metal numpy -y pip install tensorflow-macos==2.12.0 tensorflow-metal==0.8.0 numpy==1.23.5
2. 禁用TensorFlow的内存增长限制
在训练代码开头添加内存配置代码,避免Metal平台内存分配冲突:
import tensorflow as tf physical_devices = tf.config.list_physical_devices('GPU') if physical_devices: tf.config.experimental.set_memory_growth(physical_devices[0], True)
3. 重置Metal系统缓存
终端执行命令清除Metal的 shader 缓存,解决平台注册异常:
sudo rm -rf ~/Library/Caches/com.apple.metal
执行后重启Mac,再重新运行训练代码。
4. 检查并更新Xcode命令行工具
确保Xcode命令行工具适配Ventura 13.1:
xcode-select --install
若已安装,执行重置更新:
sudo xcode-select --reset
5. 调整训练代码的batch size
M1 Pro 16GB内存下,过大的batch size可能触发内存分配错误,尝试将batch size从默认64调整为32:
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") / 255.0 x_test = x_test.reshape(-1, 28, 28, 1).astype("float32") / 255.0 model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D((2,2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 调整batch_size为32 model.fit(x_train, y_train, batch_size=32, epochs=5, validation_split=0.1)
内容的提问来源于stack exchange,提问作者jansdhillon
相关产品推荐
相关产品推荐

