1. 程式人生 > >[3]深度學習和Keras----Keras深度學習框架入門例子

[3]深度學習和Keras----Keras深度學習框架入門例子

只要是程式設計師都知道,學習一門新的語言或者框架的時候,第一個自己敲入且執行的程式,都一個HelloWorld的程式、筆者也不例外,當筆者把Keras在Unbuntu系統安裝好之後,早已掩蓋不住激動的心,然後想在Keras上面執行一個HelloWorld的例子。後面筆者參考了莫愁同學的Keras的學習視訊,上面提到了一個用Keras的API去反推出一個線性函式的例子,感覺非常的有趣,所有就模擬敲入了一把,現在讓我給大家來逐一解釋一下,解釋不到位的地方,還請海涵,畢竟也是樓主第一次接觸Keras框架。所有的程式碼全部黏貼出來,檔名為helloworld.py,如下,具體解釋請看程式碼中的註釋。

# Import package
import numpy as np
np.random.seed(1337)
from keras.models import Sequential
from keras.layers import Dense
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

# 1.Build the trainning data
X=np.linspace(-1,1,200)
np.random.shuffle(X)
np.random.normal()
Y=0.5*X+2+np.random.normal(0,0.05,(200,))
plt.scatter(X,Y)
plt.show()
X_train,Y_train=X[:160],Y[:160]
X_test,Y_test=X[160:],Y[160:]
print(X)
print("*******************************************")
print(Y)

# 2.Build a neural network from the 1st layer to the last layer
model=Sequential()
model.add(Dense(output_dim=1,input_dim=1))

#3. Choose loss function and optimzing method
model.compile(loss='mse',optimizer='sgd')

#4. Trainning
print("Training......")
for step in range(1400):
        cost=model.train_on_batch(X_train,Y_train)
        if step % 100 ==0:
                print('train cost',cost)
#5.Test
print("\n Testing...........")
cost=model.evaluate(X_test,Y_test,batch_size=40)
print("Test cost:",cost)
W,b=model.layers[0].get_weights()
print('Weight=',W,"\nbiases=",b)

#6.Plotting the prediction
Y_pred=model.predict(X_test)
plt.scatter(X_test,Y_test)
plt.plot(X_test,Y_pred)
plt.show()


執行後的結果如下:

[email protected]:~/keraslearn$ python3 helloworld.py
Using TensorFlow backend.
[-0.70854271  0.1758794  -0.30653266  0.74874372 -0.02512563  0.33668342
 -0.85929648  0.01507538 -0.13567839  0.72864322  0.24623116 -0.74874372
 -0.78894472  0.50753769  0.03517588  0.35678392 -0.55778894  0.2361809
 -0.25628141 -0.44723618  0.2160804  -0.43718593 -0.64824121  0.69849246
 -0.03517588 -0.45728643  0.86934673  0.73869347  0.53768844 -0.67839196
 -0.75879397  0.55778894  0.28643216 -0.05527638 -0.86934673  0.1959799
 -0.57788945 -0.9798995  -0.6080402  -0.63819095  0.84924623  0.41708543
  0.13567839  0.79899497 -0.47738693  0.46733668  0.59798995 -0.80904523
 -0.98994975 -0.36683417 -0.5678392  -0.00502513 -0.53768844 -0.37688442
 -0.65829146 -0.1959799   0.06532663  0.44723618 -0.01507538 -0.6281407
  0.02512563 -0.71859296 -0.14572864 -0.46733668  0.07537688  0.85929648
  0.76884422  0.40703518 -0.68844221  0.68844221 -0.29648241  0.66834171
 -0.95979899 -0.33668342  0.26633166 -0.82914573  1.         -0.5879397
 -0.69849246 -0.20603015  0.63819095 -0.88944724 -0.40703518 -0.32663317
  0.15577889 -0.41708543  0.10552764  0.20603015 -0.04522613  0.00502513
 -0.31658291  0.43718593  0.42713568  0.45728643 -0.59798995 -0.66834171
  0.83919598  0.75879397 -0.24623116  0.71859296 -0.92964824  0.39698492
  0.61809045 -0.84924623 -0.87939698 -0.96984925  0.87939698  0.6281407
  0.25628141  0.27638191  0.12562814  0.09547739 -0.89949749  0.80904523
 -0.16582915 -0.12562814  0.30653266  0.49748744  0.5879397  -0.51758794
 -0.10552764  0.54773869 -0.94974874  0.92964824  0.16582915 -0.83919598
 -0.35678392 -0.48743719  0.08542714 -0.61809045  0.18592965  0.57788945
  0.65829146  0.38693467  0.91959799 -0.26633166 -0.50753769 -1.
 -0.54773869  0.6080402  -0.49748744 -0.22613065  0.9798995   0.98994975
  0.5678392   0.32663317  0.64824121 -0.52763819  0.36683417  0.81909548
 -0.11557789  0.31658291 -0.2160804   0.95979899  0.77889447 -0.73869347
 -0.81909548 -0.79899497  0.78894472  0.88944724 -0.2361809   0.37688442
  0.70854271  0.22613065 -0.28643216 -0.38693467  0.90954774 -0.91959799
  0.48743719 -0.42713568 -0.08542714  0.11557789 -0.18592965  0.47738693
 -0.39698492 -0.34673367  0.04522613  0.05527638  0.93969849 -0.77889447
 -0.93969849 -0.06532663 -0.72864322  0.29648241  0.52763819 -0.76884422
  0.94974874  0.82914573  0.34673367 -0.90954774 -0.27638191 -0.15577889
 -0.1758794   0.14572864 -0.09547739  0.96984925  0.67839196 -0.07537688
  0.89949749  0.51758794]
