拓展神经网络八股(入门级)

自制数据集

minst等数据集是别人打包好的,如果是本领域的数据集。自制数据集。

替换

把图片路径和标签文件输入到函数里,并返回输入特征和标签

要生成.npy格式的数据集,在进行读入训练集。

只需要把图片灰度值数据拼接到特征列表,标签添加到标签列表,提取操作函数如下:

复制代码
def generateds(path, txt):
    f = open(txt, 'r')
    contents = f.readlines() #读取所有行
    f.close()
    x, y_ = [], []
    for content in contents:
        value = content.split()
        img_path = path + value[0]#找到图片索引路径
        img = Image.open(img_path) #图片打开
        img = np.array(img.convert('L')) # 图片变为8位灰度的npy格式的数据集                    
        img = img / 255.
        x.append(img)
        y_.append(value[1])
        print('loading:' + content) # 打印状态提示
    x = np.array(x)
    y_ = np.array(y_)
    y_ = y_astype(np.int64)
    return x, y_

完整代码

复制代码
import tensorflow as tf
from PIL import Image
import numpy as np
import os

train_path = './fashion_image_label/fashion_train_jpg_60000/'
train_txt = './fashion_image_label/fashion_train_jpg_60000.txt'
x_train_savepath = './fashion_image_label/fashion_x_train.npy'
y_train_savepath = './fashion_image_label/fahion_y_train.npy'

test_path = './fashion_image_label/fashion_test_jpg_10000/'
test_txt = './fashion_image_label/fashion_test_jpg_10000.txt'
x_test_savepath = './fashion_image_label/fashion_x_test.npy'
y_test_savepath = './fashion_image_label/fashion_y_test.npy'


def generateds(path, txt):
    f = open(txt, 'r')
    contents = f.readlines()  # 按行读取
    f.close()
    x, y_ = [], []
    for content in contents:
        value = content.split()  # 以空格分开,存入数组
        img_path = path + value[0]
        img = Image.open(img_path)
        img = np.array(img.convert('L'))
        img = img / 255.
        x.append(img)
        y_.append(value[1])
        print('loading : ' + content)

    x = np.array(x)
    y_ = np.array(y_)
    y_ = y_.astype(np.int64)
    return x, y_


if os.path.exists(x_train_savepath) and os.path.exists(y_train_savepath) and os.path.exists(
        x_test_savepath) and os.path.exists(y_test_savepath):
    print('-------------Load Datasets-----------------')
    x_train_save = np.load(x_train_savepath)
    y_train = np.load(y_train_savepath)
    x_test_save = np.load(x_test_savepath)
    y_test = np.load(y_test_savepath)
    x_train = np.reshape(x_train_save, (len(x_train_save), 28, 28))
    x_test = np.reshape(x_test_save, (len(x_test_save), 28, 28))
else:
    print('-------------Generate Datasets-----------------')
    x_train, y_train = generateds(train_path, train_txt)
    x_test, y_test = generateds(test_path, test_txt)

    print('-------------Save Datasets-----------------')
    x_train_save = np.reshape(x_train, (len(x_train), -1))
    x_test_save = np.reshape(x_test, (len(x_test), -1))
    np.save(x_train_savepath, x_train_save)
    np.save(y_train_savepath, y_train)
    np.save(x_test_savepath, x_test_save)
    np.save(y_test_savepath, y_test)

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
model.summary()

数据增强

如果数据量过少,模型见识不足。增加数据,提高泛化力。

用来应对因为拍照角度不同引起的图片变形

image_gen_train=tf,keras.preprocessing,image.ImageDataGenneratorP(...)

image_gen)train,fit(x_train)

复制代码
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

fashion = tf.keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)  # 给数据增加一个维度,使数据和网络结构匹配

image_gen_train = ImageDataGenerator(
    rescale=1. / 1.,  # 如为图像,分母为255时,可归至0~1
    rotation_range=45,  # 随机45度旋转
    width_shift_range=.15,  # 宽度偏移
    height_shift_range=.15,  # 高度偏移
    horizontal_flip=True,  # 水平翻转
    zoom_range=0.5  # 将图像随机缩放阈量50%
)
image_gen_train.fit(x_train)

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

