案例:TensorFlow实现线性回归

本文介绍了线性回归的基本原理,包括模型构建、损失函数的选择(均方误差)以及使用梯度下降法进行优化。通过TensorFlow示例展示了如何实现线性回归的训练过程,讨论了学习率对训练的影响,并涉及了模型的优化、变量可视化、事件文件记录和TensorBoard展示,以及模型的保存与加载方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1、线性回归原理复习


     1)构建模型
            y = w1x1+w2x2 + ..... wnxn+ b
      2)构造损失函数
            均方误差
      3)优化损失
             梯度下降


2、案例:实现线性回归的训练


     准备真实数据    100样本
     x特征值形状(100,1)
     y_ _true 目标值(100, 1)
     y_ _true = 0.8x + 0.7
    假定x和y之间的关系满足
           y=kx+b
           k≈0.8    b≈0.7
          流程分析:
        (100,1) * (1, 1) = (100, 1)
         y_ predict = X * weights(1, 1) + bias(1, 2)
1)构建模型
y_ predict = tf.matmul(x, weights) + bias
2)构造损失函数
error = tf. reduce_ mean(tf. square(y. _predict - y_ .true))
3)优化损失
optimizer = tf.train. GradientDescentOpt imizer(learning_ rate=0. 01) . minimize(error)

代码示例:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
def linear_regression():
    """
    自实现一个线性回归
    1)准备数据
    2)模型构造
    3)构造损失函数
    4)优化损失
    :return:
    """
    # 准备数据
    X = tf.compat.v1.random_normal(shape=[100,1])
    y_true = tf.matmul(X,[[0.8]])+0.7
    # 构造模型 定义模型参数用 变量
    weights = tf.Variable(initial_value=tf.compat.v1.random_normal(shape=[1,1]))
    bias = tf.Variable(initial_value=tf.compat.v1.random_normal(shape=[1,1]))
    y_predict = tf.matmul(X,weights)+bias
    # 构造损失函数
    error = tf.reduce_mean(tf.square(y_predict-y_true))
    #优化损失
    optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)
    # 显示初始化变量
    init = tf.compat.v1.global_variables_initializer()
    # 开启会话
    with tf.compat.v1.Session() as sess:
        # 初始化变量
        sess.run(init)
        # 查看初始化模型参数之后的值
        print("训练前模型参数:权重%f ,偏置%f,损失为%f" % (weights.eval(),bias.eval(), error.eval()))
        # 开始训练
        for i in range(1000):
            sess.run(optimizer)
            print("第%d次训练后模型参数:权重%f ,偏置%f,损失为%f" % (i+1,weights.eval(), bias.eval(), error.eval()))

    return None

linear_regression()

学习率越高,训练到较好结果步数越小,但是过大会出现梯度爆炸现象

3、优化

1、增加变量显示

1)创建事件文件

2)收集变量

3)合并变量

4)每次迭代运行一次合并变量

5)将summary对象写入事件文件

调用tensorboard显示

2、添加命名空间

更直观的看到变量的变化

3、模型保存与加载

1)保存:saver.save(sess,path)

2)加载:saver.restore(sess,path)

### TensorFlow 项目案例与数据库示例 TensorFlow 是一种广泛使用的机器学习框架,支持多种类型的神经网络和数据处理任务。以下是几个常见的 TensorFlow 项目案例及其涉及的数据库或数据集: #### 1. 图像分类 图像分类是一个经典的深度学习应用领域。以下是一个基于 MNIST 数据集的手写数字识别项目的例子。 ```python import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten # 加载MNIST数据集 (x_train, y_train), (x_test, y_test) = mnist.load_data() # 归一化输入数据 x_train, x_test = x_train / 255.0, x_test / 255.0 # 构建模型 model = Sequential([ Flatten(input_shape=(28, 28)), Dense(128, activation='relu'), Dense(10, activation='softmax') ]) # 编译并训练模型 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=5) # 测试模型性能 test_loss, test_acc = model.evaluate(x_test, y_test) print(f'Test accuracy: {test_acc}') ``` 此代码展示了如何加载 MNIST 数据集[^2] 并构建一个简单的全连接神经网络来完成手写数字分类的任务。 --- #### 2. 文本情感分析 另一个常见应用场景是对文本的情感进行分类。IMDB 数据集常被用来演示这一过程。 ```python import tensorflow as tf from tensorflow.keras.datasets import imdb from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, GlobalAveragePooling1D, Dense # 设置超参数 vocab_size = 10000 max_length = 500 # 加载IMDB数据集 (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size) # 填充序列使其长度一致 x_train = pad_sequences(x_train, maxlen=max_length) x_test = pad_sequences(x_test, maxlen=max_length) # 定义模型架构 model = Sequential([ Embedding(vocab_size, 16), GlobalAveragePooling1D(), Dense(16, activation='relu'), Dense(1, activation='sigmoid') ]) # 编译并训练模型 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(x_train, y_train, epochs=10, batch_size=512, validation_split=0.2) ``` 这段代码利用 IMDB 数据集 来执行二元情感分类任务。 --- #### 3. 物体检测 物体检测通常依赖于更复杂的卷积神经网络(CNN)。例如,使用预训练的 MobileNet 进行迁移学习可以快速搭建目标检测系统。 ```python import tensorflow as tf from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input from tensorflow.keras.preprocessing.image import ImageDataGenerator # 创建ImageDataGenerator实例 datagen = ImageDataGenerator(preprocessing_function=preprocess_input) train_generator = datagen.flow_from_directory( 'path_to_training_images', target_size=(224, 224), batch_size=32, class_mode='categorical' ) validation_generator = datagen.flow_from_directory( 'path_to_validation_images', target_size=(224, 224), batch_size=32, class_mode='categorical' ) # 载入MobileNetV2作为基础模型 base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) # 添加自定义顶层 model = tf.keras.Sequential([ base_model, tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(train_generator.num_classes, activation='softmax') ]) # 冻结基底层权重 for layer in base_model.layers: layer.trainable = False # 编译模型 model.compile(optimizer=tf.keras.optimizers.Adam(), loss='categorical_crossentropy', metrics=['accuracy']) # 开始训练 model.fit(train_generator, validation_data=validation_generator, epochs=10) ``` 该脚本通过迁移学习方法,在自己的数据集上微调了一个预训练好的 MobileNet 模型[^3]。 --- #### 4. 面部特征提取与人脸识别 对于面部识别任务,MTCNN 和 Inception 结构经常联合使用以提高精度。 ```python import tensorflow as tf from mtcnn.mtcnn import MTCNN from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_input # 初始化MTCNN探测器 detector = MTCNN() def detect_faces(image_path): image = cv2.imread(image_path) faces = detector.detect_faces(image) return [(face['box'], face['keypoints']) for face in faces] # 使用Inception-ResNet-V2进行特征提取 feature_extractor = InceptionResNetV2(include_top=False, pooling='avg') def extract_features(face_image): preprocessed_face = preprocess_input(np.expand_dims(face_image, axis=0)) features = feature_extractor.predict(preprocessed_face) return features.flatten() ``` 上述代码片段说明了如何结合 MTCNN 提取人脸区域以及使用 Inception-ResNet-V2 抽取高维特征向量[^4]。 --- ####
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值