【人工智能】Python常用库-TensorFlow常用方法教程

TensorFlow 是一个广泛应用的开源深度学习框架,支持多种机器学习任务,如深度学习、神经网络、强化学习等。以下是 TensorFlow 的详细教程,涵盖基础使用方法和示例代码。


1. 安装与导入

安装 TensorFlow:

pip install tensorflow

导入 TensorFlow:

import tensorflow as tf
import numpy as np

验证安装:

print(tf.__version__)  # 查看 TensorFlow 版本

2. TensorFlow 基础

2.1 张量(Tensor)

TensorFlow 的核心数据结构是张量,它是一个多维数组。

# 创建张量
a = tf.constant([1, 2, 3], dtype=tf.float32)  # 常量张量
b = tf.Variable([4, 5, 6], dtype=tf.float32)  # 可变张量

# 基本运算
c = a + b
print(c.numpy())  # 转换为 NumPy 数组输出

输出结果

[5. 7. 9.]
2.2 自动求导

TensorFlow 支持自动计算梯度。

x = tf.Variable(3.0)

with tf.GradientTape() as tape:
    y = x**2  # 定义目标函数

dy_dx = tape.gradient(y, x)  # 自动求导
print(dy_dx.numpy())

输出结果

6.0

3. 构建模型

3.1 使用 Sequential API
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense

# 构建简单神经网络
model = Sequential([
    Dense(64, activation='relu', input_shape=(10,)),
    Dense(32, activation='relu'),
    Dense(1, activation='sigmoid')
])

# 查看模型结构
model.summary()

输出结果

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense (Dense)               (None, 64)                704       
                                                                 
 dense_1 (Dense)             (None, 32)                2080      
                                                                 
 dense_2 (Dense)             (None, 1)                 33        
                                                                 
=================================================================
Total params: 2,817
Trainable params: 2,817
Non-trainable params: 0
_________________________________________________________________
3.2 自定义模型
import tensorflow as tf
from tensorflow.keras.layers import Dense

class MyModel(tf.keras.Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.dense1 = Dense(64, activation='relu')
        self.dense2 = Dense(32, activation='relu')
        self.output_layer = Dense(1, activat
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值