我的模型--

from skimage import io, transform  # skimage模块下的io transform(图像的形变与缩放)模块
import glob  # glob 文件通配符模块
import os  # os 处理文件和目录的模块
import tensorflow as tf
import numpy as np  # 多维数据处理模块
import time
import matplotlib.pyplot as plt
# 数据集地址
#path = './flower_photos/'
path = '../dataset/train/'
# 模型保存地址
model_path = './cnn1_model.ckpt'# 将所有的图片resize成100*100
w = 100
h = 100
c = 3# 读取图片+数据处理
def read_img(path):# os.listdir(path) 返回path指定的文件夹包含的文件或文件夹的名字的列表# os.path.isdir(path)判断path是否是目录# b = [x+x for x in list1 if x+x<15 ]  列表生成式,循环list1,当if为真时,将x+x加入列表bcate = [path + x for x in os.listdir(path) if os.path.isdir(path + x)]imgs = []labels = []print("开始读入图片和标签。。。。")for idx, folder in enumerate(cate):# glob.glob(s+'*.py') 从目录通配符搜索中生成文件列表for im in glob.glob(folder + '/*.png'):# 输出读取的图片的名称#print('reading the images:%s' % (im))# io.imread(im)读取单张RGB图片 skimage.io.imread(fname,as_grey=True)读取单张灰度图片# 读取的图片img = io.imread(im)# skimage.transform.resize(image, output_shape)改变图片的尺寸img = transform.resize(img, (w, h))# 将读取的图片数据加载到imgs[]列表中imgs.append(img)# 将图片的label加载到labels[]中,与上方的imgs索引对应labels.append(idx)# 将读取的图片和labels信息,转化为numpy结构的ndarr(N维数组对象(矩阵))数据信息print("读入图片和标签完毕。。。。")return np.asarray(imgs, np.float32), np.asarray(labels, np.int32)# 调用读取图片的函数,得到图片和labels的数据集
data, label = read_img(path)# 打乱顺序
# 读取data矩阵的第一维数(图片的个数)
num_example = data.shape[0]
# 产生一个num_example范围,步长为1的序列
arr = np.arange(num_example)
# 调用函数,打乱顺序
np.random.shuffle(arr)
# 按照打乱的顺序,重新排序
data = data[arr]
label = label[arr]# 将所有数据分为训练集和验证集
ratio = 0.8
s = np.int(num_example * ratio)
x_train = data[:s]
y_train = label[:s]
x_val = data[s:]
y_val = label[s:]# -----------------构建网络----------------------
# 本程序cnn网络模型,共有7层,前三层为卷积层,后三层为全连接层,前三层中,每层包含卷积、激活、池化层
# 占位符设置输入参数的大小和格式
x = tf.placeholder(tf.float32, shape=[None, w, h, c], name='x')
y_ = tf.placeholder(tf.int32, shape=[None, ], name='y_')def inference(input_tensor, train, regularizer):# -----------------------第一层----------------------------with tf.variable_scope('layer1-conv1'):# 初始化权重conv1_weights为可保存变量,大小为5x5,3个通道(RGB),数量为32个conv1_weights = tf.get_variable("weight", [5, 5, 3, 32],initializer=tf.truncated_normal_initializer(stddev=0.1))# 初始化偏置conv1_biases,数量为32个conv1_biases = tf.get_variable("bias", [32], initializer=tf.constant_initializer(0.0))# 卷积计算,tf.nn.conv2d为tensorflow自带2维卷积函数,input_tensor为输入数据,# conv1_weights为权重,strides=[1, 1, 1, 1]表示左右上下滑动步长为1,padding='SAME'表示输入和输出大小一样,即补0conv1 = tf.nn.conv2d(input_tensor, conv1_weights, strides=[1, 1, 1, 1], padding='SAME')# 激励计算,调用tensorflow的relu函数relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases))with tf.name_scope("layer2-pool1"):# 池化计算,调用tensorflow的max_pool函数,strides=[1,2,2,1],表示池化边界,2个对一个生成,padding="VALID"表示不操作。pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="VALID")# -----------------------第二层----------------------------with tf.variable_scope("layer3-conv2"):# 同上,不过参数的有变化,根据卷积计算和通道数量的变化,设置对应的参数conv2_weights = tf.get_variable("weight", [5, 5, 32, 64],initializer=tf.truncated_normal_initializer(stddev=0.1))conv2_biases = tf.get_variable("bias", [64], initializer=tf.constant_initializer(0.0))conv2 = tf.nn.conv2d(pool1, conv2_weights, strides=[1, 1, 1, 1], padding='SAME')relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases))with tf.name_scope("layer4-pool2"):pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')# -----------------------第三层----------------------------# 同上,不过参数的有变化,根据卷积计算和通道数量的变化,设置对应的参数with tf.variable_scope("layer5-conv3"):conv3_weights = tf.get_variable("weight", [3, 3, 64, 128],initializer=tf.truncated_normal_initializer(stddev=0.1))conv3_biases = tf.get_variable("bias", [128], initializer=tf.constant_initializer(0.0))conv3 = tf.nn.conv2d(pool2, conv3_weights, strides=[1, 1, 1, 1], padding='SAME')relu3 = tf.nn.relu(tf.nn.bias_add(conv3, conv3_biases))with tf.name_scope("layer6-pool3"):pool3 = tf.nn.max_pool(relu3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')# -----------------------第四层----------------------------# 同上,不过参数的有变化,根据卷积计算和通道数量的变化,设置对应的参数with tf.variable_scope("layer7-conv4"):conv4_weights = tf.get_variable("weight", [3, 3, 128, 128],initializer=tf.truncated_normal_initializer(stddev=0.1))conv4_biases = tf.get_variable("bias", [128], initializer=tf.constant_initializer(0.0))conv4 = tf.nn.conv2d(pool3, conv4_weights, strides=[1, 1, 1, 1], padding='SAME')relu4 = tf.nn.relu(tf.nn.bias_add(conv4, conv4_biases))with tf.name_scope("layer8-pool4"):pool4 = tf.nn.max_pool(relu4, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')nodes = 6 * 6 * 128reshaped = tf.reshape(pool4, [-1, nodes])# 使用变形函数转化结构# -----------------------第五层---------------------------with tf.variable_scope('layer9-fc1'):# 初始化全连接层的参数,隐含节点为1024个fc1_weights = tf.get_variable("weight", [nodes, 1024],initializer=tf.truncated_normal_initializer(stddev=0.1))if regularizer != None: tf.add_to_collection('losses', regularizer(fc1_weights))  # 正则化矩阵fc1_biases = tf.get_variable("bias", [1024], initializer=tf.constant_initializer(0.1))# 使用relu函数作为激活函数fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_weights) + fc1_biases)# 采用dropout层,减少过拟合和欠拟合的程度,保存模型最好的预测效率if train: fc1 = tf.nn.dropout(fc1, 0.5)# -----------------------第六层----------------------------with tf.variable_scope('layer10-fc2'):# 同上,不过参数的有变化,根据卷积计算和通道数量的变化,设置对应的参数fc2_weights = tf.get_variable("weight", [1024, 512],initializer=tf.truncated_normal_initializer(stddev=0.1))if regularizer != None: tf.add_to_collection('losses', regularizer(fc2_weights))fc2_biases = tf.get_variable("bias", [512], initializer=tf.constant_initializer(0.1))fc2 = tf.nn.relu(tf.matmul(fc1, fc2_weights) + fc2_biases)if train: fc2 = tf.nn.dropout(fc2, 0.5)# -----------------------第七层----------------------------with tf.variable_scope('layer11-fc3'):# 同上,不过参数的有变化,根据卷积计算和通道数量的变化,设置对应的参数fc3_weights = tf.get_variable("weight", [512, 5],initializer=tf.truncated_normal_initializer(stddev=0.1))if regularizer != None: tf.add_to_collection('losses', regularizer(fc3_weights))fc3_biases = tf.get_variable("bias", [5], initializer=tf.constant_initializer(0.1))logit = tf.matmul(fc2, fc3_weights) + fc3_biases  # matmul矩阵相乘# 返回最后的计算结果return logit# ---------------------------网络结束---------------------------
# 设置正则化参数为0.0001
regularizer = tf.contrib.layers.l2_regularizer(0.0001)
# 将上述构建网络结构引入
logits = inference(x, False, regularizer)# (小处理)将logits乘以1赋值给logits_eval,定义name,方便在后续调用模型时通过tensor名字调用输出tensor
b = tf.constant(value=1, dtype=tf.float32)
logits_eval = tf.multiply(logits, b, name='logits_eval')  # b为1# 设置损失函数,作为模型训练优化的参考标准,loss越小,模型越优
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y_)
# 设置整体学习率为α为0.001
train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
# 设置预测精度
correct_prediction = tf.equal(tf.cast(tf.argmax(logits, 1), tf.int32), y_)
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))# 定义一个函数,按批次取数据
def minibatches(inputs=None, targets=None, batch_size=None, shuffle=False):assert len(inputs) == len(targets)if shuffle:indices = np.arange(len(inputs))np.random.shuffle(indices)for start_idx in range(0, len(inputs) - batch_size + 1, batch_size):  #range(start,end,step)if shuffle:excerpt = indices[start_idx:start_idx + batch_size]else:excerpt = slice(start_idx, start_idx + batch_size)yield inputs[excerpt], targets[excerpt]# 训练和测试数据,可将n_epoch设置更大一些# 迭代次数
n_epoch = 30
fig_loss = np.zeros([n_epoch])
fig_acc1 = np.zeros([n_epoch])
fig_acc2= np.zeros([n_epoch])
# 每次迭代输入的图片数据
batch_size = 64
saver = tf.train.Saver(max_to_keep=1)  # 可以指定保存的模型个数,利用max_to_keep=4,则最终会保存4个模型(
with tf.Session() as sess:# 初始化全局参数sess.run(tf.global_variables_initializer())# 开始迭代训练,调用的都是前面设置好的函数或变量for epoch in range(n_epoch):start_time = time.time()# training#训练集train_loss, train_acc, n_batch = 0, 0, 0for x_train_a, y_train_a in minibatches(x_train, y_train, batch_size, shuffle=True):_, err, ac = sess.run([train_op, loss, acc], feed_dict={x: x_train_a, y_: y_train_a})train_loss += errtrain_acc += acn_batch += 1if n_batch%20==0:# print("Epoch:%d After %d batch_size train loss" % (n_epoch,n_batch))# print(err)print("Epoch:%d After %d batch_size average train loss: %f" % (epoch, n_batch, np.sum(train_loss) / n_batch))# print("Epoch:%d After %d batch_size train acc %f" % (epoch, n_batch,ac))print("Epoch:%d After %d batch_size average train acc: %f" % (epoch, n_batch, np.sum(train_acc) / n_batch))#Epoch: 9 After 45  batch_size average train loss: 2.750402 Epoch: 9#After 45 batch_size average train acc: 0.993403fig_loss[epoch] = np.sum(train_loss) / n_batchfig_acc1[epoch] = np.sum(train_acc) / n_batch#validation#验证集val_loss, val_acc, n_batch = 0, 0, 0for x_val_a, y_val_a in minibatches(x_val, y_val, batch_size, shuffle=False):err, ac = sess.run([loss, acc], feed_dict={x: x_val_a, y_: y_val_a})val_loss += errval_acc += acn_batch += 1print("validation loss: %f" % (np.sum(val_loss) / n_batch))print("validation acc: %f" % (np.sum(val_acc) / n_batch))fig_acc2[epoch] = np.sum(val_acc) / n_batch#保存模型及模型参数if epoch % 2 == 0:saver.save(sess, model_path, global_step=epoch)# 训练loss图
fig, ax1 = plt.subplots()
lns1 = ax1.plot(np.arange(n_epoch), fig_loss, label="Loss")
ax1.set_xlabel('iteration')
ax1.set_ylabel('training loss')# 训练和验证两种准确率曲线图放在一张图中
fig2, ax2 = plt.subplots()
ax3 = ax2.twinx()#由ax2图生成ax3图
lns2 = ax2.plot(np.arange(n_epoch), fig_acc1, label="Loss")
lns3 = ax3.plot(np.arange(n_epoch), fig_acc2, label="Loss")ax2.set_xlabel('iteration')
ax2.set_ylabel('training acc')
ax3.set_ylabel('val acc')# 合并图例
lns = lns3 + lns2
labels = ["train acc", "val acc"]
plt.legend(lns, labels, loc=7)plt.show()

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/567586.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python蚁群算法 路径规划_蚁群算法(1) - Python实现

