欢迎来到 TensorFlow 基础教程!TensorFlow 是一个开源机器学习框架,广泛用于构建和训练各种机器学习模型。以下是您需要了解的关键内容:
1. 安装 TensorFlow
- Python 环境:确保已安装 Python 3.7 或更高版本
- 安装命令:使用 pip 安装 TensorFlow
📌 提示:安装后可访问 TensorFlow 官方文档 进一步了解高级功能pip install tensorflow
2. 基本用法
- 创建张量:使用
tf.constant()
定义数据import tensorflow as tf data = tf.constant([1, 2, 3], dtype=tf.int32)
- 构建模型:通过
tf.keras
创建神经网络model = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='relu', input_shape=(None, 1)), tf.keras.layers.Dense(1) ])
- 训练模型:使用
.fit()
方法进行训练model.fit(x_train, y_train, epochs=10)
3. 示例代码
以下是一个简单的线性回归示例:
import tensorflow as tf
import numpy as np
# 生成数据
x = np.random.rand(100, 1)
y = 2 * x + 1 + np.random.rand(100, 1) * 0.1
# 构建模型
model = tf.keras.Sequential([
tf.keras.layers.Dense(1)
])
model.compile(optimizer='sgd', loss='mse')
# 训练模型
model.fit(x, y, epochs=100)
4. 扩展阅读
如需深入了解 TensorFlow 的高级用法,可访问 TensorFlow 高级教程。此外,TensorFlow 官方社区 也提供大量资源和案例分享。
📌 注意:所有代码示例均基于 TensorFlow 2.x 版本,确保您的环境版本匹配