About Keras (ubuntu14.04,python2.7)

Source: Internet
Author: User
Tags random shuffle shuffle keras

Part I: Installation

Since my computer was already configured with Caffe, all the related packages for Python have been installed. Therefore, even without Anaconda installation is still very simple.

sudo pip install TensorFlow

sudo pip install Keras

Test:

Python

from keras.models import Sequential

The second part: How to use Keras to read pictures from the local, and do a two classification of the neural network, directly posted code:

#Coding=utf-8##ImportOs##和文件目录相关的都用到该模块"" " fromPILImportImage##python Imaging Library "" "ImportNumPy as NP#import a variety of module components to use#From keras.preprocessing.image import imagedatagenerator fromKeras.modelsImportSequential fromKeras.layers.coreImportdense, dropout, Activation, Flatten fromKeras.layers.advanced_activationsImportPrelu fromKeras.layers.convolutionalImportconvolution2d, maxpooling2d, Zeropadding2d fromKeras.optimizersImportSGD, Adadelta, Adagrad fromKeras.utilsImportNp_utils, Generic_utilsdef __getnum__(path):##统计样本数目的函数fm=Os.listdir (path) I=0 forFinchFm:##对于在fm中的文件I+=1returnIdefLoad_data (Path,count):##数据转换函数data = Np.empty ((count,100,100,3), dtype="float32") Label= Np.empty ((count,), dtype="int") IMGs=os.listdir (path) Num=Len (IMGs) forIinchrange (num): IMG= Image.open (path+imgs[i]) arr= Np.asarray (img,dtype="float32") Data[i,:,:,:]=arr##print i        ifI<NUM/2:##前一半label为0, the latter part of the data label is 1Label[i] =Int (0)Else: Label[i]= Int (1)         returnData,label################Start building a CNN model################Generate a modeldef __cnn__(Testdata,testlabel,traindata,trainlabel): Model=Sequential ()#The first convolution layer, 4 convolution cores, each convolution core size 5*5. 1 represents the channel of the imported picture, and the grayscale image is 1 channels. Model.add (convolution2d, 5, 5, border_mode='valid', Input_shape= (100,100,3)) ) Model.add (Activation ('Relu')) Model.add (Dropout (0.5)) Model.add (Maxpooling2d (pool_size= (2, 2)))    #the second convolution layer, 30 convolution cores, each convolution core size 5*5.     #using Maxpooling,poolsize for (2,2)Model.add (convolution2d, 3, 3, border_mode='valid')) Model.add (Activation ('Relu')) Model.add (Maxpooling2d (pool_size= (2, 2)))    #The third convolution layer, 16 convolution cores, each convolution core size 3*3    #activation function with Tanh    #using Maxpooling,poolsize for (2,2)Model.add (convolution2d (3, 3, border_mode='valid')) Model.add (Activation ('Tanh')) Model.add (Maxpooling2d (pool_size= (2, 2)) Model.add (Flatten ()) Model.add (Dense (Init=,'Normal')) Model.add (Activation ('Relu'))    #Softmax Classification, output is 4 categoryModel.add (Dense (2, init='Normal')) Model.add (Activation ('Softmax'))## # #训练模型 #using SGD + momentum ImpulseSGD = SGD (lr=0.05, decay=1e-6, momentum=0.9, nesterov=True) model.compile (loss='binary_crossentropy', optimizer=sgd,metrics=['accuracy'])    #to begin training, the show_accuracy shows the correct rate after each iteration.  Batch_size is the number of samples that are brought into the training each time, Nb_epoch is the number of iterations, and shuffle is a random shuffle of the sample. Model.fit (Traindata, Trainlabel, batch_size=20,epochs=100)    #set up test evaluation parameters, use test set samplesModel.evaluate (TestData, TestLabel, batch_size=20)#############Main module############Trainpath ='/home/lyyang/keras/data/train/'Testpath='/home/lyyang/keras/data/test/'Testcount=__getnum__(Testpath) Traincount=__getnum__(Trainpath)#Print Testcount#Print TraincountTestdata,testlabel=Load_data (testpath,testcount) Traindata,trainlabel=Load_data (Trainpath,traincount)#Print Testlabel.shape#Print TestLabel#Print Trainlabel.shape#Print Trainlabel#label for 0~1 a total of 2 categories, Keras requires the format of binary class matrices, conversion, directly call Keras provided by this functionTestLabel = Np_utils.to_categorical (TestLabel, 2) Trainlabel= Np_utils.to_categorical (Trainlabel, 2)__cnn__(TestData, TestLabel, Traindata, Trainlabel)

Using cat and dog data to classify, data can be downloaded on the Kaggle website.

Run,

Python

Python ***.py

However, I do not have a Python IDE configured, and I feel it is not convenient to write large project.

About Keras (ubuntu14.04,python2.7)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.