model.fit(image_gen_train.flow(x_train, y_train, batch_size=32), epochs=5, validation_data=(x_test, y_test),
          validation_freq=1)
model.summary()

因为是标准MINST数据集,因此在准确度上看不出来,需要在具体应用中才能体现

断点续训

实时保存最优模型

保存模型参数可以使用tensorflow提供的ModelCheckpoint(filepath=checkpoint_save,

save_weight_only,sabe_best_only)

参数提取

获取各层网络最优参数,可以在各个平台实现应用

model.trainable_variables 返回模型中可训练参数

acc/loss可视化

查看训练效果

history=model.fit()

复制代码
import tensorflow as tf
import os
import numpy as np
from matplotlib import pyplot as plt

np.set_printoptions(threshold=np.inf)

fashion = tf.keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

checkpoint_save_path = "./checkpoint/fashion.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
    print('-------------load the model-----------------')
    model.load_weights(checkpoint_save_path)

cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
                                                 save_weights_only=True,
                                                 save_best_only=True)

history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
                    callbacks=[cp_callback])
model.summary()

print(model.trainable_variables)
file = open('./weights.txt', 'w')
for v in model.trainable_variables:
    file.write(str(v.name) + '\n')
    file.write(str(v.shape) + '\n')
    file.write(str(v.numpy()) + '\n')
file.close()

###############################################    show   ###############################################

# 显示训练集和验证集的acc和loss曲线
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

plt.subplot(1, 2, 1) 画出第一列
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.legend()

plt.subplot(1, 2, 2) #画出第二列
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()

应用程序

给图识物

给出一张图片,输出预测结果

1.复现模型 Sequential加载模型

2.加载参数 load_weights(model_save_path)

3.预测结果

我们需要对颜色取反,我们的训练图片是黑底白字

减少了背景噪声的影响

复制代码
from PIL import Image
import numpy as np
import tensorflow as tf

type = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

model_save_path = './checkpoint/fashion.ckpt'
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])
                                        
model.load_weights(model_save_path)

preNum = int(input("input the number of test pictures:"))
for i in range(preNum):
    image_path = input("the path of test picture:")
    img = Image.open(image_path)
    img=img.resize((28,28),Image.ANTIALIAS)
    img_arr = np.array(img.convert('L'))
    img_arr = 255 - img_arr  #每个像素点= 255 - 各自点当前灰度值
    img_arr = img_arr/255.0
    x_predict = img_arr[tf.newaxis,...]

    result = model.predict(x_predict)
    pred=tf.argmax(result, axis=1)
    print('\n')
    print(type[int(pred)])
相关推荐
北京耐用通信8 小时前
电磁阀通讯频频“掉链”?耐达讯自动化Ethernet/IP转DeviceNet救场全行业!
人工智能·物联网·网络协议·安全·自动化·信息与通信
cooldream20098 小时前
小智 AI 智能音箱深度体验全解析:人设、音色、记忆与多场景玩法的全面指南
人工智能·嵌入式硬件·智能音箱
oil欧哟8 小时前
AI 虚拟试穿实战,如何低成本生成模特上身图
人工智能·ai作画
小糖学代码8 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
央链知播8 小时前
中国移联元宇宙与人工智能产业委联席秘书长叶毓睿受邀到北京联合大学做大模型智能体现状与趋势专题报告
人工智能·科技·业界资讯
人工智能培训8 小时前
卷积神经网络(CNN)详细介绍及其原理详解(2)
人工智能·神经网络·cnn
Data_agent8 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
YIN_尹9 小时前
目标检测模型量化加速在 openEuler 上的实现
人工智能·目标检测·计算机视觉
mys55189 小时前
杨建允:企业应对AI搜索趋势的实操策略
人工智能·geo·ai搜索优化·ai引擎优化
小毅&Nora9 小时前
【人工智能】【深度学习】 ⑦ 从零开始AI学习路径:从Python到大模型的实战指南
人工智能·深度学习·学习