*******************************************
[ 1.67999883  2.15732476  1.86215827  2.35166736  1.93572236  2.18016038
  1.61608065  2.03423062  1.99563479  2.37665292  2.18481192  1.68394294
  1.62204409  2.26767077  1.98888272  2.22171139  1.71104094  2.17892658
  1.91484027  1.82024419  2.16604711  1.81951961  1.54483872  2.34601517
  2.00887174  1.77313928  2.37743864  2.31814604  2.32716849  1.68305339
  1.60808704  2.24648868  2.26423579  1.96845047  1.66389213  2.1151824
  1.76544914  1.5408011   1.68818555  1.65445629  2.34232127  2.21861488
  2.07349814  2.44520484  1.68813908  2.23841182  2.28008276  1.61527365
  1.45239671  1.86837714  1.73063808  2.01510789  1.78710972  1.81579434
  1.7282564   1.88204563  2.12479282  2.27787801  2.04415445  1.64586279
  2.02443768  1.69792605  1.90274178  1.78137239  2.02497528  2.42132526
  2.42777448  2.16564271  1.68763444  2.31923599  1.81271447  2.34163208
  1.48248635  1.78163246  2.0686663   1.56576829  2.57615655  1.65904659
  1.57722512  1.81629077  2.26556137  1.61007302  1.88352331  1.71313059
  2.10104146  1.7038275   1.97249884  2.10127479  2.07381404  2.11472407
  1.83211308  2.26576731  2.23235442  2.28700014  1.72663184  1.71425067
  2.44958621  2.48620331  1.89267965  2.35438093  1.57974268  2.22254286
  2.23280715  1.50250543  1.58598131  1.40667751  2.50025819  2.37980426
  2.19965578  2.12256837  2.05612666  1.98159549  1.49287023  2.43805289
  1.87463195  2.04988238  2.12882858  2.2546237   2.34223092  1.65392499
  1.99025412  2.28291716  1.45807616  2.51044748  1.97988068  1.66059626
  1.7961923   1.75129171  2.0241939   1.69914728  2.07346622  2.33384759
  2.35610171  2.22847144  2.39450148  1.84129314  1.69452659  1.55065089
  1.66503047  2.28833885  1.65681898  1.9227888   2.46308462  2.55316759
  2.3420487   2.1586477   2.31608103  1.72595194  2.20947867  2.43358179
  1.92711345  2.09783848  1.90011119  2.3742013   2.39525115  1.61921788
  1.60036827  1.61487721  2.32314506  2.47010224  1.78412147  2.20253779
  2.29520865  2.13392445  1.88572837  1.80240843  2.37782058  1.53947432
  2.21682792  1.80241496  1.9832941   2.19691473  1.98446141  2.25189264
  1.79373247  1.91751681  2.04975192  1.95401037  2.47210723  1.64954777
  1.53229024  1.89811048  1.56746323  2.10295781  2.18903255  1.5645517
  2.47228584  2.29823263  2.17956294  1.51738366  1.86618515  1.92440005
  1.77639738  2.04854509  1.89432423  2.44443885  2.40954465  1.93669521
  2.4738211   2.26099266]
