#3.1 模块与数据的导入 #步骤 1 引入本次实验需求的模块 from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split import tensorflow as tf import os #步骤 2 导入数据,载入鸢尾花数据集,本数据集共有 150 个带标签的数据 iris = load_iris() #步骤 3 将数据集分为训练集 135 条,测试集 15 条 iris_train, iris_test, target_train, target_test = train_test_split(iris.data, iris.target, test_size=0.1) #3.2 制作容易被 tensorflow 数据迭代器 #步骤 1 制作训练数据与测试数据的 python 迭代器 def generate_train(): for i, j in zip(iris_train, target_train): yield (i, j) def generate_test(): for i, j in zip(iris_test, target_test): yield (i, j) #步骤 2 转化为 tensorflow 可识别的模式 def iter_data(generator): # 转化成tf.data 格式 data = tf.data.Dataset.from_generator(generator=generator, output_types=(tf.float32,tf.int32), output_shapes=(tf.TensorShape([4]), tf.TensorShape([]))) # 将数据流转化成一批一批的,设定batch_size,每组十条数据 data= data.batch(batch_size=5) # 创建数据集的迭代器 每次返回一个张量数据 return data # 分别生成tensorflow 可识别的训练集,测试集的迭代器 iter_train = iter_data(generate_train) iter_test = iter_data(generate_test) #3.3 构建神经网络,损失函数和优化器 #步骤 1 构建 3 层 DNN 模型,外加一层 dropout 层 model = tf.keras.Sequential([ # 第一层网络必须要有input_shape tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(4,)), # 输入 10,输出 10 tf.keras.layers.Dense(10, activation=tf.nn.relu), # 增加 dropout 正则层 tf.keras.layers.Dropout(0.5), # 输入 10,输出 3,对应 3 分类 tf.keras.layers.Dense(3)]) #步骤 2 定义模型的损失值 def loss(model, x,y): y_= model(x) # 返回交叉熵损失 return tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=y_) #步骤 3 计算模型的梯度值 def grad(model, inputs, targets): with tf.GradientTape() as tape: loss_value = loss(model, inputs, targets) return loss_value, tape.gradient(loss_value, model.trainable_variables) #步骤 4 构建优化器,本实验使用了 SGD 作为优化器 # optimizer = tf.keras.optimizers.Adam(learning_rate=0.01) # optimizer = tf.keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-06) #optimizer = tf.keras.optimizers.SGD(lr=0.01, momentum=0.01, decay=0.01, nesterov=False) optimizer = tf.keras.optimizers.SGD(learning_rate=0.01) #3.4 构建训练函数并训练 #步骤 1 构建训练模型 def train_model(training_dataset, model, optimizer): # 将所有数据集训练 200 次 for epoch in range(1, 201): epoch_loss_avg = tf.metrics.Mean() epoch_accuracy = tf.metrics.Accuracy() # 每次训练将一批(batch)的数据传入优化器, # 在本次训练中共有 135 条数据,每批 5 条,所以传 27 轮 for feature, label in training_dataset: # 计算模型的损失与对应的梯度 loss, gradients = grad(model, feature, label) # 讲梯度传入优化器进行反向训练 # 参数:grads_and_vars 梯度与所有变量的组合 # 参数:global_step,变量更新后用于增加的变量 optimizer.apply_gradients(grads_and_vars=zip(gradients, model.variables)) # 计算本批次数据损失的均值 epoch_loss_avg(loss) # 返回最有可能的分类 epoch_maxprob_output = tf.argmax(model(feature), axis=1, output_type=tf.int32) # 计算本批次预测的准确性 epoch_accuracy(epoch_maxprob_output, label) # 每 50 轮完整训练打印一次数据 if epoch % 10 == 0: print("Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}".format(epoch, epoch_loss_avg.result(), epoch_accuracy.result())) print('model training finished') #步骤 2 训练模型 train_model(iter_train, model,optimizer) #3.5 构建测试函数并测试 #步骤 1 构建测试函数 def test_model(test_dataset, model): for test_feature, test_label in test_dataset: Prediction = tf.argmax(model(test_feature), axis=1, output_type=tf.int32) Acc = tf.metrics.Accuracy() Acc(Prediction, test_label) print("Prediction, labels, accuracy: {},{},{:.3%}". format(Prediction, test_label, Acc.result())) #步骤 2 使用测试集评估 test_model(iter_test, model) #3.6 保存模型 #步骤 1 保存模型 # 创建模型保存文件夹 if not os.path.exists('./model/'): os.mkdir('./model/') # 训练完之后保存模型 model.save(filepath='./model/DNN.HDF5')
鸢尾花识别更正
最新推荐文章于 2023-06-11 23:13:50 发布