百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

使用Tensorflow的多层感知器 tensorflow多机训练

bigegpt 2024-10-07 06:34 36 浏览

在这篇文章中,我们将使用TensorFlow构建一个神经网络(多层感知器)并成功训练它以识别图像中的数字。Tensorflow是一个非常流行的深度学习框架,该笔记将指导用这个库构建一个神经网络。如果你想了解什么是多层感知器,你可以看看以前的文章,用Numpy从头开始构建了一个多层感知器

让我们从导入数据开始。作为Keras,一个高级深度学习库已经将MNIST数据作为其默认数据的一部分,我们将从那里导入数据集并将其拆分为训练和测试集。Python代码如下:

## Loading MNIST dataset from keras
import keras
from sklearn.preprocessing import LabelBinarizer
import matplotlib.pyplot as plt
%matplotlib inline
 
def load_dataset(flatten=False):
 (X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
 
 # normalize x
 X_train = X_train.astype(float) / 255.
 X_test = X_test.astype(float) / 255.
 
 # we reserve the last 10000 training examples for validation
 X_train, X_val = X_train[:-10000], X_train[-10000:]
 y_train, y_val = y_train[:-10000], y_train[-10000:]
 
 if flatten:
 X_train = X_train.reshape([X_train.shape[0], -1])
 X_val = X_val.reshape([X_val.shape[0], -1])
 X_test = X_test.reshape([X_test.shape[0], -1])
 
 return X_train, y_train, X_val, y_val, X_test, y_test
 
X_train, y_train, X_val, y_val, X_test, y_test = load_dataset()
## Printing dimensions
print(X_train.shape, y_train.shape)
## Visualizing the first digit
plt.imshow(X_train[0], cmap="Greys");

如我们所见,当前数据的维数为n28x28,我们将首先在N*784中对图像进行flattening ,并对目标变量进行one-hot编码。Python代码如下:

## Changing dimension of input images from N*28*28 to N*784
X_train = X_train.reshape((X_train.shape[0],X_train.shape[1]*X_train.shape[2]))
X_test = X_test.reshape((X_test.shape[0],X_test.shape[1]*X_test.shape[2]))
 
print('Train dimension:');print(X_train.shape)
print('Test dimension:');print(X_test.shape)
 
## Changing labels to one-hot encoded vector
lb = LabelBinarizer()
y_train = lb.fit_transform(y_train)
y_test = lb.transform(y_test)
print('Train labels dimension:');print(y_train.shape)
print('Test labels dimension:');print(y_test.shape)

现在我们已经处理了数据,让我们开始使用tensorflow构建我们的多层感知器。我们将从导入所需的Python库开始。

## Importing required libraries
import numpy as np
import tensorflow as tf
from sklearn.metrics import roc_auc_score, accuracy_score
s = tf.InteractiveSession()

tf.InteractiveSession()是一种直接运行tensorflow模型的方法,无需在我们想要运行模型时实例化图形。我们将构建784(输入)-512(隐藏层1)-256(隐藏层2)-10(输出)神经网络模型。让我们通过定义初始化变量来开始我们的模型构建。Python代码如下:

## Defining various initialization parameters for 784-512-256-10 MLP model
num_classes = y_train.shape[1]
num_features = X_train.shape[1]
num_output = y_train.shape[1]
num_layers_0 = 512
num_layers_1 = 256
starter_learning_rate = 0.001
regularizer_rate = 0.1

在tensorflow中,我们为输入变量和输出变量以及我们想要跟踪的任何变量定义占位符。

# Placeholders for the input data
input_X = tf.placeholder('float32',shape =(None,num_features),name="input_X")
input_y = tf.placeholder('float32',shape = (None,num_classes),name='input_Y')
## for dropout layer
keep_prob = tf.placeholder(tf.float32)

由于dense 层需要权重和偏差,它们需要以零均值和小方差的随机正态分布初始化(1/square root of the number of features)。

## Weights initialized by random normal function with std_dev = 1/sqrt(number of input features)
weights_0 = tf.Variable(tf.random_normal([num_features,num_layers_0], stddev=(1/tf.sqrt(float(num_features)))))
bias_0 = tf.Variable(tf.random_normal([num_layers_0]))
 
weights_1 = tf.Variable(tf.random_normal([num_layers_0,num_layers_1], stddev=(1/tf.sqrt(float(num_layers_0)))))
bias_1 = tf.Variable(tf.random_normal([num_layers_1]))
 
weights_2 = tf.Variable(tf.random_normal([num_layers_1,num_output], stddev=(1/tf.sqrt(float(num_layers_1)))))
bias_2 = tf.Variable(tf.random_normal([num_output]))

现在我们将开始编写图计算以开发我们的784(输入)-512(隐藏层1)-256(隐藏层2)-10(输出)模型。我们将每层的输入乘以其各自的权重并添加偏差项。在权重和偏差之后,我们需要添加激活; 我们将对隐藏层使用ReLU激活,对最终输出层使用softmax以获得类概率分数。还要防止过度拟合; 让我们在每个隐藏层之后添加一些drop out。Dropout 是在我们的网络中创建冗余的一个基本概念,这可以带来更好的泛化。

## Initializing weigths and biases
hidden_output_0 = tf.nn.relu(tf.matmul(input_X,weights_0)+bias_0)
hidden_output_0_0 = tf.nn.dropout(hidden_output_0, keep_prob)
 
hidden_output_1 = tf.nn.relu(tf.matmul(hidden_output_0_0,weights_1)+bias_1)
hidden_output_1_1 = tf.nn.dropout(hidden_output_1, keep_prob)
 
predicted_y = tf.sigmoid(tf.matmul(hidden_output_1_1,weights_2) + bias_2)
现在我们需要定义一个损失函数来优化我们的权重和偏差,我们将使用带有logits的softmax交叉熵来预测和正确的标签。我们还将为我们的网络添加一些L2正则化。
## Defining the loss function
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=predicted_y,labels=input_y)) \
 + regularizer_rate*(tf.reduce_sum(tf.square(bias_0)) + tf.reduce_sum(tf.square(bias_1)))

