TensorFlow 2.0 與 Python 3.11 兼容性
TensorFlow 2.0 官方版本對 Python 3.11 的支持有限,可能出現兼容性問題。建議使用 TensorFlow 2.10 或更高版本,這些版本已適配 Python 3.11。若需強制運行,可通過以下方式解決依賴沖突:
pip install --upgrade tensorflow
或指定版本:
pip install tensorflow==2.10.0
基礎示例:線性回歸模型
以下代碼展示了一個簡單的線性回歸模型:
import tensorflow as tf
import numpy as np# 生成模擬數據
X = np.linspace(0, 1, 100)
y = 2 * X + 1 + np.random.normal(scale=0.1, size=100)# 構建模型
model = tf.keras.Sequential([tf.keras.layers.Dense(units=1, input_shape=[1])
])# 編譯與訓練
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(X, y, epochs=100, verbose=0)# 預測
print(model.predict([0.5])) # 預期輸出接近 2.0
圖像分類示例(MNIST數據集)
from tensorflow.keras import layers, datasets# 加載數據
(train_images, train_labels), _ = datasets.mnist.load_data()
train_images = train_images / 255.0# 構建CNN模型
model = tf.keras.Sequential([layers.Reshape((28, 28, 1)),layers.Conv2D(32, (3, 3), activation='relu'),layers.MaxPooling2D((2, 2)),layers.Flatten(),layers.Dense(10, activation='softmax')
])# 訓練
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
常見問題解決
錯誤1:DLL加載失敗
在Windows系統中,安裝Microsoft Visual C++ Redistributable最新版本。
錯誤2:NumPy兼容性
嘗試降級NumPy版本:
pip install numpy==1.23.5
錯誤3:CUDA驅動問題
確認已安裝匹配的CUDA Toolkit和cuDNN版本,參考TensorFlow官方文檔的GPU支持列表。