1. 程式人生 > >深度學習框架---keras的層次示意圖---方便直觀理解---適用sklearn模型的展示

深度學習框架---keras的層次示意圖---方便直觀理解---適用sklearn模型的展示

感覺keras確實比其他框架舒服一點,但是前期理解keras層的時候可能有點小問題,keras的層使用了原始神經網路層的概念,即先有上層的輸出聚合,聚合後在進入啟用函式。我的環境是python3.5+tensorflow+keras+graphviz+pydot_ng+pydotplus

其中

安裝好Python3以及pip之後

執行: 

pip install tensorflow

pip install keras

下載(https://www.cnblogs.com/fengbohello/p/4689131.html,這篇作者提供了graphviz.msi下載地址,官網不好使,可以從作者提供的路徑下到

)graphviz.msi並配置好路徑

執行 pip install pydot_ng

pip install pydotplus

修改檔案

python\Lib\site-packages\pydot_ng\__init__.py

def find_graphviz()中的

 
# Method 3 (Windows only)
if os.sys.platform == 'win32':

    # Try and work out the equivalent of "C:\Program Files" on this
    # machine (might be on drive D:, or in a different language)
if 'PROGRAMFILES' in os.environ: # Note, we could also use the win32api to get this # information, but win32api may not be installed. path = os.path.join(os.environ['PROGRAMFILES'], 'ATT', 'GraphViz', 'bin') else: #Just in case, try the default... path = r"....\Graphviz2.37\bin"
Graphviz的路徑

 python\Lib\site-packages\pydotplus\相應的檔案也做相應的修改
 

 
然後就可以測試下面的程式碼了

 

from keras.utils.vis_utils import plot_model
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.embeddings import Embedding
from keras.layers import Input , Dense
from keras.models import Model

model = Sequential()
model.add(Dense(4, input_dim=200))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(200))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(100))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(50))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(20, input_dim=3))
model.add(Activation('softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam', class_mode="binary")
plot_model(model, to_file='model1.png',show_shapes=True)
對應的結構圖為:




sklearn中的模型展示(python3),在http://blog.csdn.net/shouwangzhelv/article/details/51163535基礎上做了修改

from sklearn.datasets import load_iris
from sklearn import tree
from sklearn.externals.six import StringIO
import pydot_ng
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data)
graph = pydot_ng.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("iris.pdf")


如果想畫xgboost的樹

from xgboost import XGBClassifier
import xgboost as xgb

import pandas as pd
import numpy as np

from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import StratifiedKFold

from matplotlib import pyplot as plt
from xgboost import plot_tree
x,y = "..."

    mode = XGBClassifier()

    mode.fit(x,y)

    plot_tree(mode)

    plt.show()