Ejemplo n.º 1
0
    def do_execute_direct(self, code):
        if self._first:
            self._first = False
            self.handle_plot_settings()
            self._do_execute_direct(self._setup)

        self._skipping = os.name != 'nt'
        super(ScilabKernel, self).do_execute_direct(code, self.Print)
        if self.plot_settings.get('backend', None) == 'inline':
            plot_dir = tempfile.mkdtemp()
            self._make_figs(plot_dir)
            width, height = 0, 0
            for fname in os.listdir(plot_dir):
                filename = os.path.join(plot_dir, fname)
                try:
                    if fname.lower().endswith('.svg'):
                        im = SVG(filename)
                        if ',' in self.plot_settings['size']:
                            size = self.plot_settings['size']
                            width, height = size.split(',')
                            width, height = int(width), int(height)
                            im.data = self._fix_svg_size(im.data,
                                size=(width, height))
                    else:
                        im = Image(filename)
                    self.Display(im)
                except Exception as e:
                    self.Error(e)
Ejemplo n.º 2
0
 def _handle_svg(self, filename):
     """
     Handle special considerations for SVG images.
     """
     # Gnuplot can create invalid characters in SVG files.
     with codecs.open(filename, 'r', encoding='utf-8',
                      errors='replace') as fid:
         data = fid.read()
     im = SVG(data=data)
     try:
         im.data = self._fix_svg_size(im.data)
     except Exception:
         pass
     return im
Ejemplo n.º 3
0
    def do_execute_direct(self, code):
        if self._first:
            self._first = False
            if sys.platform == "darwin":
                self.plot_settings["format"] = "svg"
            self.handle_plot_settings()
            super(OctaveKernel, self).do_execute_direct(self._setup)
            if os.name != "nt":
                msg = (
                    "may not be able to display plots properly "
                    "without gnuplot, please install it "
                    "(gnuplot-x11 on Linux)"
                )
                try:
                    subprocess.check_call(["gnuplot", "--version"])
                except subprocess.CalledProcessError:
                    self.Error(msg)

        resp = super(OctaveKernel, self).do_execute_direct(code)

        if self.plot_settings.get("backend", None) == "inline":
            plot_dir = tempfile.mkdtemp()
            self._make_figs(plot_dir)
            width, height = 0, 0
            for fname in os.listdir(plot_dir):
                filename = os.path.join(plot_dir, fname)
                try:
                    if fname.lower().endswith(".svg"):
                        im = SVG(filename)
                        if "," in self.plot_settings["size"]:
                            size = self.plot_settings["size"]
                            width, height = size.split(",")
                            width, height = int(width), int(height)
                            im.data = self._fix_gnuplot_svg_size(im.data, size=(width, height))
                    else:
                        im = Image(filename)
                    self.Display(im)
                except Exception as e:
                    self.Error(e)

        return resp or None
Ejemplo n.º 4
0
    def do_execute_direct(self, code):
        if self._first:
            self._first = False
            self.handle_plot_settings()
            super(OctaveKernel, self).do_execute_direct(self._setup)
            if os.name != 'nt':
                msg = ('may not be able to display plots properly '
                       'without gnuplot, please install it '
                       '(gnuplot-x11 on Linux)')
                try:
                    subprocess.check_call(['gnuplot', '--version'])
                except subprocess.CalledProcessError:
                    self.Error(msg)

        super(OctaveKernel, self).do_execute_direct(code, self.Print)
        if self.plot_settings.get('backend', None) == 'inline':
            plot_dir = tempfile.mkdtemp()
            self._make_figs(plot_dir)
            width, height = 0, 0
            for fname in os.listdir(plot_dir):
                filename = os.path.join(plot_dir, fname)
                try:
                    if fname.lower().endswith('.svg'):
                        im = SVG(filename)
                        size = self.plot_settings['size']
                        if not (isinstance(size, tuple)):
                            size = 560, 420
                        width, height = size
                        width, height = int(width), int(height)
                        im.data = self._fix_gnuplot_svg_size(im.data,
                            size=(width, height))
                    else:
                        im = Image(filename)
                    self.Display(im)
                except Exception as e:
                    import traceback
                    traceback.print_exc(file=sys.__stderr__)
                    self.Error(e)