helloworld.py:25: UserWarning: Update your `Dense` call to the Keras 2 API: `Dense(units=1, input_dim=1)`
  model.add(Dense(output_dim=1,input_dim=1))
Training......
2017-05-30 13:52:34.569118: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-30 13:52:34.569158: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-30 13:52:34.569165: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-05-30 13:52:34.569169: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-30 13:52:34.569176: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
train cost 4.02812
train cost 0.0807406
train cost 0.00588549
train cost 0.00316872
train cost 0.00276465
train cost 0.00266697
train cost 0.00264223
train cost 0.00263594
train cost 0.00263434
train cost 0.00263394
train cost 0.00263383
train cost 0.00263381
train cost 0.0026338
train cost 0.0026338

 Testing...........
40/40 [==============================] - 0s
Test cost: 0.00337669742294
Weight= [[ 0.5063296]]
biases= [ 2.00427961]

@ 匯入相關的Python和Keras的模組(module)

import numpy as np
np.random.seed(1337)
from keras.models import Sequential
from keras.layers import Dense
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
需要特別注意的是,如果在Ubuntu下,如果我們用的遠端命令列方式,因為在遠端命令列的環境下顯示不了圖形介面,所以需要加入下面的兩行程式碼,否則會執行報錯。
import matplotlib
matplotlib.use('Agg')

但是在Ubuntu的圖形化介面下(比如,遠端桌面)不需要。

@ 隨機生成200個數字並模擬一個線性函式

隨機生成200個範圍在-1到1之間一個浮點數。並模擬一個線性函式的公式,0.5*X+2 並加上一些隨機的干擾,生成200個函式結果Y

然後從中抽選出160組資料作為訓練資料,40組作為測試訓練的結果的資料。

# 1.Build the trainning data
X=np.linspace(-1,1,200)
np.random.shuffle(X)
np.random.normal()
Y=0.5*X+2+np.random.normal(0,0.05,(200,))
plt.scatter(X,Y)
plt.show()
X_train,Y_train=X[:160],Y[:160]
X_test,Y_test=X[160:],Y[160:]
print(X)
print("*******************************************")
print(Y)
把下面的兩行註釋掉,並在Ubuntu的圖形介面模式下,顯示出來的圖形效果如下:
import matplotlib
matplotlib.use('Agg')

@ 用Keras的API建立一個神經網路模型

這個模型是總共有隻要一層,1個輸入和一個輸出,建立好神經網路後,選擇損失函式和優化器。從下面的程式碼來看,其實還是非常的簡潔的,如果用TensorFlow或者Theano實現的話,程式碼會多不少,但是用Keras實現非常的簡潔和簡單。

# 2.Build a neural network from the 1st layer to the last layer
model=Sequential()
model.add(Dense(output_dim=1,input_dim=1))

#3. Choose loss function and optimzing method
model.compile(loss='mse',optimizer='sgd')
損失函式只要有下面的幾種:
  • mean_squared_error
  • mean_absolute_error
  • mean_absolute_percentage_error
  • mean_squared_logarithmic_error
  • squared_hinge
  • hinge
  • logcosh
  • categorical_crossentropy
  • sparse_categorical_crossentropy
  • binary_crossentropy
  • kullback_leibler_divergence
  • poisson
  • cosine_proximity

具體的意思,請參考:

https://keras.io/losses/

https://github.com/fchollet/keras/blob/master/keras/losses.py

我們當前選擇的是:sgd,其支援,隨機梯度下降法,支援動量引數,支援學習衰減率,支援Nesterov動量。

此外還有優化器:

  • RMSprop
  • Adagrad
  • Adadelta
  • Adam
  • Adamax
  • Nadam
  • TFOptimizer

不同的優化器有有不同的適用場景,限於篇幅,請讀者自己補腦和查詢相關資料。

@ 分批次訓練

