-
2020-12-06 13:30:19
我很难用Pybrain训练DBN。
首先我试着用简单的方法:net = buildNetwork(*layerDims)
所以我试着从头开始定义一个网络!在inp = LinearLayer(3 , 'visible')
hidden0 = SigmoidLayer(2 , 'hidden0')
hidden1= SigmoidLayer(2 , 'hidden1')
output = LinearLayer(2 , 'output')
bias = BiasUnit('bias')
net = Network()
net.addInputModule(inp)
net.addModule(hidden0)
net.addModule(hidden1)
net.addModule(output)
net.addModule(bias)
net.addConnection(FullConnection(inp, hidden0))
net.addConnection(FullConnection(hidden0, hidden1))
net.addConnection(FullConnection(hidden1, output))
net.addConnection(FullConnection(bias, hidden0))
net.addConnection(FullConnection(bias, hidden1))
net.addConnection(FullConnection(bias, output))
net.sortModules()
当我跑的时候:trainer = deepbelief.DeepBeliefTrainer(net1, dataset=ds)
trainer.trainEpochs(epochs)
我看到了这个错误:File "/home/WORK/Canopy_64bit/User/lib/python2.7/site-packages/PyBrain-0.3.1-py2.7.egg/pybrain/structure/connections/connection.py", line 37, in __init__
self.outSliceTo = outmod.indim
AttributeError: 'NoneType' object has no attribute 'indim'
这与相关RBM中的隐藏层有关。在
我是不是少了点什么?在
更多相关内容 -
基于python的深度信念网络
2019-01-02 16:19:12深度信念(置信)网络(DBN),使用python开发环境,代码思路清晰,易调试。有问题可以留言相互交流 -
基于Python的深度信念网络程序
2018-11-25 17:36:08自己编写的深度信念网络模型程序,可以直接调用。本人用DBN进行了光伏发电预测,效果很好。 -
python深度信念网实现
2020-03-08 10:35:46python深度信念网实现,python深度信念网实现,python深度信念网实现,python深度信念网实现,python深度信念网实现,python深度信念网实现,python深度信念网实现, -
深度信念网络python
2020-12-16 14:46:49《深度学习导论及案例分析》一导读PREFACE前言“深度学习”一词大家已经不陌生了,随着在不同领域取得了超越其他方法的成功,深度学习在学术界和工业界掀起了一次神经网络发展史上的新浪潮。运用深度学习解决实际...《深度学习导论及案例分析》一导读
PREFACE
前言
“深度学习”一词大家已经不陌生了,随着在不同领域取得了超越其他方法的成功,深度学习在学术界和工业界掀起了一次神经网络发展史上的新浪潮。运用深度学习解决实际问题,不仅是学术界高素质人才所需的技能,而且是工业界商业巨头进行竞争的核心武器。为适应这一发展的需要,作者以长期的相关研究...
文章
华章计算机
2017-05-02
1434浏览量
Keras作者、谷歌研究员Chollet:深度学习的理论局限
本文来自AI新媒体量子位(QbitAI)
从图像处理,到自然语言处理,再到语音识别等多个领域,深度学习都取得了很好的成绩,但是仍存在一些领域,还等待深度学习去攻坚克难。
Keras作者Francois Chollet昨天在博客上发布了一篇文章,讲述了当下深度学习理论的局限性及发展方向。这篇文章...
文章
行者武松
2018-01-08
837浏览量
清华大学发布珠算:一个用于生成模型的Python库
5 月 27-28 日,机器之心主办的第一届全球机器智能峰会(GMIS 2017)将在北京 898 创新空间举行。在峰会第一天下午的「机器学习」主题 Session 上,清华大学副教授朱军将分享解读《珠算:贝叶斯深度学习的 GPU 库(ZhuSuan: a GPU Library for Baye...
文章
科技小能手
2017-11-12
1037浏览量
清华大学发布珠算:一个用于生成模型的Python库
5 月 27-28 日,机器之心主办的第一届全球机器智能峰会(GMIS 2017)将在北京 898 创新空间举行。在峰会第一天下午的「机器学习」主题 Session 上,清华大学副教授朱军将分享解读《珠算:贝叶斯深度学习的 GPU 库(ZhuSuan: a GPU Library for Baye...
文章
科技小能手
2017-11-12
1006浏览量
这些深度学习术语,你了解多少?(上)
对于一个新手来说,深度学习术语可能非常难以理解。本表试图解释深度学习常用术语并链接到原始参考,以帮助读者深入了解特定主题。
深度学习与“一般”的机器学习术语之间的界限非常模糊。例如,我这里不包括“交叉验证”,因为它是一种通用技术,用于整个机器学习。但是,我加入了softmax或word2vec等术...
文章
【方向】
2018-10-20
1876浏览量
进入深度学习之前,想清楚这些问题!
特别说明:这篇文章是为了解决那些对于深度学习完全陌生并且正在计划进入这个领域的人。其目的是帮助他们批判性地思考该领域的复杂性,并帮助他们区分哪些是真正困难的事情,哪些是微不足道的事情。在我撰写和发表这篇文章时,我意识到这篇文章的语气过于挑衅,而且我不是一个好的作家,没有能力写一篇发人深省的文章。所...
文章
【方向】
2018-05-28
1729浏览量
教程 | 一文读懂自学机器学习的误区和陷阱(附学习资料)
来源:机器学习与统计学
文章来源:微信公众号 数据派THU
本文为你指出一些自学的误区,推荐学习资料,提供客观可行的学习表并给出进阶学习的建议。
0. 背景
写这篇教程的初衷是很多朋友都想了解如何入门/转行机器学习,搭上人工智能这列二十一世纪的快车。文章的宗旨是:1. 指出一些自学的误区 2....
文章
初商
2019-08-22
3747浏览量
带你读《Python机器学习》之一:机器学习基础
智能系统与技术丛书点击查看第二章点击查看第三章Python机器学习
赵涓涓 强 彦 主编第1章
机器学习基础
1.1 引论
在本书开篇之前,读者首先需要明白一个问题:机器学习有什么重要性,以至于需要学习这本书呢?那么接下来的两张图片,希望可以帮助大家解决这个首要问题。图1-1所展示的三位学者是当...
文章
温柔的养猫人
2019-11-16
1609浏览量
手把手教你在多种无监督聚类算法实现Python(附代码)
无监督学习是一类用于在数据中寻找模式的机器学习技术。无监督学习算法使用的输入数据都是没有标注过的,这意味着数据只给出了输入变量(自变量 X)而没有给出相应的输出变量(因变量)。在无监督学习中,算法本身将发掘数据中有趣的结构。
人工智能研究的领军人物 Yan Lecun,解释道:无监督学习能够自己...
文章
技术小能手
2018-06-01
8092浏览量
惊!C++竟然还能有这种操作——高性能深度学习库(DLL)
更多深度文章,请关注云计算频道:https://yq.aliyun.com/cloud
作为一个深度学习的老司机,你是不是以为只有Python才能够玩转深度学习?如果是这样的话,那么本文作者可能就要教你怎么“做人”了。毕竟大牛的世界我们不懂!
第一个版本C++的深度学习库(DLL)1.0发布...
文章
【方向】
2017-10-08
4126浏览量
超全!基于Java的机器学习项目、环境、库...
你是一名希望开始或者正在学习机器学习的Java程序员吗?
利用机器学习编写程序是最佳的学习方式。你可以从头开始编写算法,但是利用现有的开源库,你可以取得更大的进步。
本文介绍了主要的平台和开放源码的机器学习库。你可以使用这些机器学习库。
环境
本节描述了用于机器学习的Java环境或工作域。它们提供...
文章
技术小能手
2017-12-06
29778浏览量
干货 | Google发布官方中文版机器学习术语表
A
一种统计方法,用于将两种或多种技术进行比较,通常是将当前采用的技术与新技术进行比较。A/B 测试不仅旨在确定哪种技术的效果更好,而且还有助于了解相应差异是否具有显著的统计意义。A/B 测试通常是采用一种衡量方式对两种技术进行比较,但也适用于任意有限数量的技术和衡量方式。
准确率 (accura...
文章
技术小能手
2018-03-28
2456浏览量
如何看待和学习人工智能?这是五位哈佛博士生的AMA
本文来自AI新媒体量子位(QbitAI)
最近,五位哈佛的在读博士生集体来到著名社区reddit,展开一场围绕人工智能和认知科学的AMA(Ask Me Anything)。
简单介绍一下这几位博士生:Rockwell Anyoha来自分子生物学系;Dana Boebinger、Kevin Si...
文章
行者武松
2018-01-18
886浏览量
神经网络基础知识笔记
神经网络表示
神经元模型
神经网络从大脑的工作原理得到启发,可用于解决通用的学习问题。神经网络的基本组成单元是神经元(neuron)。每个神经元具有一个轴突和多个树突。每个连接到本神经元的树突都是一个输入,当所有输入树突的兴奋水平之和超过某一阈值,神经元就会被激活。激活的神经元会沿着其轴突发射信号...
文章
墨航
2017-05-16
3733浏览量
2020 云原生 7 大趋势预测
(作者排名不分先后)作者:叔同、谷朴、不瞋、育睿、许晓斌、至简、典违、鲁直、改之、小剑、汤志敏、白慕、循环、文卿,喽哥、水鸟、神秀
过去的几年,是云原生技术和理念得到广泛接受的几年。在这个快速发展的领域,预测未来显得尤其困难,但是我们又有着一些坚定的信念,相信以开放创新为支撑的云原生领域会持续重塑...
文章
檸,铮
2020-01-16
918浏览量
-
深度信念网络分类算法python程序.docx
2020-07-06 18:18:38深度信念网络分类算法,内含受限玻尔兹曼机训练、BP分类微调拟合,最终完成深度信念网络分类算法的训练。算法以Python语言完成,包含多个子文件,全部写入该word文档。文档注释详细,适合学习。 -
深度信念网络回归算法Python程序.docx
2020-07-06 17:08:55深度信念网络回归算法,内含受限玻尔兹曼机训练、BP微调拟合,最终完成深度信念网络回归算法的训练。算法以Python语言完成,包含多个子文件,全部写入该word文档。 -
dbn-cuda:GPU加速深度信念网络
2021-06-04 16:24:25Python 中的 GPU 加速深度信念网络 来自: 在机器学习中,深度信念网络 (DBN) 是一种生成图形模型,或者是一种深度神经网络,由多层潜在变量(“隐藏单元”)组成,层之间有连接,但内部的单元之间没有连接。每一... -
深度置信网络python3实现
2020-11-30 14:26:11Github源码地址:https://github.com/myme5261314/dbn_tf,源项目是由python2编写的,介绍如何转化为在python3环境下运行 首先要将rbm_MNIST_test.py两个print语句分别加上括号 运行rbm_MNIST_test.py文件,首先会...- Github源码地址:https://github.com/myme5261314/dbn_tf,源项目是由python2编写的,介绍如何转化为在python3环境下运行
- 首先要将rbm_MNIST_test.py两个print语句分别加上括号
- 运行rbm_MNIST_test.py文件,首先会出现No module named 'Image’错误,将rbm_MNIST_test.py中的import Image修改为from PIL import Image(需要先安装pillow库)
- 再次运行出现以下错误,解决方法为打开input_data.py,修改_read32()函数
def _read32(bytestream): dt = numpy.dtype(numpy.uint32).newbyteorder('>') return numpy.frombuffer(bytestream.read(4), dtype=dt)
修改为:
def _read32(bytestream): dt = numpy.dtype(numpy.uint32).newbyteorder('>') return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
- 修改后运行可能出现 module ‘tensorflow’ has no attribute 'placeholder’的错误,将rbm_MNIST_test.py中的import tensorflow as tf变成
import tensorflow.compat.v1 as tf tf.disable_v2_behavior()
- 运行rbm_MNIST_test.py,得到输出结果
-
Python 3深度置信网络(DBN)在Tensorflow中的实现MNIST手写数字识别
2021-04-17 14:09:50Deep Learning with TensorFlow IBM Cognitive Class ML0120EN Module 5 - Autoencoders 使用DBN识别手写体 ...深度置信网络可以通过额外的预训练规程解决局部最小值的问题。 预训练在反向传播之.任何程序错误,以及技术疑问或需要解答的,请扫码添加作者VX:1755337994
使用DBN识别手写体
传统的多层感知机或者神经网络的一个问题: 反向传播可能总是导致局部最小值。
当误差表面(error surface)包含了多个凹槽,当你做梯度下降时,你找到的并不是最深的凹槽。 下面你将会看到DBN是怎么解决这个问题的。深度置信网络
深度置信网络可以通过额外的预训练规程解决局部最小值的问题。 预训练在反向传播之前做完,这样可以使错误率离最优的解不是那么远,也就是我们在最优解的附近。再通过反向传播慢慢地降低错误率。
深度置信网络主要分成两部分。第一部分是多层玻尔兹曼感知机,用于预训练我们的网络。第二部分是前馈反向传播网络,这可以使RBM堆叠的网络更加精细化。1. 加载必要的深度置信网络库
# urllib is used to download the utils file from deeplearning.net import urllib.request response = urllib.request.urlopen('http://deeplearning.net/tutorial/code/utils.py') content = response.read().decode('utf-8') target = open('utils.py', 'w') target.write(content) target.close() # Import the math function for calculations import math # Tensorflow library. Used to implement machine learning models import tensorflow as tf # Numpy contains helpful functions for efficient mathematical calculations import numpy as np # Image library for image manipulation from PIL import Image # import Image # Utils file from utils import tile_raster_images
2. 构建RBM层
RBM的细节参考【受限玻尔兹曼机(RBM)与python在Tensorflow的实现_青年夏日科技的博客-CSDN博客_python玻尔兹曼机】
为了在Tensorflow中应用DBN, 下面创建一个RBM的类class RBM(object): def __init__(self, input_size, output_size): # Defining the hyperparameters self._input_size = input_size # Size of input self._output_size = output_size # Size of output self.epochs = 5 # Amount of training iterations self.learning_rate = 1.0 # The step used in gradient descent self.batchsize = 100 # The size of how much data will be used for training per sub iteration # Initializing weights and biases as matrices full of zeroes self.w = np.zeros([input_size, output_size], np.float32) # Creates and initializes the weights with 0 self.hb = np.zeros([output_size], np.float32) # Creates and initializes the hidden biases with 0 self.vb = np.zeros([input_size], np.float32) # Creates and initializes the visible biases with 0 # Fits the result from the weighted visible layer plus the bias into a sigmoid curve def prob_h_given_v(self, visible, w, hb): # Sigmoid return tf.nn.sigmoid(tf.matmul(visible, w) + hb) # Fits the result from the weighted hidden layer plus the bias into a sigmoid curve def prob_v_given_h(self, hidden, w, vb): return tf.nn.sigmoid(tf.matmul(hidden, tf.transpose(w)) + vb) # Generate the sample probability def sample_prob(self, probs): return tf.nn.relu(tf.sign(probs - tf.random_uniform(tf.shape(probs)))) # Training method for the model def train(self, X): # Create the placeholders for our parameters _w = tf.placeholder("float", [self._input_size, self._output_size]) _hb = tf.placeholder("float", [self._output_size]) _vb = tf.placeholder("float", [self._input_size]) prv_w = np.zeros([self._input_size, self._output_size], np.float32) # Creates and initializes the weights with 0 prv_hb = np.zeros([self._output_size], np.float32) # Creates and initializes the hidden biases with 0 prv_vb = np.zeros([self._input_size], np.float32) # Creates and initializes the visible biases with 0 cur_w = np.zeros([self._input_size, self._output_size], np.float32) cur_hb = np.zeros([self._output_size], np.float32) cur_vb = np.zeros([self._input_size], np.float32) v0 = tf.placeholder("float", [None, self._input_size]) # Initialize with sample probabilities h0 = self.sample_prob(self.prob_h_given_v(v0, _w, _hb)) v1 = self.sample_prob(self.prob_v_given_h(h0, _w, _vb)) h1 = self.prob_h_given_v(v1, _w, _hb) # Create the Gradients positive_grad = tf.matmul(tf.transpose(v0), h0) negative_grad = tf.matmul(tf.transpose(v1), h1) # Update learning rates for the layers update_w = _w + self.learning_rate * (positive_grad - negative_grad) / tf.to_float(tf.shape(v0)[0]) update_vb = _vb + self.learning_rate * tf.reduce_mean(v0 - v1, 0) update_hb = _hb + self.learning_rate * tf.reduce_mean(h0 - h1, 0) # Find the error rate err = tf.reduce_mean(tf.square(v0 - v1)) # Training loop with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # For each epoch for epoch in range(self.epochs): # For each step/batch for start, end in zip(range(0, len(X), self.batchsize), range(self.batchsize, len(X), self.batchsize)): batch = X[start:end] # Update the rates cur_w = sess.run(update_w, feed_dict={v0: batch, _w: prv_w, _hb: prv_hb, _vb: prv_vb}) cur_hb = sess.run(update_hb, feed_dict={v0: batch, _w: prv_w, _hb: prv_hb, _vb: prv_vb}) cur_vb = sess.run(update_vb, feed_dict={v0: batch, _w: prv_w, _hb: prv_hb, _vb: prv_vb}) prv_w = cur_w prv_hb = cur_hb prv_vb = cur_vb error = sess.run(err, feed_dict={v0: X, _w: cur_w, _vb: cur_vb, _hb: cur_hb}) print('Epoch: %d' % epoch, 'reconstruction error: %f' % error) self.w = prv_w self.hb = prv_hb self.vb = prv_vb # Create expected output for our DBN def rbm_outpt(self, X): input_X = tf.constant(X) _w = tf.constant(self.w) _hb = tf.constant(self.hb) out = tf.nn.sigmoid(tf.matmul(input_X, _w) + _hb) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) return sess.run(out)
3. 导入MNIST数据
使用one-hot encoding标注的形式载入MNIST图像数据。
# Getting the MNIST data provided by Tensorflow from tensorflow.examples.tutorials.mnist import input_data # Loading in the mnist data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images,\ mnist.test.labels
Extracting MNIST_data/train-images-idx3-ubyte.gz Extracting MNIST_data/train-labels-idx1-ubyte.gz Extracting MNIST_data/t10k-images-idx3-ubyte.gz Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
4. 建立DBN
RBM_hidden_sizes = [500, 200 , 50 ] #create 4 layers of RBM with size 785-500-200-50 #Since we are training, set input as training data inpX = trX #Create list to hold our RBMs rbm_list = [] #Size of inputs is the number of inputs in the training set input_size = inpX.shape[1] #For each RBM we want to generate for i, size in enumerate(RBM_hidden_sizes): print('RBM: ',i,' ',input_size,'->', size) rbm_list.append(RBM(input_size, size)) input_size = size
Extracting MNIST_data/train-images-idx3-ubyte.gz Extracting MNIST_data/train-labels-idx1-ubyte.gz Extracting MNIST_data/t10k-images-idx3-ubyte.gz Extracting MNIST_data/t10k-labels-idx1-ubyte.gz RBM: 0 784 -> 500 RBM: 1 500 -> 200 RBM: 2 200 -> 50
rbm的类创建好了和数据都已经载入,可以创建DBN。 在这个例子中,我们使用了3个RBM,一个的隐藏层单元个数为500, 第二个RBM的隐藏层个数为200,最后一个为50. 我们想要生成训练数据的深层次表示形式。
5.训练RBM
我们将使用***rbm.train()***开始预训练步骤, 单独训练堆中的每一个RBM,并将当前RBM的输出作为下一个RBM的输入。
#For each RBM in our list for rbm in rbm_list: print('New RBM:') #Train a new one rbm.train(inpX) #Return the output layer inpX = rbm.rbm_outpt(inpX)
New RBM: Epoch: 0 reconstruction error: 0.061174 Epoch: 1 reconstruction error: 0.052962 Epoch: 2 reconstruction error: 0.049679 Epoch: 3 reconstruction error: 0.047683 Epoch: 4 reconstruction error: 0.045691 New RBM: Epoch: 0 reconstruction error: 0.035260 Epoch: 1 reconstruction error: 0.030811 Epoch: 2 reconstruction error: 0.028873 Epoch: 3 reconstruction error: 0.027428 Epoch: 4 reconstruction error: 0.026980 New RBM: Epoch: 0 reconstruction error: 0.059593 Epoch: 1 reconstruction error: 0.056837 Epoch: 2 reconstruction error: 0.055571 Epoch: 3 reconstruction error: 0.053817 Epoch: 4 reconstruction error: 0.054142
现在我们可以将输入数据的学习好的表示转换为有监督的预测,比如一个线性分类器。特别地,我们使用这个浅层神经网络的最后一层的输出对数字分类。
6. 神经网络
下面的类使用了上面预训练好的RBMs实现神经网络。
import numpy as np import math import tensorflow as tf class NN(object): def __init__(self, sizes, X, Y): # Initialize hyperparameters self._sizes = sizes self._X = X self._Y = Y self.w_list = [] self.b_list = [] self._learning_rate = 1.0 self._momentum = 0.0 self._epoches = 10 self._batchsize = 100 input_size = X.shape[1] # initialization loop for size in self._sizes + [Y.shape[1]]: # Define upper limit for the uniform distribution range max_range = 4 * math.sqrt(6. / (input_size + size)) # Initialize weights through a random uniform distribution self.w_list.append( np.random.uniform(-max_range, max_range, [input_size, size]).astype(np.float32)) # Initialize bias as zeroes self.b_list.append(np.zeros([size], np.float32)) input_size = size # load data from rbm def load_from_rbms(self, dbn_sizes, rbm_list): # Check if expected sizes are correct assert len(dbn_sizes) == len(self._sizes) for i in range(len(self._sizes)): # Check if for each RBN the expected sizes are correct assert dbn_sizes[i] == self._sizes[i] # If everything is correct, bring over the weights and biases for i in range(len(self._sizes)): self.w_list[i] = rbm_list[i].w self.b_list[i] = rbm_list[i].hb # Training method def train(self): # Create placeholders for input, weights, biases, output _a = [None] * (len(self._sizes) + 2) _w = [None] * (len(self._sizes) + 1) _b = [None] * (len(self._sizes) + 1) _a[0] = tf.placeholder("float", [None, self._X.shape[1]]) y = tf.placeholder("float", [None, self._Y.shape[1]]) # Define variables and activation functoin for i in range(len(self._sizes) + 1): _w[i] = tf.Variable(self.w_list[i]) _b[i] = tf.Variable(self.b_list[i]) for i in range(1, len(self._sizes) + 2): _a[i] = tf.nn.sigmoid(tf.matmul(_a[i - 1], _w[i - 1]) + _b[i - 1]) # Define the cost function cost = tf.reduce_mean(tf.square(_a[-1] - y)) # Define the training operation (Momentum Optimizer minimizing the Cost function) train_op = tf.train.MomentumOptimizer( self._learning_rate, self._momentum).minimize(cost) # Prediction operation predict_op = tf.argmax(_a[-1], 1) # Training Loop with tf.Session() as sess: # Initialize Variables sess.run(tf.global_variables_initializer()) # For each epoch for i in range(self._epoches): # For each step for start, end in zip( range(0, len(self._X), self._batchsize), range(self._batchsize, len(self._X), self._batchsize)): # Run the training operation on the input data sess.run(train_op, feed_dict={ _a[0]: self._X[start:end], y: self._Y[start:end]}) for j in range(len(self._sizes) + 1): # Retrieve weights and biases self.w_list[j] = sess.run(_w[j]) self.b_list[j] = sess.run(_b[j]) print("Accuracy rating for epoch " + str(i) + ": " + str(np.mean(np.argmax(self._Y, axis=1) == \ sess.run(predict_op, feed_dict={_a[0]: self._X, y: self._Y}))))
7. 运行
nNet = NN(RBM_hidden_sizes, trX, trY) nNet.load_from_rbms(RBM_hidden_sizes,rbm_list) nNet.train()
Accuracy rating for epoch 0: 0.46683636363636366 Accuracy rating for epoch 1: 0.6561272727272728 Accuracy rating for epoch 2: 0.7678363636363637 Accuracy rating for epoch 3: 0.8370727272727273 Accuracy rating for epoch 4: 0.8684181818181819 Accuracy rating for epoch 5: 0.885 Accuracy rating for epoch 6: 0.8947636363636363 Accuracy rating for epoch 7: 0.9024909090909091 Accuracy rating for epoch 8: 0.9080363636363636 Accuracy rating for epoch 9: 0.9124181818181818
完整代码
pip install tensorflow==1.13.1
# Import the math function for calculations import math # Tensorflow library. Used to implement machine learning models import tensorflow as tf # Numpy contains helpful functions for efficient mathematical calculations import numpy as np # Image library for image manipulation # import Image # Utils file # Getting the MNIST data provided by Tensorflow from tensorflow.examples.tutorials.mnist import input_data """ This file contains different utility functions that are not connected in anyway to the networks presented in the tutorials, but rather help in processing the outputs into a more understandable way. For example ``tile_raster_images`` helps in generating a easy to grasp image from a set of samples or weights. """ import numpy def scale_to_unit_interval(ndar, eps=1e-8): """ Scales all values in the ndarray ndar to be between 0 and 1 """ ndar = ndar.copy() ndar -= ndar.min() ndar *= 1.0 / (ndar.max() + eps) return ndar def tile_raster_images(X, img_shape, tile_shape, tile_spacing=(0, 0), scale_rows_to_unit_interval=True, output_pixel_vals=True): """ Transform an array with one flattened image per row, into an array in which images are reshaped and layed out like tiles on a floor. This function is useful for visualizing datasets whose rows are images, and also columns of matrices for transforming those rows (such as the first layer of a neural net). :type X: a 2-D ndarray or a tuple of 4 channels, elements of which can be 2-D ndarrays or None; :param X: a 2-D array in which every row is a flattened image. :type img_shape: tuple; (height, width) :param img_shape: the original shape of each image :type tile_shape: tuple; (rows, cols) :param tile_shape: the number of images to tile (rows, cols) :param output_pixel_vals: if output should be pixel values (i.e. int8 values) or floats :param scale_rows_to_unit_interval: if the values need to be scaled before being plotted to [0,1] or not :returns: array suitable for viewing as an image. (See:`Image.fromarray`.) :rtype: a 2-d array with same dtype as X. """ assert len(img_shape) == 2 assert len(tile_shape) == 2 assert len(tile_spacing) == 2 # The expression below can be re-written in a more C style as # follows : # # out_shape = [0,0] # out_shape[0] = (img_shape[0]+tile_spacing[0])*tile_shape[0] - # tile_spacing[0] # out_shape[1] = (img_shape[1]+tile_spacing[1])*tile_shape[1] - # tile_spacing[1] out_shape = [ (ishp + tsp) * tshp - tsp for ishp, tshp, tsp in zip(img_shape, tile_shape, tile_spacing) ] if isinstance(X, tuple): assert len(X) == 4 # Create an output numpy ndarray to store the image if output_pixel_vals: out_array = numpy.zeros((out_shape[0], out_shape[1], 4), dtype='uint8') else: out_array = numpy.zeros((out_shape[0], out_shape[1], 4), dtype=X.dtype) #colors default to 0, alpha defaults to 1 (opaque) if output_pixel_vals: channel_defaults = [0, 0, 0, 255] else: channel_defaults = [0., 0., 0., 1.] for i in range(4): if X[i] is None: # if channel is None, fill it with zeros of the correct # dtype dt = out_array.dtype if output_pixel_vals: dt = 'uint8' out_array[:, :, i] = numpy.zeros( out_shape, dtype=dt ) + channel_defaults[i] else: # use a recurrent call to compute the channel and store it # in the output out_array[:, :, i] = tile_raster_images( X[i], img_shape, tile_shape, tile_spacing, scale_rows_to_unit_interval, output_pixel_vals) return out_array else: # if we are dealing with only one channel H, W = img_shape Hs, Ws = tile_spacing # generate a matrix to store the output dt = X.dtype if output_pixel_vals: dt = 'uint8' out_array = numpy.zeros(out_shape, dtype=dt) for tile_row in range(tile_shape[0]): for tile_col in range(tile_shape[1]): if tile_row * tile_shape[1] + tile_col < X.shape[0]: this_x = X[tile_row * tile_shape[1] + tile_col] if scale_rows_to_unit_interval: # if we should scale values to be between 0 and 1 # do this by calling the `scale_to_unit_interval` # function this_img = scale_to_unit_interval( this_x.reshape(img_shape)) else: this_img = this_x.reshape(img_shape) # add the slice to the corresponding position in the # output array c = 1 if output_pixel_vals: c = 255 out_array[ tile_row * (H + Hs): tile_row * (H + Hs) + H, tile_col * (W + Ws): tile_col * (W + Ws) + W ] = this_img * c return out_array # Class that defines the behavior of the RBM class RBM(object): def __init__(self, input_size, output_size): # Defining the hyperparameters self._input_size = input_size # Size of input self._output_size = output_size # Size of output self.epochs = 5 # Amount of training iterations self.learning_rate = 1.0 # The step used in gradient descent self.batchsize = 100 # The size of how much data will be used for training per sub iteration # Initializing weights and biases as matrices full of zeroes self.w = np.zeros([input_size, output_size], np.float32) # Creates and initializes the weights with 0 self.hb = np.zeros([output_size], np.float32) # Creates and initializes the hidden biases with 0 self.vb = np.zeros([input_size], np.float32) # Creates and initializes the visible biases with 0 # Fits the result from the weighted visible layer plus the bias into a sigmoid curve def prob_h_given_v(self, visible, w, hb): # Sigmoid return tf.nn.sigmoid(tf.matmul(visible, w) + hb) # Fits the result from the weighted hidden layer plus the bias into a sigmoid curve def prob_v_given_h(self, hidden, w, vb): return tf.nn.sigmoid(tf.matmul(hidden, tf.transpose(w)) + vb) # Generate the sample probability def sample_prob(self, probs): return tf.nn.relu(tf.sign(probs - tf.random_uniform(tf.shape(probs)))) # Training method for the model def train(self, X): # Create the placeholders for our parameters _w = tf.placeholder("float", [self._input_size, self._output_size]) _hb = tf.placeholder("float", [self._output_size]) _vb = tf.placeholder("float", [self._input_size]) prv_w = np.zeros([self._input_size, self._output_size], np.float32) # Creates and initializes the weights with 0 prv_hb = np.zeros([self._output_size], np.float32) # Creates and initializes the hidden biases with 0 prv_vb = np.zeros([self._input_size], np.float32) # Creates and initializes the visible biases with 0 cur_w = np.zeros([self._input_size, self._output_size], np.float32) cur_hb = np.zeros([self._output_size], np.float32) cur_vb = np.zeros([self._input_size], np.float32) v0 = tf.placeholder("float", [None, self._input_size]) # Initialize with sample probabilities h0 = self.sample_prob(self.prob_h_given_v(v0, _w, _hb)) v1 = self.sample_prob(self.prob_v_given_h(h0, _w, _vb)) h1 = self.prob_h_given_v(v1, _w, _hb) # Create the Gradients positive_grad = tf.matmul(tf.transpose(v0), h0) negative_grad = tf.matmul(tf.transpose(v1), h1) # Update learning rates for the layers update_w = _w + self.learning_rate * (positive_grad - negative_grad) / tf.to_float(tf.shape(v0)[0]) update_vb = _vb + self.learning_rate * tf.reduce_mean(v0 - v1, 0) update_hb = _hb + self.learning_rate * tf.reduce_mean(h0 - h1, 0) # Find the error rate err = tf.reduce_mean(tf.square(v0 - v1)) # Training loop with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # For each epoch for epoch in range(self.epochs): # For each step/batch for start, end in zip(range(0, len(X), self.batchsize), range(self.batchsize, len(X), self.batchsize)): batch = X[start:end] # Update the rates cur_w = sess.run(update_w, feed_dict={v0: batch, _w: prv_w, _hb: prv_hb, _vb: prv_vb}) cur_hb = sess.run(update_hb, feed_dict={v0: batch, _w: prv_w, _hb: prv_hb, _vb: prv_vb}) cur_vb = sess.run(update_vb, feed_dict={v0: batch, _w: prv_w, _hb: prv_hb, _vb: prv_vb}) prv_w = cur_w prv_hb = cur_hb prv_vb = cur_vb error = sess.run(err, feed_dict={v0: X, _w: cur_w, _vb: cur_vb, _hb: cur_hb}) print('Epoch: %d' % epoch, 'reconstruction error: %f' % error) self.w = prv_w self.hb = prv_hb self.vb = prv_vb # Create expected output for our DBN def rbm_outpt(self, X): input_X = tf.constant(X) _w = tf.constant(self.w) _hb = tf.constant(self.hb) out = tf.nn.sigmoid(tf.matmul(input_X, _w) + _hb) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) return sess.run(out) class NN(object): def __init__(self, sizes, X, Y): # Initialize hyperparameters self._sizes = sizes self._X = X self._Y = Y self.w_list = [] self.b_list = [] self._learning_rate = 1.0 self._momentum = 0.0 self._epoches = 10 self._batchsize = 100 input_size = X.shape[1] # initialization loop for size in self._sizes + [Y.shape[1]]: # Define upper limit for the uniform distribution range max_range = 4 * math.sqrt(6. / (input_size + size)) # Initialize weights through a random uniform distribution self.w_list.append( np.random.uniform(-max_range, max_range, [input_size, size]).astype(np.float32)) # Initialize bias as zeroes self.b_list.append(np.zeros([size], np.float32)) input_size = size # load data from rbm def load_from_rbms(self, dbn_sizes, rbm_list): # Check if expected sizes are correct assert len(dbn_sizes) == len(self._sizes) for i in range(len(self._sizes)): # Check if for each RBN the expected sizes are correct assert dbn_sizes[i] == self._sizes[i] # If everything is correct, bring over the weights and biases for i in range(len(self._sizes)): self.w_list[i] = rbm_list[i].w self.b_list[i] = rbm_list[i].hb # Training method def train(self): # Create placeholders for input, weights, biases, output _a = [None] * (len(self._sizes) + 2) _w = [None] * (len(self._sizes) + 1) _b = [None] * (len(self._sizes) + 1) _a[0] = tf.placeholder("float", [None, self._X.shape[1]]) y = tf.placeholder("float", [None, self._Y.shape[1]]) # Define variables and activation functoin for i in range(len(self._sizes) + 1): _w[i] = tf.Variable(self.w_list[i]) _b[i] = tf.Variable(self.b_list[i]) for i in range(1, len(self._sizes) + 2): _a[i] = tf.nn.sigmoid(tf.matmul(_a[i - 1], _w[i - 1]) + _b[i - 1]) # Define the cost function cost = tf.reduce_mean(tf.square(_a[-1] - y)) # Define the training operation (Momentum Optimizer minimizing the Cost function) train_op = tf.train.MomentumOptimizer( self._learning_rate, self._momentum).minimize(cost) # Prediction operation predict_op = tf.argmax(_a[-1], 1) # Training Loop with tf.Session() as sess: # Initialize Variables sess.run(tf.global_variables_initializer()) # For each epoch for i in range(self._epoches): # For each step for start, end in zip( range(0, len(self._X), self._batchsize), range(self._batchsize, len(self._X), self._batchsize)): # Run the training operation on the input data sess.run(train_op, feed_dict={ _a[0]: self._X[start:end], y: self._Y[start:end]}) for j in range(len(self._sizes) + 1): # Retrieve weights and biases self.w_list[j] = sess.run(_w[j]) self.b_list[j] = sess.run(_b[j]) print("Accuracy rating for epoch " + str(i) + ": " + str(np.mean(np.argmax(self._Y, axis=1) == \ sess.run(predict_op, feed_dict={_a[0]: self._X, y: self._Y})))) if __name__ == '__main__': # Loading in the mnist data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images,\ mnist.test.labels RBM_hidden_sizes = [500, 200, 50] # create 4 layers of RBM with size 785-500-200-50 # Since we are training, set input as training data inpX = trX # Create list to hold our RBMs rbm_list = [] # Size of inputs is the number of inputs in the training set input_size = inpX.shape[1] # For each RBM we want to generate for i, size in enumerate(RBM_hidden_sizes): print('RBM: ', i, ' ', input_size, '->', size) rbm_list.append(RBM(input_size, size)) input_size = size # For each RBM in our list for rbm in rbm_list: print('New RBM:') # Train a new one rbm.train(inpX) # Return the output layer inpX = rbm.rbm_outpt(inpX) nNet = NN(RBM_hidden_sizes, trX, trY) nNet.load_from_rbms(RBM_hidden_sizes, rbm_list) nNet.train()
任何程序错误,以及技术疑问或需要解答的,请添加
-
【学习笔记】【DBN】十九——深度信念网络DBN
2021-10-12 20:06:15本篇简要介绍深度信念网络DBN,是一个不太常见的神经网络。 一、DBN概述 深度信念网络(Deep Belief Nets,DBN),既可用于非监督学习,类似于一个自编码机;也可以用于监督学习,作为分类器使用。 从非监督学习... -
基于深度信念网络的高光谱影像森林类型识别
2021-05-06 12:20:50深度信念网络是一种半监督学习方法,可将高光谱所有波段作为深度信念网络的输入,从而避免降维处理.论文利用深度信念网络对泉州市德化县西部8个乡镇进行森林类型识别研究.基于HJ/1A高光谱图像与二类调查数据,利用... -
基于多隐层Gibbs 采样的深度信念网络训练方法
2021-05-11 03:38:11深度信念网络(Deep belief network, DBN) 作为一类非常重要的概率生成模型, 在多个领域都有着广泛的用途. 现.有深度信念网的训练分为两个阶段, 首先是对受限玻尔兹曼机(Restricted Boltzmann machine, RBM) 层自底... -
深度信念网络(DBN)
2014-03-22 20:29:48本系列文章主要记录自己对深度神经网络的一些学习心得。 1. 自联想神经网络与深度网络 自联想神经网络是很古老的神经网络模型,简单的说,它就是三层BP网络,只不过它的输出等于... -
机器学习入门:第十九章 深度信念网络
2022-04-15 10:16:43深度信念网络 (Deep Belief Network, DBN) 深度信念网络 (Deep Belief Network, DBN) 由 Geoffrey Hinton 在 2006 年提出。它是一种生成模型,通过训练其神经元间的权重,我们可以让整个神经网络按照最大概率来生成... -
深度信念网络研究现状与展望
2021-02-03 17:25:16来源:专知摘要:深度信念网络(Deep belief network, DBN)是一种基于深度学习的生成模型, 克服了传统梯度类学习算法在处理深层结构所面临的梯度消失问题, 近几年来已成... -
使用深度置信网络进行特征提取代码实现 python_2020 必学的10大顶级 Python 库
2020-11-22 12:42:33python 是最流行和使用最广泛的编程语言之一,它已经取代了业界许多编程语言。python 在开发人员中流行的原因有很多。然而,最重要的一点是它有大量的库供用户使用。python 的简单性吸引了许多开发人员为机器学习... -
hyperspectral_classifier_DBN:深度信念网络,用于高光谱图像中的材料分类
2021-05-03 09:21:15关于数据集的注释: 使用一个简单的脚本将原始的.mat图像和基本事实转换为.txt文件。 数据目录包含这些.txt文件的示例(但不是全部)。 原始.mat文件可以从[Palis Vasco大学]( )获得。 使用注意事项: ... -
TensorFlow DBN深度信念网络搭建2
2018-01-05 15:43:041、改进1:层数改变 通过修改rbm的层数,可以看到重构误差是变小了,但是,我发现只是修改rbm,并没有影响到最终的accuracy,而且更加诡异的是,这个accuracy,只从我修改了数据集以来,无论怎么修改,都是同一个数... -
Python的遗传算法GA优化深度置信网络DBN超参数回归预测
2021-07-22 10:26:03DBN超参数众多,包括隐含层层数、各层节点数、无监督预...之前写过MATLAB版本的DBN超参数优化,今天这个是python/torch版本的DBN超参数优化。具体运行环境python36、torch1.2。 话不多说,直接上结果。数据结构是... -
DBNN.NASA:约翰和凯瑟琳的 NASA SpaceApps Challenge 项目,使用深度信念网络对小行星进行分类
2021-06-13 01:59:26我们使用 Python、 和对网络和小行星数据进行可视化,从在线数据库中获取内容,并将这些内容链接到一个应用程序中。 我们使用了两个主要数据来源——来自美国宇航局光曲线,一个对太阳系大部分地区进行成像的红外... -
python 深度学习_Python深度学习-简介
2020-09-22 06:22:14Python深度学习-简介 (Python Deep Learning - Introduction) Advertisements 广告 Previous Page 上一页 Next Page 下一页 Deep structured learning or hierarchical learning or deep learning in ... -
基于深度信念网络的猪咳嗽声识别
2018-07-19 23:33:02基于深度信念网络的猪咳嗽声识别,采用深度信念网络通过分析猪咳嗽声识别情绪 -
基于Python TensorFlow Keras的深度学习回归代码——keras.Sequential深度神经网络
2021-02-24 12:18:42基于Python TensorFlow Keras的深度学习回归代码——keras.Sequential深度神经网络1 写在前面2 代码分解介绍2.1 准备工作2.2 参数配置2.3 数据导入与数据划分2.4 联合分布图绘制2.5 因变量分离与数据标准化2.6 原有... -
求助——深度信念网络模型中的RBM是怎么执行的?
2019-10-22 13:50:15最近在学习深度信念网络,看了很多的资料,但是还是有一些疑问,希望看到的大佬可以给予帮助,非常感谢。联系方式:18809861082 疑问??? 很多资料解释DBN是由多个RBM和一层BP神经网络网络组成(暂且这么理解)。... -
深度置信网络(DBM)
2021-12-02 11:21:55深度置信网络 -
数学推导+纯Python实现机器学习算法12:贝叶斯网络
2022-02-04 02:10:50pgmpy是一款基于Python的概率图模型包,主要包括贝叶斯网络和马尔可夫蒙特卡洛等常见概率图模型的实现以及推断方法。本节使用pgmpy包来实现简单的贝叶斯网络。 我们以学生获得推荐信质量这样一个例子来进行贝叶斯... -
Keras(三)实现深度神经网络
2020-11-20 16:18:49/usr/bin/env python3 # -*- coding: utf-8 -*- import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import sklearn import pandas as pd import os import sys import time import ... -
大话深度信念网络(DBN)
2018-03-01 01:53:002019独角兽企业重金招聘Python工程师标准>>> ...