Ejemplo n.º 5
0
        counts["best_move"].append(best_move)
        counts["best_move_score"].append(next_scores[0])
        best_move_score_diff = abs(next_scores[0] - score)
        counts["best_move_score_diff"].append(best_move_score_diff)
        counts["best_move_score_diff_category"].append(
            categorize_best_move_score_diff(best_move_score_diff, best_move, actual_move))
    else:
        counts["best_move"].append("-")
        counts["best_move_score"].append(0)
        counts["best_move_score_diff"].append(0)

        # push actual move to the board again
    board.push(move)
    exportBoardSVG('output/' + filename + '/images/', len(counts["san"]))

SVG(chess.svg.board(board=board, size=400))

# use plotly to visualize the chess game in a line graph
import plotly
# import plotly.plotly as py
import plotly.graph_objs as go
import plotly.io as pio

# plotly.tools.set_credentials_file(username='******', api_key='••••••••••')
plotly.offline.init_notebook_mode(connected=True)

checkcolor = ['red' if i else 'white' for i in counts["is_check"]]
checknr = [i for (i, s) in enumerate(counts["is_check"]) if s]
bubble = [s / 2 for s in counts["move_count"]]
# best = [np.log(s+1) for s in counts["bestdiff"]]
# best = [s for s in counts["bestdiff"]]
Ejemplo n.º 6
0
    def draw(self, filename=None, opts={}, **kwargs):
        """
        filename specifies the name of the file to produce.  If None,
        the schematic is displayed on the screen.

        Note, if using Jupyter, then need to first issue command %matplotlib inline

        kwargs include:
           label_ids: True to show component ids
           label_values: True to display component values
           draw_nodes: True to show all nodes, False to show no nodes, 
             'primary' to show primary nodes,
             'connections' to show nodes that connect more than two components,
             'all' to show all nodes
           label_nodes: True to label all nodes, False to label no nodes, 
             'primary' to label primary nodes,
             'alpha' to label nodes starting with a letter,
             'pins' to label nodes that are pins on a chip,
             'all' to label all nodes
           style: 'american', 'british', or 'european'
           scale: schematic scale factor, default 1.0
           node_spacing: spacing between component nodes, default 2.0
           cpt_size: size of a component, default 1.5
           oversample: oversampling factor for png or pdf files
           help_lines: distance between lines in grid, default 0.0 (disabled)
           debug: True to display debug information
        """

        for key, val in opts.items():
            if key not in kwargs or kwargs[key] is None:
                kwargs[key] = val

        def in_ipynb():
            try:
                ip = get_ipython()
                cfg = ip.config

                kernapp = cfg['IPKernelApp']

                # Check if processing ipynb file.
                if 'connection_file' in kernapp:
                    return True
                elif kernapp and kernapp[
                        'parent_appname'] == 'ipython-notebook':
                    return True
                else:
                    return False
            except (NameError, KeyError):
                return False

        if not self.hints:
            raise RuntimeWarning('No schematic drawing hints provided!')

        png = 'png' in kwargs and kwargs.pop('png')
        svg = 'svg' in kwargs and kwargs.pop('svg')

        if not png and not svg:
            png = True

        if in_ipynb() and filename is None:

            if png:
                from IPython.display import Image, display_png

                pngfilename = tmpfilename('.png')
                self.tikz_draw(pngfilename, **kwargs)

                # Create and display PNG image object.
                # There are two problems:
                # 1. The image metadata (width, height) is ignored
                #    when the ipynb file is loaded.
                # 2. The image metadata (width, height) is not stored
                #    when the ipynb file is written non-interactively.
                display_png(
                    Image(filename=pngfilename,
                          width=self.width * 100,
                          height=self.height * 100))
                return

            if svg:
                from IPython.display import SVG, display_svg

                svgfilename = tmpfilename('.svg')
                self.tikz_draw(svgfilename, **kwargs)

                # Create and display SVG image object.
                # Note, there is a problem displaying multiple SVG
                # files since the later ones inherit the namespace of
                # the first ones.
                display_svg(
                    SVG(filename=pngfilename,
                        width=self.width * 100,
                        height=self.height * 100))
                return

        if filename is None:
            filename = tmpfilename('.png')
            self.tikz_draw(filename=filename, **kwargs)
            display_matplotlib(filename)
            return

        self.tikz_draw(filename=filename, **kwargs)