批次的次數不是越多越好,在當前的例子中,批次的訓練次數達到1300次左右基本上已經達到損失函式能夠達到的最好的結果了,在增加次數也增加了不了精度。具體請見
日誌的輸出。
#4. Trainning
print("Training......")
for step in range(1400):
        cost=model.train_on_batch(X_train,Y_train)
        if step % 100 ==0:
                print('train cost',cost)

@ 測試資料測試訓練結果。

在上面的部分,經過1400次的分批次訓練,神經網路已經完全模擬出了上面的線性函式的模型。這個時候代入剩下的40組測試資料進行測試。我們會發現0.5*X+2 這個線性函式完全被建立起來了。從輸出的weight和biases的值其實就是上面的0.5和2; weight和0.5越接近,說明效果越好;biases和2越接近說明效果越好。
#5.Test
print("\n Testing...........")
cost=model.evaluate(X_test,Y_test,batch_size=40)
print("Test cost:",cost)
W,b=model.layers[0].get_weights()
print('Weight=',W,"\nbiases=",b)

@ Keras模型結果 VS 原始測試資料結果

把通過神經網路得出的結果與原始的測試結果得出的結果進行比較,並顯示其對比影象。
#6.Plotting the prediction
Y_pred=model.predict(X_test)
plt.scatter(X_test,Y_test)
plt.plot(X_test,Y_pred)
plt.show()

相關推薦

[3]深度學習Keras----Keras深度學習框架入門例子

只要是程式設計師都知道,學習一門新的語言或者框架的時候,第一個自己敲入且執行的程式,都一個HelloWorld的程式、筆者也不例外,當筆者把Keras在Unbuntu系統安裝好之後,早已掩蓋不住激動的心,然後想在Keras上面執行一個HelloWorld的例子。後面筆者參考了

python的學習注意點初學的幾個例子

第一天學習的總結: 1.瞭解了python的簡史,通俗的講python對於一個沒有開發經驗的小白來講是最容易上手的。 python在linux、windows、mac下的安裝,以及對於python2和python3的抉擇,(建議小白入手3)。 2.字元的編碼和解碼,可見# -*- coding:utf -8

Keras:基於TheanoTensorFlow的深度學習庫之中文文件

  本部落格主要給出某些必備的部分(一直更新中),詳細內容請移步至Github以及MoyanZitto的主頁。 第一部分:快速開始Keras   Keras的核心資料結構是“模型”,模型是一種組織網路層的方式。Keras中主要的模型是Sequ

[4]深度學習Keras----斯坦福的一個可線上執行的卷積神經網路的Demo

學習深度學習,肯定要接觸CNN(卷積神經網路)和RNN(迴圈神經網路),剛好斯坦福大學給出了一個線上的卷積神經網路的例子,方便大家學習和了解深度學習。這個Demo從MNIST資料庫中取出了60000張28X28畫素的圖片作為訓練的樣本;那麼什麼是MNIST資料庫呢》MNIST

【Tensorflow kerasKeras:基於TheanoTensorFlow的深度學習

catalogue 1. 引言 2. 一些基本概念 3. Sequential模型 4. 泛型模型 5. 常用層 6. 卷積層 7. 池化層 8. 遞迴層Recurrent 9. 嵌入層 Embedding 1. 引言 Keras是一

[6]深度學習Keras---- 深度學習中的一些難理解的基礎概念:softmax, batch,min-batch,iterations,epoch,SGD

在進行深度學習的過程中,我們經常會遇到一些自己不懂的概念和術語,比如,softmax, batch,min-batch,iterations,epoch,那麼如何快速和容易的理解這些術語呢? 因為筆者也是深度學習的初學者,所以筆者在學習和瀏覽文章的過程中,把一些自己不太容易和

TensorFlowCaffe、MXNet、Keras深度學習框架的對比

Keras 是一個崇尚極簡、高度模組化的神經網路庫,使用 Python 實現,並可以同時執行在 TensorFlow 和 Theano 上。它旨在讓使用者進行最快速的原型實驗,讓想法變為結果的這個過程最短。Theano 和 TensorFlow 的計算圖支援更通用的計算,而 Keras 則專精於深度學習。Th

[7]深度學習Keras---- 快速入門心得

上個禮拜終於給公司技術達人們分享完了深度學習和Keras,這其中也走過了不少的彎路。比如筆者一上來就開始看Keras,看TenseFlow,看Theano,一下子買了4五本類似的書,結果看了半天,感覺索

