温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

tensorflow怎么用

发布时间:2026-09-24 12:04:29 来源:亿速云 阅读:97 作者:小樊 栏目:软件技术

下面给你一个从安装到基本使用的 TensorFlow 入门指南,适合初学者。


一、安装 TensorFlow

1. 安装 Python(建议 3.8–3.11)

先确认已安装 Python:

python --version

2. 使用 pip 安装

pip install tensorflow

如果你有 NVIDIA GPU 并配置好 CUDA,可安装 GPU 版:

pip install tensorflow-gpu

(新版 TensorFlow 已统一为 tensorflow,自动识别 GPU)

验证安装:

import tensorflow as tf
print(tf.__version__)

二、TensorFlow 核心概念

1. Tensor(张量)

Tensor 是多维数组:

import tensorflow as tf

a = tf.constant([[1, 2], [3, 4]])
print(a)

2. 自动求导(GradientTape)

x = tf.Variable(3.0)

with tf.GradientTape() as tape:
    y = x ** 2

dy_dx = tape.gradient(y, x)
print(dy_dx)  # 6.0

三、用 Keras 快速建模(最常用)

1. 构建一个简单神经网络

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense

model = Sequential([
    Dense(64, activation='relu', input_shape=(10,)),
    Dense(1, activation='sigmoid')
])

2. 编译模型

model.compile(
    optimizer='adam',
    loss='binary_crossentropy',
    metrics=['accuracy']
)

3. 训练模型

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)

4. 预测

model.predict(x_train[:5])

四、常见使用场景

场景 模块
图像识别 tf.keras.applications
文本处理 tf.keras.layers.Embedding
自定义训练 tf.GradientTape
数据处理 tf.data.Dataset

五、简单示例:手写数字识别(MNIST)

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)

六、学习建议

  • 新手先学 Keras API
  • 官方教程:https://www.tensorflow.org/tutorials
  • 推荐路线:
    张量 → Keras 模型 → 训练/评估 → 自定义训练 → 实战项目

如果你愿意,可以告诉我:

  • 你是 零基础 / Python 基础 / 有 ML 基础
  • 想做 图像 / 文本 / 时间序列 / 科研

我可以给你更针对性的学习路径和代码。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手