一、TensorFlow 簡介
TensorFlow 是由 Google 開發的開源深度學習框架,支持數據流圖計算,可運行于 CPU/GPU/TPU。它被廣泛應用于語音識別、圖像處理、自然語言處理等多個 AI 領域。
二、安裝 TensorFlow
2.1 pip 安裝(默認 CPU 版本)
pip install tensorflow
2.2 pip 安裝(GPU 支持版本)
pip install tensorflow==2.15.0
注意:需提前安裝對應版本的 CUDA 和 cuDNN,推薦使用 NVIDIA 提供的安裝說明。
2.3 conda 安裝(適用于 Anaconda)
conda install -c conda-forge tensorflow
三、驗證安裝
import tensorflow as tf
print(tf.__version__)
print("是否使用 GPU:", tf.config.list_physical_devices('GPU'))
四、TensorFlow 基礎使用
4.1 創建張量
import tensorflow as tfa = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[5, 6], [7, 8]])
print(tf.add(a, b))
4.2 張量基本屬性
print(a.shape)
print(a.dtype)
五、構建神經網絡模型
使用 Keras Sequential 構建模型
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Densemodel = Sequential([Dense(128, activation='relu', input_shape=(784,)),Dense(10, activation='softmax')
])
六、模型編譯與訓練
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])# 假設有訓練數據 (x_train, y_train)
model.fit(x_train, y_train, epochs=5, batch_size=32)
七、保存與加載模型
保存模型
model.save('my_model.h5')
加載模型
from tensorflow.keras.models import load_model
model = load_model('my_model.h5')
八、TensorBoard 可視化
記錄日志
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir="./logs")
model.fit(x_train, y_train, callbacks=[tensorboard_callback])
啟動 TensorBoard
tensorboard --logdir=./logs
九、常見問題
Q1: 安裝失敗?
請升級 pip 并使用國內鏡像源安裝:
pip install --upgrade pip
pip install tensorflow -i https://pypi.tuna.tsinghua.edu.cn/simple
Q2: CUDA 相關報錯?
- 檢查 TensorFlow 和 CUDA/cuDNN 的兼容版本
- 確保安裝了 GPU 驅動并配置好環境變量
十、學習資源推薦
- TensorFlow 官方文檔
- TensorFlow 中文社區
- Google 官方入門教程
- 動手學深度學習(TF 版)
本文由“小奇Java面試”原創發布,轉載請注明出處。
可以搜索【小奇JAVA面試】第一時間閱讀,回復【資料】獲取福利,回復【項目】獲取項目源碼,回復【簡歷模板】獲取簡歷模板,回復【學習路線圖】獲取學習路線圖。