Ejemplo n.º 7
0
def plot_model(model):
    return SVG(model_to_dot(model).create(prog='dot', format='svg'))
Ejemplo n.º 8
0
    def viewms(objs,wo3d=F,nmr=8,molSize=(100,80),wlgd=T,wlgd_text='smiles', labels=None, \
               wia=T,woH=T,kekulize=T,atsh=[],bsh=[],colors=[],filename=None):
        """
        vars
        atsh : atoms to be highlighted (list)
        """
        mols, strings = draw_rdkit.str2mol(objs, woH=woH)
        mcs = []
        _labels = []
        nat = 0
        nm = len(mols)
        smis = []
        for mol in mols:
            labels_i = [
                chemical_symbols[ai.GetAtomicNum()] + '%d' % (ai.GetIdx() + 1)
                for ai in mol.GetAtoms()
            ]
            nat += len(labels_i)
            _labels += labels_i
            mc = Chem.Mol(mol.ToBinary())
            if kekulize:
                try:
                    Chem.Kekulize(mc)
                except:
                    mc = Chem.Mol(mol.ToBinary())
            c2d = F
            if mc.GetNumConformers():
                if wo3d:
                    c2d = T
            else:
                c2d = T
            if c2d: rdDepictor.Compute2DCoords(mc)
            smis.append(Chem.MolToSmiles(mc))
            mcs.append(mc)
        #print('labels=',labels)

        molsPerRow = nmr  #5
        subImgSize = molSize

        nRows = len(mols) // molsPerRow
        if len(mols) % molsPerRow:
            nRows += 1
        fsize = (molsPerRow * subImgSize[0], nRows * subImgSize[1])

        dw, dh = 0, 0
        drawer = rdMolDraw2D.MolDraw2DSVG(fsize[0] + dw, fsize[1] + dh,
                                          subImgSize[0], subImgSize[1])

        opts = drawer.drawOptions()
        ## [bad news] opts seems to be able to accept only the first `na1 labels (where na1=len(mols[0]))
        #for i in range(nat):
        #    opts.atomLabels[i] = labels[i]

        if labels:
            labs = labels
        else:
            if wlgd_text in ['id']:
                labs = [str(i + 1) for i in range(nm)]  #rows*cols) ]
            elif wlgd_text in [
                    'smiles',
            ]:
                labs = smis
            elif wlgd_text in ['file', 'filename']:
                assert len(fs) > 1, '#ERROR: input objs are not files!!'
                labs = [fi.split('/')[-1] for fi in fs]
            else:
                raise Exception('invalid `wlgd_text')

        drawer.DrawMolecules(mcs, legends=labs)

        drawer.FinishDrawing()
        svg = drawer.GetDrawingText()
        # It seems that the svg renderer used doesn't quite hit the spec.
        # Here are some fixes to make it work in the notebook, although I think
        # the underlying issue needs to be resolved at the generation step

        if filename is not None:
            open(filename + '.svg', 'w').write(svg)
            try:
                import cairosvg
                cairosvg.svg2pdf(url='%s.svg' % filename,
                                 write_to='%s.pdf' % filename)
            except:
                raise Exception(
                    '#ERROR: svg to pdf failed, as cairosvg seems to be not installed?'
                )
        return SVG(svg.replace('svg:', ''))
                         output_dim=embedding_dim, 
                         input_length=400))
# mlp.add(layers.Flatten())
mlp.add(layers.GlobalMaxPool1D())
mlp.add(layers.Dense(128, activation='relu', kernel_regularizer = regularizers.l2(l = 0.001)))
mlp.add(layers.Dropout(0.5))
mlp.add(layers.Dense(64, activation='relu', kernel_regularizer = regularizers.l2(l = 0.001)))
mlp.add(layers.Dropout(0.5))
mlp.add(layers.Dense(7, activation='softmax'))
mlp.compile(optimizer='adam',
            loss='categorical_crossentropy',
            metrics=['accuracy'],
           )