现在我们需要为我们的网络定义一个优化器和学习率来优化给定损失函数上的权重和偏差。我们将使用指数衰减我们的学习率每5 epochs减少15%的学习。对于优化器,我们将使用Adam优化器。

## Variable learning rate
learning_rate = tf.train.exponential_decay(starter_learning_rate, 0, 5, 0.85, staircase=True)
## Adam optimzer for finding the right weight
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss,var_list=[weights_0,weights_1,weights_2,
 bias_0,bias_1,bias_2])

我们完成了模型构建。让我们定义精度度量来评估我们的模型性能,因为损失函数是非直观的。

## Metrics definition
correct_prediction = tf.equal(tf.argmax(y_train,1), tf.argmax(predicted_y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

我们现在将开始训练我们的训练数据网络并同时评估我们的测试数据集网络。我们将使用尺寸为128的批量优化,并将其训练为14个epochs,以获得98%以上的准确度。

## Training parameters
batch_size = 128
epochs=14
dropout_prob = 0.6
 
training_accuracy = []
training_loss = []
testing_accuracy = []
 
s.run(tf.global_variables_initializer())
for epoch in range(epochs): 
 arr = np.arange(X_train.shape[0])
 np.random.shuffle(arr)
 for index in range(0,X_train.shape[0],batch_size):
 s.run(optimizer, {input_X: X_train[arr[index:index+batch_size]],
 input_y: y_train[arr[index:index+batch_size]],
 keep_prob:dropout_prob})
 training_accuracy.append(s.run(accuracy, feed_dict= {input_X:X_train, 
 input_y: y_train,keep_prob:1}))
 training_loss.append(s.run(loss, {input_X: X_train, 
 input_y: y_train,keep_prob:1}))
 
 ## Evaluation of model
 testing_accuracy.append(accuracy_score(y_test.argmax(1), 
 s.run(predicted_y, {input_X: X_test,keep_prob:1}).argmax(1)))
 print("Epoch:{0}, Train loss: {1:.2f} Train acc: {2:.3f}, Test acc:{3:.3f}".format(epoch,
 training_loss[epoch],
 training_accuracy[epoch],
 testing_accuracy[epoch]))

让我们将可视化训练和测试准确率作为epoch的数量的函数。

## Plotting chart of training and testing accuracy as a function of iterations
iterations = list(range(epochs))
plt.plot(iterations, training_accuracy, label='Train')
plt.plot(iterations, testing_accuracy, label='Test')
plt.ylabel('Accuracy')
plt.xlabel('iterations')
plt.show()
print("Train Accuracy: {0:.2f}".format(training_accuracy[-1]))
print("Test Accuracy:{0:.2f}".format(testing_accuracy[-1]))

正如我们所看到的,我们已经成功地训练了一个多层感知器,它是用tensorflow编写的,具有很高的验证精度!

相关推荐

当Frida来“敲”门(frida是什么)

0x1渗透测试瓶颈目前,碰到越来越多的大客户都会将核心资产业务集中在统一的APP上,或者对自己比较重要的APP,如自己的主业务,办公APP进行加壳,流量加密,投入了很多精力在移动端的防护上。而现在挖...

服务端性能测试实战3-性能测试脚本开发

前言在前面的两篇文章中,我们分别介绍了性能测试的理论知识以及性能测试计划制定,本篇文章将重点介绍性能测试脚本开发。脚本开发将分为两个阶段:阶段一:了解各个接口的入参、出参,使用Python代码模拟前端...

Springboot整合Apache Ftpserver拓展功能及业务讲解(三)

今日分享每天分享技术实战干货,技术在于积累和收藏,希望可以帮助到您,同时也希望获得您的支持和关注。架构开源地址:https://gitee.com/msxyspringboot整合Ftpserver参...

Linux和Windows下:Python Crypto模块安装方式区别

一、Linux环境下:fromCrypto.SignatureimportPKCS1_v1_5如果导包报错:ImportError:Nomodulenamed'Crypt...

Python 3 加密简介(python des加密解密)

Python3的标准库中是没多少用来解决加密的,不过却有用于处理哈希的库。在这里我们会对其进行一个简单的介绍,但重点会放在两个第三方的软件包:PyCrypto和cryptography上,我...

怎样从零开始编译一个魔兽世界开源服务端Windows

第二章:编译和安装我是艾西,上期我们讲述到编译一个魔兽世界开源服务端环境准备,那么今天跟大家聊聊怎么编译和安装我们直接进入正题(上一章没有看到的小伙伴可以点我主页查看)编译服务端:在D盘新建一个文件夹...

附1-Conda部署安装及基本使用(conda安装教程)

Windows环境安装安装介质下载下载地址:https://www.anaconda.com/products/individual安装Anaconda安装时,选择自定义安装,选择自定义安装路径:配置...

如何配置全世界最小的 MySQL 服务器

配置全世界最小的MySQL服务器——如何在一块IntelEdison为控制板上安装一个MySQL服务器。介绍在我最近的一篇博文中,物联网,消息以及MySQL,我展示了如果Partic...

如何使用Github Action来自动化编译PolarDB-PG数据库

随着PolarDB在国产数据库领域荣膺桂冠并持续获得广泛认可,越来越多的学生和技术爱好者开始关注并涉足这款由阿里巴巴集团倾力打造且性能卓越的关系型云原生数据库。有很多同学想要上手尝试,却卡在了编译数据...

面向NDK开发者的Android 7.0变更(ndk android.mk)

订阅Google官方微信公众号:谷歌开发者。与谷歌一起创造未来!受Android平台其他改进的影响,为了方便加载本机代码,AndroidM和N中的动态链接器对编写整洁且跨平台兼容的本机...

信创改造--人大金仓(Kingbase)数据库安装、备份恢复的问题纪要

问题一:在安装KingbaseES时,安装用户对于安装路径需有“读”、“写”、“执行”的权限。在Linux系统中,需要以非root用户执行安装程序,且该用户要有标准的home目录,您可...

OpenSSH 安全漏洞,修补操作一手掌握

1.漏洞概述近日,国家信息安全漏洞库(CNNVD)收到关于OpenSSH安全漏洞(CNNVD-202407-017、CVE-2024-6387)情况的报送。攻击者可以利用该漏洞在无需认证的情况下,通...

Linux:lsof命令详解(linux lsof命令详解)

介绍欢迎来到这篇博客。在这篇博客中,我们将学习Unix/Linux系统上的lsof命令行工具。命令行工具是您使用CLI(命令行界面)而不是GUI(图形用户界面)运行的程序或工具。lsoflsof代表&...

幻隐说固态第一期:固态硬盘接口类别

前排声明所有信息来源于网络收集,如有错误请评论区指出更正。废话不多说,目前固态硬盘接口按速度由慢到快分有这几类:SATA、mSATA、SATAExpress、PCI-E、m.2、u.2。下面我们来...

新品轰炸 影驰SSD多款产品登Computex

分享泡泡网SSD固态硬盘频道6月6日台北电脑展作为全球第二、亚洲最大的3C/IT产业链专业展,吸引了众多IT厂商和全球各地媒体的热烈关注,全球存储新势力—影驰,也积极参与其中,为广大玩家朋友带来了...