1 importnumpy as np2 importmatplotlib.pyplot as plt345 #建立“蚂蚁”类6 classAnt(object):7 def __init__(self, path):8 self.path path #蚂蚁当前迭代整体路径9 self.length self.calc_length(path) #蚂蚁当前迭代整体路径长度1011 def calc_length(self, path_): #pa…

win10-PC端无法输入中文

试过 任务管理器中&#xff0c;的 MscCtfMonitor任务&#xff0c;先选择结束&#xff0c;然后再选择运行。关闭后输入法就可重新使用了---不行 当出现Win10无法输入中文汉字时&#xff0c;首先我们需要重启一下“输入法”程序&#xff1a; 右击桌面“Windows”图标&#xff0c…

python变量和数据类型_python的变量和数据类型

1.Python的变量不用定义类型,每个语句后面也不用使用分号结束语句(不像java,C,C#要在变量声明后加上分号)如:message"hello python world"print(message)-----------------------------------age19print(age)2.字符串(1).在Python中用引号括起来的都是字符串, 其中的…

函数声明是形参类型省略

如果参数类型省略&#xff0c;默认为int类型。&#xff08;此为古老写法&#xff09; #include<stdio.h>float average(a,n) int a[]; {int j;float s0;float aver;for(j0;j<0;j){sa[j];}avers/n;return aver; }main() {int a[12]{10,4,2,7,3,12,5,34,5,9,6,8};print…

因果图中的约束关系

E:互斥&#xff0c;exclude&#xff0c;表示abc最多只能有一个1&#xff0c;即abc000&#xff0c;100&#xff0c;010&#xff0c;001&#xff0c;只能有1个1或者全0&#xff08;可不选&#xff0c;要选最多选一个&#xff09;。I:包含&#xff0c;include&#xff0c;表示abc不…

如何销毁一个实例化对象_JAVA中如何创建和销毁对象

第1条 考虑用静态方法代替构造器类可以通过静态工厂方法来提供它的客户端&#xff0c;而不是通过构造器。提供静态工厂方法而不是公有构造器&#xff0c;这样做具有几大优势。1.静态工厂方法与构造器不同的第一大优势在于&#xff0c;它们有名称。例如&#xff0c;构造器BigInt…

因果图-交通一卡通自动充值软件系统-实例分析

因果图法测试用例的设计步骤 &#xff08;1&#xff09;确定软件规格(需求)中的原因和结果 &#xff08;2&#xff09;确定原因和结果之间的逻辑关系 &#xff08;3&#xff09;确定因果图中的各个约束(constraints) &#xff08;4&#xff09;画出因果图并转换为决策表 &…

如何区分电梯卡为id卡ic卡_电梯刷卡系统基本属性

电梯刷卡控制系统的发展是十分迅速的&#xff0c;在这点上相信大家都有所体会。但是为了节约成本费用&#xff0c;很多地产商都是安装的基本常见的电梯刷卡控制系统&#xff0c;这种常见的电梯&#xff0c;能够满足基本上的用户需求&#xff0c;在零件上面也是能够与大多数的零…

python应用体系_python-大型django应用程序体系结构

如何适当地构建一个较大的Django网站,以保持可测试性和可维护性&#xff1f;本着最好的django精神(我希望),我们开始时不太关心网站不同部分之间的去耦.我们确实将其分为不同的应用程序,但是通过共同使用模型类和直接方法调用,它们直接相互依赖.这变得越来越纠结.例如,我们的一…

Postman入门到精通01

1、什么是接口&#xff1f; 电脑&#xff1a;USB&#xff0c;投影仪 作用&#xff1a;数据传输 软件&#xff1a;API&#xff08;application Program Interface&#xff09;&#xff0c;微信提现和充值接口&#xff0c;支付宝支付&#xff0c;银联支付接口&#xff08;鉴权…

python oracle orm_Python ORM

本章内容ORM介绍如果写程序用pymysql和程序交互&#xff0c;那是不是要写原生sql语句。如果进行复杂的查询&#xff0c;那sql语句就要进行一点一点拼接&#xff0c;而且不太有重用性&#xff0c;扩展不方便。而且写的sql语句可能不高效&#xff0c;导致程序运行也变慢。为了避免…

前端校验和后端校验区别

前台验证数据格式 后台验证的是数据的正确性 当下流行的系统架构方案中&#xff0c;前端和后端都是分离开的。 目的&#xff1a;① 为了方便前端开发人员和后端开发人员可以同时开发&#xff1b;② 前后端分离也使得前后端的代码可以分开进行管理&#xff0c;方便了各自的版…

unittest-ddt报错AttributeError: type object ‘forTestDDT‘ has no attribute ‘test_2‘

unittest 添加多个ddt数据驱动后&#xff0c;报错&#xff1a; FAILED (errors1)Error Traceback (most recent call last):File "D:\Anaconda3\lib\unittest\case.py", line 60, in testPartExecutoryieldFile "D:\Anaconda3\lib\unittest\case.py", lin…

socket timeout是什么引起的_MySQL C API 参数 MYSQL_OPT_READ_TIMEOUT 的一些行为分析

作者&#xff1a;戴岳兵MYSQL_OPT_READ_TIMEOUT 是 MySQL c api 客户端中用来设置读取超时时间的参数。在 MySQL 的官方文档中&#xff0c;该参数的描述是这样的&#xff1a;MYSQL_OPT_READ_TIMEOUT (argument type: unsigned int *)The timeout in seconds for each attempt t…

python动态爬取知乎_python爬虫从小白到高手 Day2 动态页面的爬取

今天我们说说动态页面的抓取&#xff0c;动态页面的概念不是说网页上的内容是活动的&#xff0c;而是刷新的内容由Ajax加载&#xff0c;页面的URL没有变化&#xff0c;具体概念问度娘。就以男人都喜欢的美女街拍为例&#xff0c;对象为今日头条。chrome打开今日头条 ->搜索开…

Python操作文件,报FileNotFoundError: [Error 2] No such file or directory错误

python操作文件时&#xff0c;报No such file or directory错误。 多次检查目录、文件名、语法都是对的。 折腾一番后&#xff0c;打开文件所在文件夹&#xff0c;并显示所有文件后缀名&#xff0c;才发现此文件并没有txt后缀名 解决方法&#xff1a; 添加文件的.txt后缀名&a…

python多标签分类_如何通过sklearn实现多标签分类?

sklearn支持多类别(Multiclass)分类和多标签(Multilabel)分类&#xff1a;多类别分类&#xff1a;超过两个类别的分类任务。多类别分类假设每个样本属于且仅属于一个标签&#xff0c;类如一个水果可以是苹果或者是桔子但是不能同时属于两者。多标签分类&#xff1a;给每个样本分…

练习ddt-file_data时,报错UnboundLocalError local variable ‘value‘ referenced before assignment

错误原因就是&#xff0c;在xx.yml中的内容无效 更改之前&#xff1a; 更改之后&#xff1a; 注意冒号后面要有空格 改完之后运行就能正确读取到了

python筛选数据求均值_Python Pandas实现数据分组求平均值并填充nan的示例

Python实现按某一列关键字分组&#xff0c;并计算各列的平均值&#xff0c;并用该值填充该分类该列的nan值。DataFrame数据格式fillna方式实现groupby方式实现DataFrame数据格式以下是数据存储形式&#xff1a;fillna方式实现1、按照industryName1列&#xff0c;筛选出业绩2、筛…

HTMLTestRunner.py内容

HTMLTesstRunner.py 修改后内容如下&#xff1a; """ A TestRunner for use with the Python unit testing framework. It generates a HTML report to show the result at a glance.The simplest way to use this is to invoke its main method. E.g.import u…