mlp.summary()

SVG(model_to_dot(mlp, show_shapes=True, show_layer_names=False).create(prog='dot', format='svg'))

"""#### Measure performance of MLP"""

import matplotlib.pyplot as plt
plt.style.use('ggplot')

def plot_history(history):
    acc = history.history['acc']
    val_acc = history.history['val_acc']
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    x = range(1, len(acc) + 1)

    plt.figure(figsize=(12, 5))
    plt.subplot(1, 2, 1)
acc = accuracy_score(testY, predY)

#confusion matrix calculation
cfm = confusion_matrix(testY, predY, labels=[0, 1])
print('Confusion Matrix:\n', cfm)
print('\nAccuracy: ', acc)

# calculating per class precision and per class recall
precision = []
recall = []
precision.append(cfm[0, 0] / (cfm[0, 0] + cfm[1, 0]))
precision.append(cfm[1, 1] / (cfm[0, 1] + cfm[1, 1]))
recall.append(cfm[0, 0] / (cfm[0, 0] + cfm[0, 1]))
recall.append(cfm[1, 1] / (cfm[1, 0] + cfm[1, 1]))

print('\nPrecision: ', precision)
print('\nRecall: ', recall)

# Decision tree visualization

# Note: Decision tree is huge,
# so some times it feels like there is no output, to see the whole tree please scroll down

print("\nTree Visualization")
graph = Source(
    tree.export_graphviz(
        clf,
        out_file=None,
        feature_names=['Occupation', 'Marital_Status', 'Age', 'Gender']))
SVG(graph.pipe(format='svg'))
Ejemplo n.º 11
0
tech_rets = closing_df.pct_change()
tech_rets.head()

# In[59]:

sns.jointplot('GOOG', 'GOOG', tech_rets, kind="scatter", color='seagreen')

# In[60]:

sns.jointplot('GOOG', 'MSFT', tech_rets, kind="scatter")

# In[61]:

from IPython.display import SVG
SVG(url=
    'http://upload.wikimedia.org/wikipedia/commons/d/d4/Correlation_examples2.svg'
    )

# In[63]:

#correlation between different stocks
sns.pairplot(tech_rets.dropna())

# In[66]:

return_fig = sns.PairGrid(tech_rets.dropna())
return_fig.map_upper(plt.scatter, color='purple')
return_fig.map_lower(sns.kdeplot, cmap='cool_d')
return_fig.map_diag(plt.hist, bins=30)

# In[67]:
Ejemplo n.º 12
0
        
movehistory =[]
board = chess.Board()
boardvalue = init_evaluate_board()
i = 1
x = 5 

if move == 0:
    print (board)
    if color == "black":
        while not board.is_game_over(claim_draw=True):
           ponder = 0
           mov = selectmove(x)
           make_move(mov)
           print (mov)
           SVG(chess.svg.board(board=board,size=400,lastmove=mov))
           print (board)
           playermove = input ("what is your move?")
                        
           board.push_san(playermove)
           print(board)
    if color == "white":
           while not board.is_game_over(claim_draw=True):
               ponder = 1
               playermove = input ("what is your move?")
               board.push_san(playermove)
               print (board)
               ponder = 0
               mov = selectmove(x)
               make_move(mov)
               print (mov)
Ejemplo n.º 13
0
 def draw(self):
     return SVG(self.graph.draw(format='svg', prog='dot'))
Ejemplo n.º 14
0
from IPython.display import SVG

from keras.utils.vis_utils import model_to_dot
from keras.utils import plot_model
import pydot
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

#启动神经网络
network = models.Sequential()
#添加使用ReLU激活函数的全连接层
network.add(layers.Dense(units=16, activation="relu", input_shape=(10, )))
#添加使用ReLU激活函数的全连接层
network.add(layers.Dense(units=16, activation="relu"))
#添加使用sigmoid激活函数的全连接层
network.add(layers.Dense(units=1, activation="sigmoid"))