keras 深度學習之遷移學習fine tune

一.遷移學習 就是說把別人訓練好的網路(比如說卷積特徵提取部分)拿過來配合上自己分類器,這樣可以增加訓練的速度和提高分類效果。 ''' Created on 2018年8月28日 ''' #遷移學習 import keras from keras.

【火爐煉AI】深度學習009-用Keras遷移學習提升性能(多分類問題)

tro ray size array 全連接 步驟 loss pytho numpy 【火爐煉AI】深度學習009-用Keras遷移學習提升性能(多分類問題) (本文所使用的Python庫和版本號: Python 3.6, Numpy 1.14, scikit-learn

[GAN學習系列3]採用深度學習 TensorFlow 實現圖片修復(上)

在之前的兩篇 GAN 系列文章--[GAN學習系列1]初識GAN以及[GAN學習系列2] GAN的起源中簡單介紹了 GAN 的基本思想和原理,這次就介紹利用 GAN 來做一個圖片修復的應用,主要採用的也是 GAN 在網路結構上的升級版--DCGAN,最初始的 GAN 採用的還是神經網路,即全連線網路,而 DC

深度學習(六)keras常用函式學習

inputs = Input((n_ch, patch_height, patch_width)) conv1 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(inputs) conv1 = Dropout(0.

[GAN學習系列3]採用深度學習 TensorFlow 實現圖片修復(中)

上一篇文章--[GAN學習系列3]採用深度學習和 TensorFlow 實現圖片修復(上)中,我們先介紹了對於影象修復的背景,需要利用什麼資訊來對缺失的區域進行修復,以及將影象當做概率分佈取樣的樣本來看待,通過這個思路來開始進行影象的修復。 這篇文章將繼續介紹原文的第二部分,利用對抗生成網路來快速生成假圖片

2_初學者快速掌握主流深度學習框架Tensorflow、Keras、Pytorch學習程式碼(20181211)

初學者快速掌握主流深度學習框架Tensorflow、Keras、Pytorch學習程式碼 一、TensorFlow 1、資源地址: 2、資源介紹: 3、配置環境: 4、資源目錄: 二、Keras

幾種深度學習模型,keras實現

#coding=utf-8 from keras.models import Sequential from keras.layers import Dense,Flatten from keras.layers.convolutional import Con

ROS開發筆記(9)——ROS 深度強化學習應用之keras版本dqn程式碼分析

在ROS開發筆記(8)中構建了ROS中DQN演算法的開發環境,在此基礎上,對演算法程式碼進行了分析,並做了簡單的修改: 修改1  : 改變了儲存模型引數在迴圈中的位置,原來是每個10整數倍數回合裡面每一步都修改(相當於修改episode_step次),改成了每個10整數倍數

[GAN學習系列3]採用深度學習 TensorFlow 實現圖片修復(下)

這是本文的最後一部分內容了,前兩部分內容的文章: [GAN學習系列3]採用深度學習和 TensorFlow 實現圖片修復(上) [GAN學習系列3]採用深度學習和 TensorFlow 實現圖片修復(中) 以及原文的地址: bamos.github.io/2016/08/09/… 最後一

吳恩達Coursera深度學習課程 deeplearning.ai (5-3) 序列模型注意力機制--程式設計作業(二):觸發字檢測

Part 2: 觸發字檢測 關鍵詞語音喚醒 觸發字檢測 歡迎來到這個專業課程的最終程式設計任務! 在本週的視訊中,你瞭解瞭如何將深度學習應用於語音識別。在本作業中,您將構建一個語音資料集並實現觸發字檢測演算法(有時也稱為關鍵字檢測或喚醒檢測)。觸發字

基於keras深度學習——分類

使用keras的深度學習來分類白葡萄酒還是紅葡萄酒 首先介紹一下資料型別: 1.這個資料集包含了1599種紅酒,4898種白酒; 2.輸入資料特徵: 1 - fixed acidity 2 - volatile acidity 3

吳恩達Coursera深度學習課程 deeplearning.ai (5-3) 序列模型注意力機制--課程筆記

3.1 基礎模型 sequence to sequence sequence to sequence:兩個序列模型組成,前半部分叫做編碼,後半部分叫做解碼。用於機器翻譯。 image to sequence sequence to sequenc