深度学习框架---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.****.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()