导入有关库
import urllib.request import os # python中的os模块用于处理文件和目录 import tarfile import tensorflow._api.v2.compat.v1 as tf import tensorflow #导入深度学习库,可引用有关算法模型 import tkinter.filedialog import tkinter as tk import matplotlib.pyplot as plt from PIL import Image tf.disable_v2_behavior() import time import numpy as np import skimage # python中的skimage模块用于图像处理 from skimage import data, transform, io from skimage.color import rgb2gray # rgb2gray将图片转化为灰度 import random from sklearn.utils import shuffle from PIL import Image
加载有关交通标志的数据集
def load_data(data_dir):
# 加载了两个list列表:
# images: 这个列表包含了一组图像,每个图像都转换为numpy数组。
# labels: 列表是标签,值为0到61的整数:
# 获取data_dir的所有子目录。每个代表一个标签。
directories = [d for d in os.listdir(data_dir)
if os.path.isdir(os.path.join(data_dir, d))]
labels = []
images = []
for d in directories:
label_dir = os.path.join(data_dir, d)
file_names = [os.path.join(label_dir, f) for f in os.listdir(label_dir) if f.endswith(".jpg")]
# 对于每个标签,加载它的图像,并将它们添加到图像列表。
# 并将标签编号(即目录名)添加到标签列表中。
for f in file_names:
images.append(skimage.io.imread(f))
labels.append(int(d))
return images, labels
# 获取训练集和测试集的特征和标签。
ROOT_PATH = "" #文件路径
train_data_dir = os.path.join(ROOT_PATH, "test_name") # 打开训练集文件
test_data_dir = os.path.join(ROOT_PATH, "test_name") # 打开测试集文件
# 加载训练数据集
train_images, train_labels = load_data(train_data_dir)
# 加载测试数据集
test_images, test_labels = load_data(test_data_dir)
# 统计图像和标签的数量
print("Unique Labels: {0}nTotal Images: {1}".format(len(set(train_labels)), len(train_images)))
数据预处理:打乱数据集、改变图片大小、特征标准化、设置独热编码
# 打乱训练集
x = 6
random.seed(x)
random.shuffle(train_images)
random.seed(x)
random.shuffle(train_labels)
# 把训练集图片改变成64*64大小的图片
train_images64 = [transform.resize(image, (64, 64)) for image in train_images]
# 把图片转成np数组
train_images64 = np.array(train_images64)
# 把测试集图片改变成64*64大小的图片
test_images64 = [transform.resize(image, (64, 64)) for image in test_images]
# 把图片转成np数组
test_images64 = np.array(test_images64)
# 把标签转成np数组
train_labels = np.array(train_labels)
test_labels = np.array(test_labels)
# 特征标准化
Xtrain_normalize = train_images64.astype("float32") / 255.0
Xtest_normalize = test_images64.astype("float32") / 255.0
# 将标签转化为读热编码
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse=False) # 可以实现将分类特征的每个元素转化为一个可以用来计算的值
yy = [[i] for i in range(62)]
print(yy)
# 把所有标签转为读热编码
encoder.fit(yy)
Ytrain_reshape = train_labels.reshape(-1, 1)
Ytrian_onehot = encoder.transform(Ytrain_reshape)
Ytest_reshape = test_labels.reshape(-1, 1)
Ytest_onehot = encoder.transform(Ytest_reshape)
构建深度神经网络(模型自行构建,下边是本人构建的神经网络模型图)
超参数的设置
train_epochs = 30 # 训练次数 batch_size = 50 total_batch = int(len(train_images) / batch_size) epoch_list = [] accuracy_list = [] loss_list = [] epoch = tf.Variable(0, name="epoch", trainable=False) startTime = time.time() sess = tf.Session() init = tf.global_variables_initializer() sess.run(init)
保存模型
ckpt_dir = "" #保存路径
if not os.path.exists(ckpt_dir):
os.makedirs(ckpt_dir)
# 生成saver
saver = tf.train.Saver(max_to_keep=1)
# 如果有检查点文件,读取最新的检查点文件,恢复各种变量值
ckpt = tf.train.latest_checkpoint(ckpt_dir)
if ckpt != None:
saver.restore(sess, ckpt)
else:
print("Training form scratch")
# 获取续训参数
start = sess.run(epoch)
print("Training starts from {} epoch".format(start + 1))
for ep in range(start, train_epochs):
Xtrain_normalize, Ytrian_onehot = shuffle(Xtrain_normalize, Ytrian_onehot, random_state=0)
for i in range(total_batch):
batch_x, batch_y = get_train_batch(i, batch_size)
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
# if i%10==0:
# print("step{}".format(i),"Finished!")
loss, acc = sess.run([loss_function, accuracy], feed_dict={x: batch_x, y: batch_y})
epoch_list.append(ep + 1)
loss_list.append(loss)
accuracy_list.append(acc)
print("Train epoch", (ep + 1), "Loss=", loss, "Accuracu=", acc)
# 保存检查点
saver.save(sess, ckpt_dir + "CIFAR10_cnn_model.ckpt", global_step=ep + 1)
sess.run(epoch.assign(ep + 1))
数据可视化
fig = plt.gcf()
fig.set_size_inches(4, 2)
plt.plot(epoch_list, loss_list, label="loss")
plt.xlabel("epoch")
plt.ylabel("loss")
plt.legend(["loss"], loc="best")
plt.show()
fig = plt.gcf()
fig.set_size_inches(4, 2)
plt.plot(epoch_list, accuracy_list, label="accuracy")
plt.xlabel("epoch")
plt.ylabel("accuracy")
plt.legend(["accuracy"], loc="best")
plt.show()
test_pred, acc = sess.run([pred, accuracy], feed_dict={x: Xtest_normalize, y: Ytest_onehot})
print("在测试集上的精度为", acc)
识别图片应用
def identify():
# 将文件夹中的图片放进模型里边识别出是哪个标签
global file_path
file_path = tkinter.filedialog.askopenfilename() # 打开文件窗口页面进行选择文件图片
print(file_path)
img1 = io.imread(file_path)
img_resize = transform.resize(img1, (64, 64))
img_arr = np.array(img_resize).reshape(1, 64, 64, 3)
img_ast = img_arr.astype("float32") / 255.0
pre = sess.run([pred], feed_dict={x: img_ast})
name = yy[np.argmax(pre)][0]
print(name)
以上是本人学习人工智能课程所选的课程设计,参考了一些技术大佬的经验所完成属于自己的项目设计,有些代码并未贴出,敬请谅解。该项目的精确度只有百分之八十多。



