如何用9行Python代码编写一个简易神经网络
学习人工智能时,我给自己定了一个目标--用Python写一个简单的神经网络。为了确保真得理解它,我要求自己不使用任何神经网络库,从头写起。多亏了AndrewTrask写得一篇精彩的博客,我做到了!
下面贴出那九行代码:在这篇文章中,我将解释我是如何做得,以便你可以写出你自己的。我将会提供一个长点的但是更完美的源代码。首先,神经网络是什么?人脑由几千亿由突触相互连接的细胞(神经元)组成。
突触传入足够的兴奋就会引起神经元的兴奋。这个过程被称为“思考”。我们可以在计算机上写一个神经网络来模拟这个过程。不需要在生物分子水平模拟人脑,只需模拟更高层级的规则。
我们使用矩阵(二维数据表格)这一数学工具,并且为了简单明了,只模拟一个有3个输入和一个输出的神经元。我们将训练神经元解决下面的问题。前四个例子被称作训练集。你发现规律了吗?‘?’是0还是1?
你可能发现了,输出总是等于输入中最左列的值。所以‘?’应该是1。训练过程但是如何使我们的神经元回答正确呢?赋予每个输入一个权重,可以是一个正的或负的数字。
拥有较大正(或负)权重的输入将决定神经元的输出。首先设置每个权重的初始值为一个随机数字,然后开始训练过程:取一个训练样本的输入,使用权重调整它们,通过一个特殊的公式计算神经元的输出。
计算误差,即神经元的输出与训练样本中的期待输出之间的差值。根据误差略微地调整权重。重复这个过程1万次。最终权重将会变为符合训练集的一个最优解。
如果使用神经元考虑这种规律的一个新情形,它将会给出一个很棒的预测。这个过程就是backpropagation。计算神经元输出的公式你可能会想,计算神经元输出的公式是什么?
首先,计算神经元输入的加权和,即接着使之规范化,结果在0,1之间。为此使用一个数学函数--Sigmoid函数:Sigmoid函数的图形是一条“S”状的曲线。
把第一个方程代入第二个,计算神经元输出的最终公式为:你可能注意到了,为了简单,我们没有引入最低兴奋阈值。调整权重的公式我们在训练时不断调整权重。但是怎么调整呢?
可以使用“ErrorWeightedDerivative”公式:为什么使用这个公式?首先,我们想使调整和误差的大小成比例。其次,乘以输入(0或1),如果输入是0,权重就不会调整。
最后,乘以Sigmoid曲线的斜率(图4)。
为了理解最后一条,考虑这些:我们使用Sigmoid曲线计算神经元的输出如果输出是一个大的正(或负)数,这意味着神经元采用这种(或另一种)方式从图四可以看出,在较大数值处,Sigmoid曲线斜率小如果神经元认为当前权重是正确的,就不会对它进行很大调整。
乘以Sigmoid曲线斜率便可以实现这一点Sigmoid曲线的斜率可以通过求导得到:把第二个等式代入第一个等式里,得到调整权重的最终公式:当然有其他公式,它们可以使神经元学习得更快,但是这个公式的优点是非常简单。
构造Python代码虽然我们没有使用神经网络库,但是将导入Python数学库numpy里的4个方法。
分别是:exp--自然指数array--创建矩阵dot--进行矩阵乘法random--产生随机数比如,我们可以使用array()方法表示前面展示的训练集:“.T”方法用于矩阵转置(行变列)。
所以,计算机这样存储数字:我觉得我们可以开始构建更优美的源代码了。给出这个源代码后,我会做一个总结。我对每一行源代码都添加了注释来解释所有内容。注意在每次迭代时,我们同时处理所有训练集数据。
所以变量都是矩阵(二维数据表格)。下面是一个用Python写地完整的示例代码。我们做到了!我们用Python构建了一个简单的神经网络!首先神经网络对自己赋予随机权重,然后使用训练集训练自己。
接着,它考虑一种新的情形[1,0,0]并且预测了0.99993704。正确答案是1。非常接近!传统计算机程序通常不会学习。
而神经网络却能自己学习,适应并对新情形做出反应,这是多么神奇,就像人类一样。
python简单神经网络的实现 求问这儿是怎么实现syn0均值为0的,以及我在Python3中运行发现l1的shape也不对
np.random.random返回[0,1)区间的随机数,2*np.random.random -1返回[-1,1)的随机数,具体可以看网页链接看这个神经网络结构应该就输入输出两层,l1的shape为(l0,syn0),[4*3],[3*1]的矩阵相乘得到[4*1]的矩阵,y=np.array([[0,1,1,0]]).T,y也是[4*1]的矩阵。
Hopfield神经网络用python实现讲解?
神经网络结构具有以下三个特点:神经元之间全连接,并且为单层神经网络。每个神经元既是输入又是输出,导致得到的权重矩阵相对称,故可节约计算量。
在输入的激励下,其输出会产生不断的状态变化,这个反馈过程会一直反复进行。
假如Hopfield神经网络是一个收敛的稳定网络,则这个反馈与迭代的计算过程所产生的变化越来越小,一旦达到了稳定的平衡状态,Hopfield网络就会输出一个稳定的恒值。
Hopfield网络可以储存一组平衡点,使得当给定网络一组初始状态时,网络通过自行运行而最终收敛于这个设计的平衡点上。
当然,根据热力学上,平衡状态分为stablestate和metastablestate,这两种状态在网络的收敛过程中都是非常可能的。为递归型网络,t时刻的状态与t-1时刻的输出状态有关。
之后的神经元更新过程也采用的是异步更新法(Asynchronous)。Hopfield神经网络用python实现。
怎样用python构建一个卷积神经网络模型
上周末利用python简单实现了一个卷积神经网络,只包含一个卷积层和一个maxpooling层,pooling层后面的多层神经网络采用了softmax形式的输出。
实验输入仍然采用MNIST图像使用10个featuremap时,卷积和pooling的结果分别如下所示。
部分源码如下:[python] viewplain copy#coding=utf-8'''''Created on 2014年11月30日@author: Wangliaofan'''import numpyimport structimport matplotlib.pyplot as pltimport mathimport randomimport copy#testfrom BasicMultilayerNeuralNetwork import BMNN2def sigmoid(inX):if (-inX)== 0.0:return 999999999.999999999return 1.0/((-inX))def difsigmoid(inX):return sigmoid(inX)*(1.0-sigmoid(inX))def tangenth(inX):return (1.0*(inX)-1.0*(-inX))/(1.0*(inX)+1.0*(-inX))def cnn_conv(in_image, filter_map,B,type_func='sigmoid'):#in_image[num,feature map,row,col]=>in_image[Irow,Icol]#features map[k filter,row,col]#type_func['sigmoid','tangenth']#out_feature[k filter,Irow-row+1,Icol-col+1]shape_image=numpy.shape(in_image)#[row,col]#print "shape_image",shape_imageshape_filter=numpy.shape(filter_map)#[k filter,row,col]if shape_filter[1]>shape_image[0] or shape_filter[2]>shape_image[1]:raise Exceptionshape_out=(shape_filter[0],shape_image[0]-shape_filter[1]+1,shape_image[1]-shape_filter[2]+1)out_feature=numpy.zeros(shape_out)k,m,n=numpy.shape(out_feature)for k_idx in range(0,k):#rotate 180 to calculate convc_filter=numpy.rot90(filter_map[k_idx,:,:], 2)for r_idx in range(0,m):for c_idx in range(0,n):#conv_temp=numpy.zeros((shape_filter[1],shape_filter[2]))(in_image[r_idx:r_idx+shape_filter[1],c_idx:c_idx+shape_filter[2]],c_filter)(conv_temp)if type_func=='sigmoid':out_feature[k_idx,r_idx,c_idx]=sigmoid(sum_temp+B[k_idx])elif type_func=='tangenth':out_feature[k_idx,r_idx,c_idx]=tangenth(sum_temp+B[k_idx])else:raise Exceptionreturn out_featuredef cnn_maxpooling(out_feature,pooling_size=2,type_pooling="max"):k,row,col=numpy.shape(out_feature)max_index_Matirx=numpy.zeros((k,row,col))out_row=int(numpy.floor(row/pooling_size))out_col=int(numpy.floor(col/pooling_size))out_pooling=numpy.zeros((k,out_row,out_col))for k_idx in range(0,k):for r_idx in range(0,out_row):for c_idx in range(0,out_col):temp_matrix=out_feature[k_idx,pooling_size*r_idx:pooling_size*r_idx+pooling_size,pooling_size*c_idx:pooling_size*c_idx+pooling_size]out_pooling[k_idx,r_idx,c_idx](temp_matrix)max_index=numpy.argmax(temp_matrix)#print max_index#print max_index/pooling_size,max_index%pooling_sizemax_index_Matirx[k_idx,pooling_size*r_idx+max_index/pooling_size,pooling_size*c_idx+max_index%pooling_size]=1return out_pooling,max_index_Matirxdef poolwithfunc(in_pooling,W,B,type_func='sigmoid'):k,row,col=numpy.shape(in_pooling)out_pooling=numpy.zeros((k,row,col))for k_idx in range(0,k):for r_idx in range(0,row):for c_idx in range(0,col):out_pooling[k_idx,r_idx,c_idx]=sigmoid(W[k_idx]*in_pooling[k_idx,r_idx,c_idx]+B[k_idx])return out_pooling#out_feature is the out put of convdef backErrorfromPoolToConv(theta,max_index_Matirx,out_feature,pooling_size=2):k1,row,col=numpy.shape(out_feature)error_conv=numpy.zeros((k1,row,col))k2,theta_row,theta_col=numpy.shape(theta)if k1!=k2:raise Exceptionfor idx_k in range(0,k1):for idx_row in range( 0, row):for idx_col in range( 0, col):error_conv[idx_k,idx_row,idx_col]=\max_index_Matirx[idx_k,idx_row,idx_col]*\float(theta[idx_k,idx_row/pooling_size,idx_col/pooling_size])*\difsigmoid(out_feature[idx_k,idx_row,idx_col])return error_convdef backErrorfromConvToInput(theta,inputImage):k1,row,col=numpy.shape(theta)#print "theta",k1,row,coli_row,i_col=numpy.shape(inputImage)if row>i_row or col> i_col:raise Exceptionfilter_row=i_row-row+1filter_col=i_col-col+1detaW=numpy.zeros((k1,filter_row,filter_col))#the same with conv valid in matlabfor k_idx in range(0,k1):for idx_row in range(0,filter_row):for idx_col in range(0,filter_col):subInputMatrix=inputImage[idx_row:idx_row+row,idx_col:idx_col+col]#print "subInputMatrix",numpy.shape(subInputMatrix)#rotate theta 180#print numpy.shape(theta)theta_rotate=numpy.rot90(theta[k_idx,:,:], 2)#print "theta_rotate",theta_rotate(subInputMatrix,theta_rotate)detaW[k_idx,idx_row,idx_col](dotMatrix)detaB=numpy.zeros((k1,1))for k_idx in range(0,k1):detaB[k_idx](theta[k_idx,:,:])return detaW,detaBdef loadMNISTimage(absFilePathandName,datanum=60000):images=open(absFilePathandName,'rb')()index=0magic, numImages , numRows , numColumns = struct.unpack_from('>IIII' , buf , index)print magic, numImages , numRows , numColumnsindex += struct.calcsize('>IIII')if magic != 2051:raise Exceptiondatasize=int(784*datanum)datablock=">"+str(datasize)+"B"#nextmatrix=struct.unpack_from('>47040000B' ,buf, index)nextmatrix=struct.unpack_from(datablock ,buf, index)nextmatrix=numpy.array(nextmatrix)/255.0#nextmatrix=nextmatrix.reshape(numImages,numRows,numColumns)#nextmatrix=nextmatrix.reshape(datanum,1,numRows*numColumns)nextmatrix=nextmatrix.reshape(datanum,1,numRows,numColumns)return nextmatrix, numImagesdef loadMNISTlabels(absFilePathandName,datanum=60000):labels=open(absFilePathandName,'rb')()index=0magic, numLabels = struct.unpack_from('>II' , buf , index)print magic, numLabelsindex += struct.calcsize('>II')if magic != 2049:raise Exceptiondatablock=">"+str(datanum)+"B"#nextmatrix=struct.unpack_from('>60000B' ,buf, index)nextmatrix=struct.unpack_from(datablock ,buf, index)nextmatrix=numpy.array(nextmatrix)return nextmatrix, numLabelsdef simpleCNN(numofFilter,filter_size,pooling_size=2,maxIter=1000,imageNum=500):decayRate=0.01MNISTimage,num1=loadMNISTimage("F:\Machine Learning\UFLDL\data\common\\train-images-idx3-ubyte",imageNum)print num1row,col=numpy.shape(MNISTimage[0,0,:,:])out_Di=numofFilter*((row-filter_size+1)/pooling_size)*((col-filter_size+1)/pooling_size)MLP=BMNN2.MuiltilayerANN(1,[128],out_Di,10,maxIter)MLP.setTrainDataNum(imageNum)MLP.loadtrainlabel("F:\Machine Learning\UFLDL\data\common\\train-labels-idx1-ubyte")MLP.initialweights()#MLP.printWeightMatrix()rng = numpy.random.RandomState(23455)W_shp = (numofFilter, filter_size, filter_size)W_bound = (numofFilter * filter_size * filter_size)W_k=rng.uniform(low=-1.0 / W_bound,high=1.0 / W_bound,size=W_shp)B_shp = (numofFilter,)B= numpy.asarray(rng.uniform(low=-.5, high=.5, size=B_shp))cIter=0while cIter。
怎样用python构建一个卷积神经网络
用keras框架较为方便首先安装anaconda,然后通过pip安装keras以下转自wphh的博客。
#coding:utf-8''' GPU run command: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python CPU run command: python 2016.06.06更新:这份代码是keras开发初期写的,当时keras还没有现在这么流行,文档也还没那么丰富,所以我当时写了一些简单的教程。
现在keras的API也发生了一些的变化,建议及推荐直接上看更加详细的教程。
'''#导入各种用到的模块组件from __future__ import absolute_importfrom __future__ import print_functionfrom keras.preprocessing.image import ImageDataGeneratorfrom keras.models import Sequentialfrom import Dense, Dropout, Activation, Flattenfrom keras.layers.advanced_activations import PReLUfrom keras.layers.convolutional import Convolution2D, MaxPooling2Dfrom keras.optimizers import SGD, Adadelta, Adagradfrom keras.utils import np_utils, generic_utilsfrom six.moves import rangefrom data import load_dataimport randomimport numpy as np(1024) # for reproducibility#加载数据data, label = load_data()#打乱数据index = [i for i in range(len(data))]random.shuffle(index)data = data[index]label = label[index]print(data.shape[0], ' samples')#label为0~9共10个类别,keras要求格式为binary class matrices,转化一下,直接调用keras提供的这个函数label = np_utils.to_categorical(label, 10)################开始建立CNN模型################生成一个modelmodel = Sequential()#第一个卷积层,4个卷积核,每个卷积核大小5*5。
1表示输入的图片的通道,灰度图为1通道。
#border_mode可以是valid或者full,具体看这里说明:.conv2d#激活函数用tanh#你还可以在(Activation('tanh'))后加上dropout的技巧: (Dropout(0.5))(Convolution2D(4, 5, 5, border_mode='valid',input_shape=(1,28,28))) (Activation('tanh'))#第二个卷积层,8个卷积核,每个卷积核大小3*3。
4表示输入的特征图个数,等于上一层的卷积核个数#激活函数用tanh#采用maxpooling,poolsize为(2,2)(Convolution2D(8, 3, 3, border_mode='valid'))(Activation('tanh'))(MaxPooling2D(pool_size=(2, 2)))#第三个卷积层,16个卷积核,每个卷积核大小3*3#激活函数用tanh#采用maxpooling,poolsize为(2,2)(Convolution2D(16, 3, 3, border_mode='valid')) (Activation('relu'))(MaxPooling2D(pool_size=(2, 2)))#全连接层,先将前一层输出的二维特征图flatten为一维的。
#Dense就是隐藏层。16就是上一层输出的特征图个数。
4是根据每个卷积层计算出来的:(28-5+1)得到24,(24-3+1)/2得到11,(11-3+1)/2得到4#全连接有128个神经元节点,初始化方式为normal(Flatten())(Dense(128, init='normal'))(Activation('tanh'))#Softmax分类,输出是10类别(Dense(10, init='normal'))(Activation('softmax'))##############开始训练模型###############使用SGD + momentum#model.compile里的参数loss就是损失函数(目标函数)sgd = SGD(lr=0.05, decay=1e-6, momentum=0.9, nesterov=True)model.compile(loss='categorical_crossentropy', optimizer=sgd,metrics=["accuracy"])#调用fit方法,就是一个训练过程. 训练的epoch数设为10,batch_size为100.#数据经过随机打乱shuffle=True。
verbose=1,训练过程中输出的信息,0、1、2三种方式都可以,无关紧要。show_accuracy=True,训练时每一个epoch都输出accuracy。
#validation_split=0.2,将20%的数据作为验证集。
(data, label, batch_size=100, nb_epoch=10,shuffle=True,verbose=1,validation_split=0.2)"""#使用data augmentation的方法#一些参数和调用的方法,请看文档datagen = ImageDataGenerator( featurewise_center=True, # set input mean to 0 over the dataset samplewise_center=False, # set each sample mean to 0 featurewise_std_normalization=True, # divide inputs by std of the dataset samplewise_std_normalization=False, # divide each input by its std zca_whitening=False, # apply ZCA whitening rotation_range=20, # randomly rotate images in the range (degrees, 0 to 180) width_shift_range=0.2, # randomly shift images horizontally (fraction of total width) height_shift_range=0.2, # randomly shift images vertically (fraction of total height) horizontal_flip=True, # randomly flip images vertical_flip=False) # randomly flip images# compute quantities required for featurewise normalization # (std, mean, and principal components if ZCA whitening is applied)(data)for e in range(nb_epoch): print('-'*40) print('Epoch', e) print('-'*40) print("Training...") # batch train with realtime data augmentation progbar = generic_utils.Progbar(data.shape[0]) for X_batch, Y_batch in (data, label): loss,accuracy = model.train(X_batch, Y_batch,accuracy=True) (X_batch.shape[0], values=[("train loss", loss),("accuracy:", accuracy)] )"""。
怎么用python写tensorflow
。
开始使用TensorFlow并不是一个纯粹的神经网络框架,而是使用数据流图进行数值分析的框架.TensorFlow使用有向图(graph)表示一个计算任务.图的节点称为ops(operations)表示对数据的处理,图的边flow描述数据的流向.该框架计算过程就是处理tensor组成的流.这也是TensorFlow名称的来源.TensorFlow使用tensor表示数据.tensor意为张量即高维数组,在python中使用numpy.ndarray表示.TensorFlow使用Session执行图,使用Variable维护状态.tf.constant是只能输出的ops,常用作数据源.下面我们构建一个只有两个constant做输入,然后进行矩阵乘的简单图:fromtensorflowimportSession,device,constant,matmul'''构建一个只有两个constant做输入,然后进行矩阵乘的简单图:'''#如果不使用withsession()语句,需要手动执行session.close().#withdevice设备指定了执行计算的设备:# "/cpu:0":机器的CPU.# "/gpu:0":机器的第一个GPU,如果有的话.# "/gpu:1":机器的第二个GPU,以此类推.withSession()assession: #创建执行图的上下文withdevice('/cpu:0'): #指定运算设备mat1=constant([[3,3]]) #创建源节点mat2=constant([[2],[2]])product=matmul(mat1,mat2)#指定节点的前置节点,创建图result=(product)#执行计算 print(result)呵呵1112131415161718下面使用Variable做一个计数器:fromtensorflowimportSession,constant,Variable,add,assign,initialize_all_variablesstate=Variable(0,name='counter')#创建计数器one=constant(1)#创建数据源:1val=add(state,one)#创建新值节点update=assign(state,val)#更新计数器setup=initialize_all_variables()#初始化VariablewithSession()assession:(setup)#执行初始化print((state))#输出初值foriinrange(3):(update)#执行更新print((state))#输出计数器值呵呵111213 在使用变量前必须运行initialize_all_variables()返回的图,运行Variable节点将返回变量的值.本示例中将构建图的过程写在了上下文之外,而且没有指定运行设备.上面示例中只接受一个op作为参数,实际上run可以接受op列表作为输入:([op1,op2])1上述示例一直使用constant作为数据源,feed可以在运行时动态地输入数据:fromtensorflowimportSession,placeholder,mul,float32input1=placeholder(float32)input2=placeholder(float32)output=mul(input1,input2)withSession()assession: print(output,feed_dict={input1:[3],input2:[2]})1234567实现一个简单神经网络神经网络是应用广泛的机器学习模型,关于神经网络的原理可以参见这篇随笔,或者在tensorflowplayground上体验一下在线demo.首先定义一个BPNeuralNetwork类:classBPNeuralNetwork:def__init__(self):self.session=tf.Session()self.input_layer=Noneself.label_layer=None=Noneself.trainer=Noneself.layers=[] def__del__(self):self.session.close()呵呵11编写一个生成单层神经网络函数,每层神经元用一个数据流图表示.使用一个Variable矩阵表示与前置神经元的连接权重,另一个Variable向量表示偏置值,并为该层设置一个激励函数.defmake_layer(inputs,in_size,out_size,activate=None):weights=tf.Variable(tf.random_normal([in_size,out_size]))basis=tf.Variable(tf.zeros([1,out_size])+0.1)result=tf.matmul(inputs,weights)+basis ifactivateisNone: returnresult else: returnactivate(result)12345678使用placeholder作为输入层.self.input_layer=tf.placeholder(tf.float32,[None,2])1placeholder的第二个参数为张量的形状,[None,1]表示行数不限,列数为1的二维数组,含义与numpy.array.shape相同.这里,self.input_layer被定义为接受二维输入的输入层.同样使用placeholder表示训练数据的标签:self.label_layer=tf.placeholder(tf.float32,[None,1])1使用make_layer为神经网络定义两个隐含层,并用最后一层作为输出层:=tf.reduce_mean(tf.reduce_sum(tf.square((self.label_layer-self.layers[1])),reduction_indices=[1]))1tf.train提供了一些优化器,可以用来训练神经网络.以损失函数最小化为目标:self.trainer=tf.train.GradientDescentOptimizer(learn_rate).minimize()1使用Session运行神经网络模型:initer=tf.initialize_all_variables()#do(initer)foriinrange(limit):(self.trainer,feed_dict={self.input_layer:cases,self.label_layer:labels})12345使用训练好的模型进行预测:(self.layers[-1],feed_dict={self.input_layer:case})1完整代码:importtensorflowastfimportnumpyasnpdefmake_layer(inputs,in_size,out_size,activate=None):weights=tf.Variable(tf.random_normal([in_size,out_size]))basis=tf.Variable(tf.zeros([1,out_size])+0.1)result=tf.matmul(inputs,weights)+basis ifactivateisNone: returnresult else: returnactivate(result)classBPNeuralNetwork:def__init__(self):self.session=tf.Session()self.input_layer=Noneself.label_layer=None=Noneself.optimizer=Noneself.layers=[] def__del__(self):self.session.close() deftrain(self,cases,labels,limit=100,learn_rate=0.05):#构建网络self.input_layer=tf.placeholder(tf.float32,[None,2])self.label_layer=tf.placeholder(tf.float32,[None,1])self.layers.append(make_layer(self.input_layer,2,10,))self.layers.append(make_layer(self.layers[0],10,2,activate=None))=tf.reduce_mean(tf.reduce_sum(tf.square((self.label_layer-self.layers[1])),reduction_indices=[1]))self.optimizer=tf.train.GradientDescentOptimizer(learn_rate).minimize()initer=tf.initialize_all_variables() #做训练(initer) foriinrange(limit):(self.optimizer,feed_dict={self.input_layer:cases,self.label_layer:labels}) defpredict(self,case):return(self.layers[-1],feed_dict={self.input_layer:case}) deftest(self):x_data=np.array([[0,0],[0,1],[1,0],[1,1]])y_data=np.array([[0,1,1,0]]).transpose()test_data=np.array([[0,1]])self.train(x_data,y_data)print(self.predict(test_data))nn=BPNeuralNetwork()()呵呵111213141516171819202122232425262728293031323334353637383940414243444546474849505152上述模型虽然简单但是使用不灵活,作者采用同样的思想实现了一个可以自定义输入输出维数以及多层隐含神经元的网络,可以参见importtensorflowastfimportnumpyasnpdefmake_layer(inputs,in_size,out_size,activate=None):weights=tf.Variable(tf.random_normal([in_size,out_size]))basis=tf.Variable(tf.zeros([1,out_size])+0.1)result=tf.matmul(inputs,weights)+basis ifactivateisNone: returnresult else: returnactivate(result)classBPNeuralNetwork:def__init__(self):self.session=tf.Session()=Noneself.optimizer=Noneself.input_n=0self.hidden_n=0self.hidden_size=[]self.output_n=0self.input_layer=Noneself.hidden_layers=[]self.output_layer=Noneself.label_layer=Nonedef__del__(self):self.session.close() defsetup(self,ni,nh,no):#设置参数个数self.input_n=niself.hidden_n=len(nh) #隐藏层的数量self.hidden_size=nh #每个隐藏层中的单元格数self.output_n=no #构建输入层self.input_layer=tf.placeholder(tf.float32,[None,self.input_n]) #构建标签层self.label_layer=tf.placeholder(tf.float32,[None,self.output_n]) #构建隐藏层in_size=self.input_nout_size=self.hidden_size[0]inputs=self.input_layerself.hidden_layers.append(make_layer(inputs,in_size,out_size,)) foriinrange(self.hidden_n-1):in_size=out_sizeout_size=self.hidden_size[i+1]inputs=self.hidden_layers[-1]self.hidden_layers.append(make_layer(inputs,in_size,out_size,)) #构建输出层self.output_layer=make_layer(self.hidden_layers[-1],self.hidden_size[-1],self.output_n) deftrain(self,cases,labels,limit=100,learn_rate=0.05):=tf.reduce_mean(tf.reduce_sum(tf.square((self.label_layer-self.output_layer)),reduction_indices=[1]))self.optimizer=tf.train.GradientDescentOptimizer(learn_rate).minimize()initer=tf.initialize_all_variables() #做训练(initer) foriinrange(limit):(self.optimizer,feed_dict={self.input_layer:cases,self.label_layer:labels}) defpredict(self,case):return(self.output_layer,feed_dict={self.input_layer:case}) deftest(self):x_data=np.array([[0,0],[0,1],[1,0],[1,1]])y_data=np.array([[0,1,1,0]]).transpose()test_data=np.array([[0,1]])self.setup(2,[10,5],1)self.train(x_data,y_data)print(self.predict(test_data))nn=BPNeuralNetwork()()呵呵111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576。
如何用 Python 构建神经网络择时模型
。
importmathimportrandom(0)defrand(a,b):#随机函数return(b-a)*random.random()+adefmake_matrix(m,n,fill=0.0):#创建一个指定大小的矩阵mat=[]foriinrange(m):mat.append([fill]*n)returnmat#定义sigmoid函数和它的导数defsigmoid(x):return1.0/((-x))defsigmoid_derivate(x):returnx*(1-x)#sigmoid函数的导数classBPNeuralNetwork:def__init__(self):#初始化变量self.input_n=0self.hidden_n=0self.output_n=0self.input_cells=[]self.hidden_cells=[]self.output_cells=[]self.input_weights=[]self.output_weights=[]self.input_correction=[]self.output_correction=[]#三个列表维护:输入层,隐含层,输出层神经元defsetup(self,ni,nh,no):self.input_n=ni+1#输入层+偏置项self.hidden_n=nh#隐含层self.output_n=no#输出层#初始化神经元self.input_cells=[1.0]*self.input_nself.hidden_cells=[1.0]*self.hidden_nself.output_cells=[1.0]*self.output_n#初始化连接边的边权self.input_weights=make_matrix(self.input_n,self.hidden_n)#邻接矩阵存边权:输入层->隐藏层self.output_weights=make_matrix(self.hidden_n,self.output_n)#邻接矩阵存边权:隐藏层->输出层#随机初始化边权:为了反向传导做准备--->随机初始化的目的是使对称失效foriinrange(self.input_n):forhinrange(self.hidden_n):self.input_weights[i][h]=rand(-0.2,0.2)#由输入层第i个元素到隐藏层第j个元素的边权为随机值forhinrange(self.hidden_n):foroinrange(self.output_n):self.output_weights[h][o]=rand(-2.0,2.0)#由隐藏层第i个元素到输出层第j个元素的边权为随机值#保存校正矩阵,为了以后误差做调整self.input_correction=make_matrix(self.input_n,self.hidden_n)self.output_correction=make_matrix(self.hidden_n,self.output_n)#输出预测值defpredict(self,inputs):#对输入层进行操作转化样本foriinrange(self.input_n-1):self.input_cells[i]=inputs[i]#n个样本从0~n-1#计算隐藏层的输出,每个节点最终的输出值就是权值*节点值的加权和forjinrange(self.hidden_n):total=0.0foriinrange(self.input_n):total+=self.input_cells[i]*self.input_weights[i][j]#此处为何是先i再j,以隐含层节点做大循环,输入样本为小循环,是为了每一个隐藏节点计算一个输出值,传输到下一层self.hidden_cells[j]=sigmoid(total)#此节点的输出是前一层所有输入点和到该点之间的权值加权和forkinrange(self.output_n):total=0.0forjinrange(self.hidden_n):total+=self.hidden_cells[j]*self.output_weights[j][k]self.output_cells[k]=sigmoid(total)#获取输出层每个元素的值returnself.output_cells[:]#最后输出层的结果返回#反向传播算法:调用预测函数,根据反向传播获取权重后前向预测,将结果与实际结果返回比较误差defback_propagate(self,case,label,learn,correct):#对输入样本做预测self.predict(case)#对实例进行预测output_deltas=[0.0]*self.output_n#初始化矩阵foroinrange(self.output_n):error=label[o]-self.output_cells[o]#正确结果和预测结果的误差:0,1,-1output_deltas[o]=sigmoid_derivate(self.output_cells[o])*error#误差稳定在0~1内#隐含层误差hidden_deltas=[0.0]*self.hidden_nforhinrange(self.hidden_n):error=0.0foroinrange(self.output_n):error+=output_deltas[o]*self.output_weights[h][o]hidden_deltas[h]=sigmoid_derivate(self.hidden_cells[h])*error#反向传播算法求W#更新隐藏层->输出权重forhinrange(self.hidden_n):foroinrange(self.output_n):change=output_deltas[o]*self.hidden_cells[h]#调整权重:上一层每个节点的权重学习*变化+矫正率self.output_weights[h][o]+=learn*change+correct*self.output_correction[h][o]#更新输入->隐藏层的权重foriinrange(self.input_n):forhinrange(self.hidden_n):change=hidden_deltas[h]*self.input_cells[i]self.input_weights[i][h]+=learn*change+correct*self.input_correction[i][h]self.input_correction[i][h]=change#获取全局误差error=0.0foroinrange(len(label)):error=0.5*(label[o]-self.output_cells[o])**2#平方误差函数returnerrordeftrain(self,cases,labels,limit=10000,learn=0.05,correct=0.1):foriinrange(limit):#设置迭代次数error=0.0forjinrange(len(cases)):#对输入层进行访问label=labels[j]case=cases[j]error+=self.back_propagate(case,label,learn,correct)#样例,标签,学习率,正确阈值deftest(self):#学习异或cases=[[0,0],[0,1],[1,0],[1,1],]#测试样例labels=[[0],[1],[1],[0]]#标签self.setup(2,5,1)#初始化神经网络:输入层,隐藏层,输出层元素个数self.train(cases,labels,10000,0.05,0.1)#可以更改forcaseincases:print(self.predict(case))if__name__=='__main__':nn=BPNeuralNetwork()()。
学:如何用Python实现7种机器学习算法(附
1.线性回归算法在线性回归中,我们想要建立一个模型,来拟合一个因变量y与一个或多个独立自变量(预测变量)x之间的关系。
是一个目标变量,它是一个标量线性回归模型可以理解为一个非常简单的神经网络:...2.Logistic回归算法在Logistic回归中,我们试图对给定输入特征的线性组合进行建模,来得到其二元变量的输出结果。
例如,我们可以尝试使用竞选候选人花费的金钱和时间信息来预测选举的结果(胜或负)。