2-5实战分类模型之数据归一化

模块名称:002tf_keras_classification_model_normalize
与2-4相比,添加了一个数据归一化模块分别对训练数据,验证集,测试数据,进行归一化。然后accuracy:0.9218,归一化之后…accuracy:0.8758(并不是所有的归一化会对结果产生好的影响)。接下来回顾整体代码
首先加载相关库


import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
import tensorflow as tf
from tensorflow import keras

加载数据集,将数据集分类。可以ctrl+点击查看下load_data()的返回数组在这里插入图片描述
代码


#Keras里面有很多数据集,下面这个是一些黑白物品
#导入数据
fashion_mnist = keras.datasets.fashion_mnist
#拆分,利用load_data函数
(x_train_all,y_train_all),(x_test,y_test) = fashion_mnist.load_data()
#再一次拆分为训练集和验证集
x_valid,x_train = x_train_all[:5000],x_train_all[5000:]
y_valid,y_train = y_train_all[:5000],y_train_all[5000:]
print(x_valid.shape,y_valid.shape)
print(x_train.shape,y_train.shape)
print(x_test.shape,y_test.shape)

查看下训练数据中的最大值和最小值

print(np.max(x_train),np.min(x_train))

在这里插入图片描述
接下来就是本文的重点了,对数据进行归一化(查了下资料好像应该是正则化,归一化和正则化还是有所区别的)。首先引入StandardScaler模块,初始化一个scaler

#对数据进行归一化
#x = (x-u) / std
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()

作用:去均值和方差归一化。且是针对每一个特征维度来做的,而不是针对样本。 标准差标准化(standardScale)使得经过处理的数据符合标准正态分布,即均值为0,标准差为1。
接下来要注意:
第一:
fit(): Method calculates the parameters μ and σ and saves them as internal objects.
解释:简单来说,就是求得训练集X的均值,方差,最大值,最小值,这些训练集X固有的属性。
transform(): Method using these calculated parameters apply the transformation to a particular dataset.
解释:在fit的基础上,进行标准化,降维,归一化等操作(看具体用的是哪个工具,如PCA,StandardScaler等)。
fit_transform(): joins the fit() and transform() method for transformation of dataset.
解释:fit_transform是fit和transform的组合,既包括了训练又包含了转换。
transform()和fit_transform()二者的功能都是对数据进行某种统一处理(比如标准化~N(0,1),将数据缩放(映射)到某个固定区间,归一化,正则化等)
fit_transform(trainData)对部分数据先拟合fit,找到该part的整体指标,如均值、方差、最大值最小值等等(根据具体转换的目的),然后对该trainData进行转换transform,从而实现数据的标准化、归一化等等。
第二:scaler.transform()输入时一个二维的,然而我们的数据是三维的所以必须先 x_valid.astype(np.float32).reshape(-1,1),将三维降成二维。(这一点需要更深一步的理解)
接下来的代码

#x_train"[None , 28 ,28] ->[None,784]
x_train_scaled = scaler.fit_transform(
    x_train.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)
x_valid_scaled = scaler.transform(
    x_valid.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)
x_test_scaled = scaler.transform(
    x_test.astype(np.float32).reshape(-1,1)).reshape(-1,28,28)

然后看一下标准化之后训练数据中的最值

print(np.max(x_train_scaled),np.min(x_train_scaled))

在这里插入图片描述

验证集5000张图片(验证集(development set)—— 是模型训练过程中单独留出的样本集,它可以用于调整模型的超参数和用于对模型的能力进行初步评估)
训练集有55000张图片(是模型训练过程中单独留出的样本集,它可以用于调整模型的超参数和用于对模型的能力进行初步评估。)
测试集有10000张图片( 用来评估模最终模型的泛化能力。但不能作为调参、选择特征等算法相关的选择的依据。)


def show_images(n_rows,n_cols,x_data,y_data,class_names):
    assert len(x_data) == len(y_data)
    assert n_cols*n_cols < len(x_data)
    plt.figure(figsize=(n_cols*1.4,n_rows*1.6))
    for row in range(n_rows):
        for col in range(n_cols):
            index = n_cols*row +col
            plt.subplot(n_rows,n_cols,index+1)
            plt.imshow(x_data[index],cmap='binary',interpolation=
                       'nearest')
            plt.axis('off')
            plt.title(class_names[y_data[index]])
    plt.show()
class_names = ['T-shirt', 'Trouser', 'Pollover',
               'Dress', 'Coat', 'Sandal', 'Shirt',
               'Sneaker', 'Bag', 'Ankle boot']

构建模型


#tf.keras.model.Sequential
#我的理解是:model是建立的一个Sequential模型
model = keras.models.Sequential()
#添加一些图层,这一句是指添加一个展平层,将输入一个28*28的一维向量
model.add(keras.layers.Flatten(input_shape=[28,28]))
#再加一层全连接层
#300个单元
model.add(keras.layers.Dense(400,activation="relu"))
model.add(keras.layers.Dense(200,activation="relu"))
model.add(keras.layers.Dense(10,activation="softmax"))
#另外一种写法
# model1 = keras.models.Sequential([
#     keras.layers.Flatten(input_shape=[28,28]),
#     keras.layers.Dense(300,activation='relu'),
#     keras.layers.Dense(100,activation='relu'),
#     keras.layers.Dense(10,activation='softmax')
# ])
#relu: y = max(0,x)
#softmax:将向量变成概率分布,x = [x1,x2,x3]
#            y = [e^x1/sum,e^x2/sum,e^x3/sum],
#            sum=e^x1/sum+e^x2/sum+e^x3/sum
#为什么用sparse:y只是一个index值,y经过one-hot变成向量
#if y是一个向量则loss='categorical_crossentropy'
model.compile(loss='sparse_categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

训练
将x_train->x_train_scaled
将x_valid->x_valid_scaled


history = model.fit(x_train_scaled,y_train,epochs=10,
                    validation_data=(x_valid_scaled,y_valid))

训练结果:准确率进一步提升
在这里插入图片描述
指示图示的打印:

#指标图示的打印
def plot_learning_curves(history):
    pd.DataFrame(history.history).plot(figsize=(8,5))
    plt.grid(True)
    plt.gca().set_ylim(0,1)
    plt.show()
plot_learning_curves(history)

在这里插入图片描述
未进行标准化的相关指标:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值