下面给你一个从安装到基本使用的 TensorFlow 入门指南,适合初学者。
先确认已安装 Python:
python --version
pip install tensorflow
如果你有 NVIDIA GPU 并配置好 CUDA,可安装 GPU 版:
pip install tensorflow-gpu
(新版 TensorFlow 已统一为 tensorflow,自动识别 GPU)
验证安装:
import tensorflow as tf
print(tf.__version__)
Tensor 是多维数组:
import tensorflow as tf
a = tf.constant([[1, 2], [3, 4]])
print(a)
x = tf.Variable(3.0)
with tf.GradientTape() as tape:
y = x ** 2
dy_dx = tape.gradient(y, x)
print(dy_dx) # 6.0
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
model = Sequential([
Dense(64, activation='relu', input_shape=(10,)),
Dense(1, activation='sigmoid')
])
model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)
import numpy as np
x_train = np.random.randn(1000, 10)
y_train = np.random.randint(0, 2, (1000,))
model.fit(x_train, y_train, epochs=10, batch_size=32)
model.predict(x_train[:5])
| 场景 | 模块 |
|---|---|
| 图像识别 | tf.keras.applications |
| 文本处理 | tf.keras.layers.Embedding |
| 自定义训练 | tf.GradientTape |
| 数据处理 | tf.data.Dataset |
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(-1, 28*28) / 255.0
y_train = to_categorical(y_train)
model = Sequential([
Dense(128, activation='relu', input_shape=(784,)),
Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
如果你愿意,可以告诉我:
我可以给你更针对性的学习路径和代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。