糖尿病康复,内容丰富有趣,生活中的好帮手!
糖尿病康复 > 神经网络模型的训练过程 神经网络模型训练过程

神经网络模型的训练过程 神经网络模型训练过程

时间:2022-02-17 03:31:51

相关推荐

神经网络模型的训练过程 神经网络模型训练过程

Python,神经网络训练模型,报错是字符串不能转换为浮点,请问怎么解决?

可能需要将csv中的数据改为数字,可能默认是文本类型看起来read_csv读出来是一个numpy.array可以试下读完csv后下一行改为train=numpy.array(train,dtype='int64')。

谷歌人工智能写作项目:神经网络伪原创

如何用 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构建一个卷积神经网络模型

上周末利用python简单实现了一个卷积神经网络,只包含一个卷积层和一个maxpooling层,pooling层后面的多层神经网络采用了softmax形式的输出。

实验输入仍然采用MNIST图像使用10个featuremap时,卷积和pooling的结果分别如下所示。

部分源码如下:[python]viewplaincopy#coding=utf-8'''''Createdon11月30日@author:Wangliaofan'''importnumpyimportstructimportmatplotlib.pyplotaspltimportmathimportrandomimportcopy#testfromBasicMultilayerNeuralNetworkimportBMNN2defsigmoid(inX):if(-inX)==0.0:return999999999.999999999return1.0/((-inX))defdifsigmoid(inX):returnsigmoid(inX)*(1.0-sigmoid(inX))deftangenth(inX):return(1.0*(inX)-1.0*(-inX))/(1.0*(inX)+1.0*(-inX))defcnn_conv(in_image,filter_map,B,type_func='sigmoid'):#in_image[num,featuremap,row,col]=>in_image[Irow,Icol]#featuresmap[kfilter,row,col]#type_func['sigmoid','tangenth']#out_feature[kfilter,Irow-row+1,Icol-col+1]shape_image=numpy.shape(in_image)#[row,col]#print"shape_image",shape_imageshape_filter=numpy.shape(filter_map)#[kfilter,row,col]ifshape_filter[1]>shape_image[0]orshape_filter[2]>shape_image[1]:raiseExceptionshape_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)fork_idxinrange(0,k):#rotate180tocalculateconvc_filter=numpy.rot90(filter_map[k_idx,:,:],2)forr_idxinrange(0,m):forc_idxinrange(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)iftype_func=='sigmoid':out_feature[k_idx,r_idx,c_idx]=sigmoid(sum_temp+B[k_idx])eliftype_func=='tangenth':out_feature[k_idx,r_idx,c_idx]=tangenth(sum_temp+B[k_idx])else:raiseExceptionreturnout_featuredefcnn_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))fork_idxinrange(0,k):forr_idxinrange(0,out_row):forc_idxinrange(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)#printmax_index#printmax_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]=1returnout_pooling,max_index_Matirxdefpoolwithfunc(in_pooling,W,B,type_func='sigmoid'):k,row,col=numpy.shape(in_pooling)out_pooling=numpy.zeros((k,row,col))fork_idxinrange(0,k):forr_idxinrange(0,row):forc_idxinrange(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])returnout_pooling#out_featureistheoutputofconvdefbackErrorfromPoolToConv(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)ifk1!=k2:raiseExceptionforidx_kinrange(0,k1):foridx_rowinrange(0,row):foridx_colinrange(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])returnerror_convdefbackErrorfromConvToInput(theta,inputImage):k1,row,col=numpy.shape(theta)#print"theta",k1,row,coli_row,i_col=numpy.shape(inputImage)ifrow>i_roworcol>i_col:raiseExceptionfilter_row=i_row-row+1filter_col=i_col-col+1detaW=numpy.zeros((k1,filter_row,filter_col))#thesamewithconvvalidinmatlabfork_idxinrange(0,k1):foridx_rowinrange(0,filter_row):foridx_colinrange(0,filter_col):subInputMatrix=inputImage[idx_row:idx_row+row,idx_col:idx_col+col]#print"subInputMatrix",numpy.shape(subInputMatrix)#rotatetheta180#printnumpy.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))fork_idxinrange(0,k1):detaB[k_idx](theta[k_idx,:,:])returndetaW,detaBdefloadMNISTimage(absFilePathandName,datanum=60000):images=open(absFilePathandName,'rb')()index=0magic,numImages,numRows,numColumns=struct.unpack_from('>IIII',buf,index)printmagic,numImages,numRows,numColumnsindex+=struct.calcsize('>IIII')ifmagic!=2051:raiseExceptiondatasize=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)returnnextmatrix,numImagesdefloadMNISTlabels(absFilePathandName,datanum=60000):labels=open(absFilePathandName,'rb')()index=0magic,numLabels=struct.unpack_from('>II',buf,index)printmagic,numLabelsindex+=struct.calcsize('>II')ifmagic!=2049:raiseExceptiondatablock=">"+str(datanum)+"B"#nextmatrix=struct.unpack_from('>60000B',buf,index)nextmatrix=struct.unpack_from(datablock,buf,index)nextmatrix=numpy.array(nextmatrix)returnnextmatrix,numLabelsdefsimpleCNN(numofFilter,filter_size,pooling_size=2,maxIter=1000,imageNum=500):decayRate=0.01MNISTimage,num1=loadMNISTimage("F:\MachineLearning\UFLDL\data\common\\train-images-idx3-ubyte",imageNum)printnum1row,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:\MachineLearning\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=0whilecIter。