#可视化网络结构
#SVG(model_to_dot(network,show_shapes=False).create(prog="dot",format="svg"))
#keras提供了工具函数用于快速可视化神经网络
#model_to_dot可以显示一个神经网络
# show_shapes 参数指定是否展示输入输出的形状,可以帮助我们调试网络

#将可视化后的网络结构图保存为文件
#plot_model(network,show_shapes=True,to_file="network.png")

#展示一个更加简单的网络模型
SVG(model_to_dot(network, show_shapes=False).create(prog="dot", format="svg"))
plot_model(network, show_shapes=True, to_file="network.png")
Ejemplo n.º 15
0
def plot_network(network):
    from IPython.display import SVG
    from keras.utils.vis_utils import model_to_dot
    SVG(model_to_dot(network).create(prog='dot', format='svg'))
def show_model(model):
    return SVG(
        model_to_dot(model, show_shapes=True,
                     show_layer_names=False).create(prog='dot', format='svg'))
Ejemplo n.º 17
0
 def svg(self):
     from IPython.display import SVG
     return SVG(self._repr_svg_())
Ejemplo n.º 18
0
def viz_model_architecture(model):
    """Visualize model architecture in Jupyter notebook."""
    display(SVG(model_to_dot(model).create(prog='dot', format='svg')))
