TensorFlow 是一个由 Google 开源的高级神经网络库,用于数据流编程。它允许研究人员和开发者轻松地构建和训练复杂的机器学习模型。
安装 TensorFlow
在开始之前,您需要安装 TensorFlow。以下是在 Python 中安装 TensorFlow 的基本步骤:
- 安装 Python 环境。
- 使用 pip 安装 TensorFlow:
pip install tensorflow
- 验证安装:运行
python -c "import tensorflow as tf; print(tf.__version__)"
快速入门
简单的神经网络
以下是一个简单的神经网络示例,用于分类任务:
import tensorflow as tf
# 创建模型
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='relu', input_shape=(784,)),
tf.keras.layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=5)
# 评估模型
model.evaluate(x_test, y_test)
使用 TensorFlow.js
TensorFlow.js 是 TensorFlow 在浏览器中的版本,允许您在浏览器中运行 TensorFlow 模型。
// 创建模型
const model = tf.sequential();
model.add(tf.layers.dense({units: 10, activation: 'relu', inputShape: [784]}));
model.add(tf.layers.dense({units: 10, activation: 'softmax'}));
// 编译模型
model.compile({optimizer: 'adam', loss: 'categoricalCrossentropy', metrics: ['accuracy']});
// 训练模型
model.fit(tf.tensor2d(x_train), tf.tensor1d(y_train), epochs=5);
// 评估模型
model.evaluate(tf.tensor2d(x_test), tf.tensor1d(y_test));
扩展阅读
想要了解更多关于 TensorFlow 的信息,请访问我们的 TensorFlow 官方文档。
TensorFlow Logo