使用logistic完成手写数据集的分类问题

243 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

理解logistic回归

逻辑回归是用于确定事件概率的一种数学模型,在0-1变量的情况下,当因变量取1时,自变量变化情况,反过来说就是当自变量发生变化时,因变量取1的概率发生了什么变化,也就是所谓的条件概率,其数学模型如下:

1.PNG

此时的概率P是抽象得到的一种情况,无法直接在观测数据中直接得到该值,因此计算概率时无法使用最小二乘法,但是却可以使用似然估计来进行求解。

logistic回归采用的是logit函数,所以上述公式可以进一步写为:

2.PNG

通过上式子使用最大似然估计可以得到交叉熵损失函数为

3.PNG

下面以最开始的MNIST数据集识别为例,进行识别分类任务。

# logistic回归实现Mnist手写数据集分类

import tensorflow as tf
from tensorflow import estimator as est
import numpy as np
from tensorflow import keras
from tensorflow import feature_column as fc
import matplotlib.pyplot as plt

# 导入数据集
(train_x, train_y), (test_x, test_y) = keras.datasets.mnist.load_data()

# 查看数据集与标签内容
# plt.imshow(train__x[0])
# print(train_y[0])
# plt.show()

# 数据处理,归一化
train_x = train_x/np.float32(255)
test_x = test_x/np.float32(255)
train_y = train_y.astype(np.int32)
test_y = test_y.astype(np.int32)

# 定义特征列
feature_col = [fc.numeric_column("x", shape=[28, 28])]
# 创建输入函数
train_input_function = tf.compat.v1.estimator.inputs.numpy_input_fn(
    x={"x":train_x},
    y = train_y,
    batch_size=100,
    num_epochs=None,
    shuffle=True
)
# 创建估计器,并存储模型图
classfiler = est.LinearClassifier(
    feature_columns=feature_col,
    model_dir="./blog05Tensorboard/",
    n_classes=10
)
# 训练模型
classfiler.train(train_input_function, steps=100)
# 从numpy的输入数据中,产生读取的featrues和labels数据。这样当我们在使用numpy的数据作为输入的时候就很方便。
val_input_function = tf.compat.v1.estimator.inputs.numpy_input_fn(
    x={"x": test_x},
    y=test_y,
    num_epochs=1,
    shuffle=False
)
# 评估训练的结果
eval_results = classfiler.evaluate(val_input_function)
print(eval_results)

4.PNG

对于上述的训练时间步长逐渐增加,训练的结果如上图所示。

5.PNG

6.PNG 训练的准确率与损失函数的走势如上图所示。