Ejemplo n.º 19
0
at https://www.debuggingbook.org/html/Tours.html
'''

# Allow to use 'from . import <module>' when run as script (cf. PEP 366)
if __name__ == '__main__' and __package__ is None:
    __package__ = 'debuggingbook'

# Tours through the Book
# ======================

if __name__ == '__main__':
    print('# Tours through the Book')

if __name__ == '__main__':
    from IPython.display import SVG

if __name__ == '__main__':
    SVG(filename='PICS/Sitemap.svg')

## The Pragmatic Programmer Tour
## -----------------------------

if __name__ == '__main__':
    print('\n## The Pragmatic Programmer Tour')

## Lessons Learned
## ---------------

if __name__ == '__main__':
    print('\n## Lessons Learned')
Ejemplo n.º 20
0
    etree.Element("rect", {
        "width": "100%",
        "height": "100%",
        "fill": "white"
    }),
    panel_1a,
    panel_1b,
    panel_1c,
    panel_1dleft,
    panel_1dright,
    panel_1a_label,
    panel_1b_label,
    panel_1c_label,
    panel_1d_label,
])
display(SVG(figure_1.to_str()))

# save generated SVG files
figure_1.save("output/figure_1.svg")

# ## Figure 2

# Create panels for figure 2
panel_2a = make_figure_panel("fig2A.svg",
                             scale_x_input=2,
                             scale_y_input=2,
                             x_loc=30,
                             y_loc=10)
panel_2b = make_figure_panel(
    "../human_cancer_analysis/gene_ranking_logFC.svg",
    scale_x_input=0.6,
Ejemplo n.º 21
0
# coding: utf-8
# Conv2Dを使ったCNNの例

# CNN Model 3 - zero padding
# Kerasとその他ライブラリをインポート
from keras.models import Sequential, Model
from keras.layers import Conv2D
from keras.utils import np_utils

# SVGの表示に必要なライブラリのインポート
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot

# Windows の場合は以下を追加
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'

# パディングつき畳み込みニューラルネットワークのモデルを作成
model = Sequential()
model.add(Conv2D(filters=3, kernel_size=(3, 3), input_shape=(6, 6, 1), padding='same', name='Conv2D_1'))

# SVG形式でモデルを表示
SVG(model_to_dot(model, show_shapes=True).create(prog='dot', format='svg'))
Ejemplo n.º 22
0
def plotm(model):
    display(
        SVG(
            model_to_dot(model, show_shapes=True).create(prog='dot',
                                                         format='svg')))
Ejemplo n.º 23
0
 def svg(self, line, cell):
     """Render the cell as an SVG literal"""
     display(SVG(cell))
Ejemplo n.º 24
0
def render_model(cobra_model,
                 background_template=None,
                 custom_css=None,
                 figure_id=None,
                 hide_unused=None,
                 hide_unused_cofactors=None,
                 inactive_alpha=1.,
                 figsize=None,
                 label=None,
                 fontsize=None,
                 default_flux_width=2.5,
                 flux_dict=None):
    """ Render a cobra.Model object in the current window

    Parameters:

    background_template:
        filename for an SVG to render behind the flux figure.  Useful for
        compartments or layout guides.

    custom_css:
        Additional CSS to embed in the figure. Use HTML inspector to show
        labels and classes applied to reactions and metabolites.

    figure_id:
        Each figure in the page requires a unique ID, which can be passed or
        generated automatically.

    hide_unused:
        whether or not to show metabolites and reactions with zero flux.

    hide_unused_cofactors:
        similar to hide_unused, but only hide cofactor nodes for reactions with
        0 flux.

    inactive_alpha:
        Alpha value with which to color reactions and nodes without any carried
        flux. Defaults to 1.

    figsize:
        size, in pixels, of the generated SVG window. Defaults to 1024x768.

    fontsize:
        text size, in pt. Defaults to 12

    default_flux_width:
        If reaction fluxes are missing, the default thickness to use for
        connecting arrows.

    flux_dict:
        A dictionary-like object containing the desired fluxes for each
        reaction in the model

    """

    # Increment figure counter

    # Get figure name and JSON string for the cobra model
    if not figure_id:
        render_model._fignum += 1
        figure_id = 'd3flux{:0>3d}'.format(render_model._fignum)

    if not figsize:
        figsize = (1028, 768)

    modeljson = create_model_json(cobra_model, flux_dict)

    if not hide_unused:
        hide_unused = "false"
    else:
        hide_unused = "true"

    if not hide_unused_cofactors:
        hide_unused_cofactors = "false"
    else:
        hide_unused_cofactors = "true"

    # Handle custom CSS
    if not custom_css:
        custom_css = ''

    if not fontsize:
        fontsize = 12

    # Handle background template
    if not background_template:
        background_svg = ''
        no_background = "true"
    else:
        from IPython.display import SVG
        background_svg = SVG(background_template).data
        no_background = "false"

    # Initialize the jinja templates
    env = Environment(loader=FileSystemLoader(
        os.path.join(os.path.dirname(d3flux.__file__), 'templates')))

    template_css = env.get_template('network_style.css')
    template_html = env.get_template('output_template.html')
    template_js = env.get_template('d3flux.js')

    # Render the jinja templates with the given variables
    css = template_css.render(inactive_alpha=inactive_alpha)

    js = template_js.render(figure_id=figure_id,
                            modeljson=modeljson,
                            no_background=no_background,
                            hide_unused=hide_unused,
                            hide_unused_cofactors=hide_unused_cofactors,
                            figwidth=figsize[0],
                            figheight=figsize[1],
                            fontsize=fontsize,
                            css=compress(css + custom_css),
                            default_flux_width=default_flux_width)

    html = template_html.render(figure_id=figure_id,
                                background_svg=background_svg,
                                javascript_source=js)

    # compile and return HTML
    return HTML(html)
Ejemplo n.º 25
0
import numpy as np
np.random.seed(123) # for reproducibility
import os; os.environ['KERAS_BACKEND'] = 'theano'
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
from keras.models import load_model
os.environ["PATH"] += os.pathsep + 'C:/anaconda3/Lib/site-packages/graphviz-2.38/bin'


(X_train, y_train), (X_test, y_test) = mnist.load_data()

model = load_model('models/mnistCNN.h5')


SVG(model_to_dot(model).create(prog='dot', format='svg'))
Ejemplo n.º 26
0
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=data['a'],
    y=data['b']
))
fig.show()

# %% [markdown]
# # Show image

# %%
import plotly.io as pio
from IPython.display import SVG, display, Image
img_bytes = pio.to_image(fig, format="svg")
display(SVG(img_bytes))

# %%
fig.write_image('out.png')

# %% [markdown]
# # Export json for Plotly viewer

# %%
pio.write_json(fig,'demo_plotly.json')

# %% [markdown]
# # SQL access

# %%
# python database api specification v2.0
Ejemplo n.º 27
0
    def viewms(objs, nmr=8, molSize=[100,80], woH=T, wo3d=F, wlgd_text='smiles',\
               wlgd=T, wia=F, filename=None, tdir='/tmp/'):
        """
        vars
        ====================
        nmr: num of mol per row
        woH: without Hydrogens displayed, T/F
        wo3d: without 3d coordinates? T/F
        wlgd: with legend displayed? T/F
        wlgd_text: 'smiles' or 'idx'
        wia: with idx of atom shown? T/F
        """
        mols, smis, fs = draw_oechem.str2mol(objs, woH=woH, wo3d=wo3d)
        nm = len(mols)
        cols = nmr  #4 if nm < nmr else nmr # num mol per row
        rows = int(nm / cols) if nm % cols == 0 else int(nm / cols) + 1

        image = oedepict.OEImage(cols * molSize[0], rows * molSize[1])

        grid = oedepict.OEImageGrid(image, rows, cols)

        opts = oedepict.OE2DMolDisplayOptions(grid.GetCellWidth(), \
                           grid.GetCellHeight(), oedepict.OEScale_AutoScale)

        if wlgd_text in ['id']:
            labs = [str(i + 1) for i in range(nm)]  #rows*cols) ]
        elif wlgd_text in [
                'smiles',
        ]:
            labs = smis
        elif wlgd_text in ['file', 'filename']:
            assert len(fs) > 1, '#ERROR: input objs are not files!!'
            labs = [fi.split('/')[-1] for fi in fs]
        else:
            raise Exception('invalid `wlgd_text')

        for i in range(nm):
            mol = mols[i]
            #print('mol=',mol)
            oedepict.OEPrepareDepiction(mol)

            irow, icol = int(i / cols) + 1, i % cols + 1
            cell = grid.GetCell(irow, icol)

            if wlgd:
                mol.SetTitle(labs[i])

            opts.SetAtomVisibilityFunctor(
                oechem.OEIsTrueAtom())  # explicitly set the default

            font = oedepict.OEFont()
            font.SetSize(16)
            font.SetStyle(oedepict.OEFontStyle_Normal)  #_Bold)
            font.SetColor(oechem.OEDarkGreen)
            opts.SetAtomPropLabelFont(font)

            if wia:
                opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomIdx())

            opts.SetAtomLabelFont(font)
            #opts.SetAtomLabelFontScale(1.5)

            opts.SetAtomPropLabelFont(font)  # atom idx
            opts.SetAtomPropLabelFontScale(2)  # atom idx

            opts.SetTitleLocation(oedepict.OETitleLocation_Bottom)
            opts.SetTitleHeight(10.0)

            disp = oedepict.OE2DMolDisplay(mol, opts)
            clearbackground = True
            oedepict.OERenderMolecule(cell, disp, not clearbackground)

        save = F  # save as pdf
        if filename is not None:
            tf = filename + '.svg'
            save = T
        else:
            tf = tpf.NamedTemporaryFile(dir=tdir).name + '.svg'
        oedepict.OEWriteImage(tf, image)

        if save:
            try:
                import cairosvg
                cairosvg.svg2pdf(url='%s.svg' % filename,
                                 write_to='%s.pdf' % filename)
            except:
                raise Exception(
                    '#ERROR: svg to pdf failed, as cairosvg seems to be not installed?'
                )

        return SVG(tf)
    def image(self):
        """Returns the result as an SVG image for output in jupyter"""
        from IPython.display import SVG

        return SVG(self.result["svgUrl"])
Ejemplo n.º 29
0
    'artifacts/model.pb': '1Ap3eWHWwAyw_3wOmy237AJF3pWQRnG3_',   # pb format
    'artifacts/model.nnet': '1HzfGxhKrw9PpeA1cMsexC4FcWv5OPdtB', # nnet format
    'artifacts/scaler.pkl': '10EkqHQ3aqEYAxbLS4Q4LRWJ1byNCvAcf', # scaler object
    'artifacts/onehot.pkl': '1SeED9m_TeyqtmHRgDe_kd9HVmn2K1hh8'  # onehot object
    }

# upload all of the artifacts to drive
# for fname,driveid in artifacts.items():
#     overwrite_gdrive_file(driveid, fname)



"""    
## Visualization
"""

!mkdir -p images
display(tf.keras.utils.plot_model(model, to_file='images/model.png', show_shapes=True, show_layer_names=True, expand_nested=True, dpi=1200, rankdir='LR'))

from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot

svg_plot = tf.keras.utils.model_to_dot(model, show_shapes=False, show_layer_names=True, rankdir='LR')
SVG(svg_plot.create(prog='dot', format='svg'))

# with open('images/model.svg', 'w') as f:
#     f.write(svg_plot.decode('utf-8'))
svg_plot.write_svg('images/model.svg')

# Commented out IPython magic to ensure Python compatibility.
# %tensorboard --logdir $tensorboard_logs --host localhost --port 6006
Ejemplo n.º 30
0
 def make_svg(self):
     from IPython.display import SVG
     return SVG(self.make_dot().create_svg())
h = Dense(hidden_size, activation='relu')(x)
r = Dense(output_size, activation='sigmoid')(h)

# 构建模型,给定模型优化参数
autoencoder = Model(inputs=x, outputs=r)
autoencoder.compile(optimizer='adam', loss='mse')

#  --------------------- 3、构建单层自编码器模型 ---------------------

#  --------------------- 4、模型可视化 ---------------------

from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot

# 可视化模型
SVG(model_to_dot(autoencoder).create(prog='dot', format='svg'))

#  --------------------- 4、模型可视化 ---------------------

#  --------------------- 5、训练 ---------------------

# 设定peochs和batch_size大小
epochs = 5
batch_size = 128

# 训练模型
history = autoencoder.fit(X_train,
                          X_train,
                          batch_size=batch_size,
                          epochs=epochs,
                          verbose=1,
Ejemplo n.º 32
0
import chess
import chess.svg
from IPython.display import SVG

board = chess.Board()

board

board.push_san("e4")

board

SVG(chess.svg.board(board=board))
Ejemplo n.º 33
0
from keras.models import model_from_json
from keras.utils.vis_utils import plot_model, model_to_dot
from IPython.display import SVG, display_svg

# load model
json_file = open('model_100.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load model weights
loaded_model.load_weights("model_100.h5")

plot_model(loaded_model,
           to_file='model_plot.png',
           show_shapes=True,
           show_layer_names=True)

display(SVG(model_to_dot(loaded_model).create(prog='dot', format='svg')))
Ejemplo n.º 34
0
eeg_df.head()
eeg_df=eeg_df.iloc[:,1:]
filted_df=generate_samples(eeg_df,489).reset_index()
y=filted_df['group']
X=filted_df.drop(columns=['index','group'])
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
X_valid, X_train = X_train[:100], X_train[100:]
y_valid, y_train = y_train[:100], y_train[100:]
X_train,X_valid,X_test=transformat_define(X_train),transformat_define(X_valid),transformat_define(X_test)
y_train,y_valid,y_test=transformat_define(y_train),transformat_define(y_valid),transformat_define(y_test)
X_train=X_train.astype('float32')
X_test=X_test.astype('float32')
onehot_train = keras.utils.to_categorical(y_train, num_classes=2)
onehot_test=keras.utils.to_categorical(y_test,num_classes=2)

model.add(Dense(30,activation='relu',input_shape=(72,)))
model.add(Dense(20,activation='relu'))
model.add(Dense(10,activation='relu'))
model.add(Dense(2,activation='softmax'))
model.summary()
from keras.utils.vis_utils import plot_model
plot_model(model,to_file="keras_dnn.png")
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
SVG(model_to_dot(model).create(prog="dot",format='svg'))

from keras import optimizers
sgd=optimizers.SGD(lr=0.01,momentum=0.9)
model.compile(optimizer=sgd,loss="categorical_crossentropy",metrics=['accuracy'])
model.fit(x=X_train,y=onehot_train,epochs=50,batch_size=20)
model.evaluate(X_test,onehot_test,batch_size=128)