怎样用python构建一个卷积神经网络

用keras框架较为方便首先安装anaconda,然后通过pip安装keras以下转自wphh的博客。

#coding:utf-8'''GPUruncommand:THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32pythonCPUruncommand:python.06.06更新:这份代码是keras开发初期写的,当时keras还没有现在这么流行,文档也还没那么丰富,所以我当时写了一些简单的教程。

现在keras的API也发生了一些的变化,建议及推荐直接上看更加详细的教程。

'''#导入各种用到的模块组件from__future__importabsolute_importfrom__future__importprint_functionfromkeras.preprocessing.imageimportImageDataGeneratorfromkeras.modelsimportSequentialfromimportDense,Dropout,Activation,Flattenfromkeras.layers.advanced_activationsimportPReLUfromkeras.layers.convolutionalimportConvolution2D,MaxPooling2Dfromkeras.optimizersimportSGD,Adadelta,Adagradfromkeras.utilsimportnp_utils,generic_utilsfromsix.movesimportrangefromdataimportload_dataimportrandomimportnumpyasnp(1024)#forreproducibility#加载数据data,label=load_data()#打乱数据index=[iforiinrange(len(data))]random.shuffle(index)data=data[index]label=label[index]print(data.shape[0],'samples')#label为0~9共10个类别,keras要求格式为binaryclassmatrices,转化一下,直接调用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#pile里的参数loss就是损失函数(目标函数)sgd=SGD(lr=0.05,decay=1e-6,momentum=0.9,nesterov=True)pile(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)"""#使用dataaugmentation的方法#一些参数和调用的方法,请看文档datagen=ImageDataGenerator(featurewise_center=True,#setinputmeanto0overthedatasetsamplewise_center=False,#seteachsamplemeanto0featurewise_std_normalization=True,#divideinputsbystdofthedatasetsamplewise_std_normalization=False,#divideeachinputbyitsstdzca_whitening=False,#applyZCAwhiteningrotation_range=20,#randomlyrotateimagesintherange(degrees,0to180)width_shift_range=0.2,#randomlyshiftimageshorizontally(fractionoftotalwidth)height_shift_range=0.2,#randomlyshiftimagesvertically(fractionoftotalheight)horizontal_flip=True,#randomlyflipimagesvertical_flip=False)#randomlyflipimages#computequantitiesrequiredforfeaturewisenormalization#(std,mean,andprincipalcomponentsifZCAwhiteningisapplied)(data)foreinrange(nb_epoch):print('-'*40)print('Epoch',e)print('-'*40)print("Training...")#batchtrainwithrealtimedataaugmentationprogbar=generic_utils.Progbar(data.shape[0])forX_batch,Y_batchin(data,label):loss,accuracy=model.train(X_batch,Y_batch,accuracy=True)(X_batch.shape[0],values=[("trainloss",loss),("accuracy:",accuracy)])"""。

怎么用python 中brian包进行神经网络简化模型

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

作者:王赟Maigo链接:来源:知乎就我所知,Python有一个Theano库可以利用GPU进行矩阵运算和符号求导,在此基础上有PDNN等专门训练神经网络的工具包(PDNN是我实验室的同学开发的~)。

Matlab那边我不了解,随便搜了一下发现了一个DeepNeuralNetworksforMatlab。因为没有用过,所以不好评价。

怎么用python训练神经网络

如果觉得《神经网络模型的训练过程 神经网络模型训练过程》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。