def ka_C_Binary_ratio(y, positive=1):
'''Find the positive ration of dependent variable
Parameters
----------
y: pandas series
binary dependent variable
positive: 1 or 0
identify which value is positive
Return
------
float value display positive rate
'''
return y.value_counts()[positive] / (y.value_counts().sum())
####################################################################################
## NUMERICAL BLOCK
####################################################################################
python类display()的实例源码
PlayCatchGame.py 文件源码
项目:CatchGame-QLearningExample-TensorFlow
作者: solaris33
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def drawState(fruitRow, fruitColumn, basket):
global gridSize
# column is the x axis
fruitX = fruitColumn
# Invert matrix style points to coordinates
fruitY = (gridSize - fruitRow + 1)
statusTitle = "Wins: " + str(winCount) + " Losses: " + str(loseCount) + " TotalGame: " + str(numberOfGames)
axis.set_title(statusTitle, fontsize=30)
for p in [
patches.Rectangle(
((ground - 1), (ground)), 11, 10,
facecolor="#000000" # Black
),
patches.Rectangle(
(basket - 1, ground), 2, 0.5,
facecolor="#FF0000" # No background
),
patches.Rectangle(
(fruitX - 0.5, fruitY - 0.5), 1, 1,
facecolor="#FF0000" # red
),
]:
axis.add_patch(p)
display.clear_output(wait=True)
display.display(pl.gcf())
def task_search_bar():
task_search = widgets.Text(
value="",
placeholder="Task ID",
description="Search for a task:",
disabled=False
)
display(task_search)
def handle_submit(sender):
pp = pprint.PrettyPrinter()
pp.pprint(ray.global_state.task_table(task_search.value))
task_search.on_submit(handle_submit)
# Hard limit on the number of tasks to return to the UI client at once
def add_input_toggle():
from IPython.display import HTML, display
r = HTML('''
<script>
$( document ).ready(function () {
IPython.CodeCell.options_default['cm_config']['lineWrapping'] = true;
IPython.notebook.get_selected_cell()
IPython.toolbar.add_buttons_group([
{
'label' : 'toggle all input cells',
'icon' : 'fa-eye-slash',
'callback': function(){ $('div.input').slideToggle(); }
}
]);
});
</script>
''')
display(r)
return r
def drawGUI():
'''
Draw the GUI on the screen
'''
display(widget_dict['aws_id_widget'])
display(widget_dict['aws_secret_widget'])
display(widget_dict['aws_region_widget'])
display(widget_dict['aws_security_widget'])
display(widget_dict['aws_keyname_widget'])
display(widget_dict['aws_pem_widget'])
display(widget_dict['aws_image_id'])
display(widget_dict['instance_type_widget'])
display(widgets.HBox([widget_dict['initialize_button'], widget_dict['cache_button'],widget_dict['restore_button']]))
# display(widgets.HBox([widget_dict['label_num_instances'], widget_dict['new_num_instances_widget']]))
# display(widgets.HBox([widget_dict['run_label'], widget_dict['aws_status_widget']]))
display(widget_dict['new_num_instances_widget'])
display(widget_dict['aws_status_widget'])
display(widget_dict['execute_instances_button'])
def drawState(fruitRow, fruitColumn, basket):
global gridSize
# column is the x axis
fruitX = fruitColumn
# Invert matrix style points to coordinates
fruitY = (gridSize - fruitRow + 1)
statusTitle = "Wins: " + str(winCount) + " Losses: " + str(loseCount) + " TotalGame: " + str(numberOfGames)
axis.set_title(statusTitle, fontsize=30)
for p in [
patches.Rectangle(
((ground - 1), (ground)), 11, 10,
facecolor="#000000" # Black
),
patches.Rectangle(
(basket - 1, ground), 2, 0.5,
facecolor="#FF0000" # No background
),
patches.Rectangle(
(fruitX - 0.5, fruitY - 0.5), 1, 1,
facecolor="#FF0000" # red
),
]:
axis.add_patch(p)
display.clear_output(wait=True)
display.display(pl.gcf())
def plot_dynamics(vecs, vec2, n=5, MAX_ITER=100):
"""
Plot how the distances between pairs change with each n
iterations of the optimization method.
"""
for i in xrange(MAX_ITER):
if (i%n==0):
plt.clf()
plt.xlim([-0.01, 1.2])
plt.plot(vecs[i], vec2, 'ro', color='blue')
plt.grid()
display.clear_output(wait=True)
display.display(plt.gcf())
plt.clf()
fig, ax = plt.subplots(1, 2, figsize=(13, 4))
for i in xrange(2):
ax[i].set_xlim([-0.01, 1.2])
ax[i].plot(vecs[-i], vec2, 'ro', color='blue')
ax[i].set_title(str(i*MAX_ITER)+' iterations')
ax[i].set_xlabel('Cosine distance', fontsize=14)
ax[i].set_ylabel('Assesor grade', fontsize=14)
ax[i].grid()
def __init__(self):
#user=widgets.Text(value=USERNAME,placeholder='Your ROGER Account name', description='Username',disabled=False)
#display(user)
#pw=getpass(prompt='Password')
#paramiko.util.log_to_file("ssh.log")
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.homeDir = '%s/%s'%(JUPYTER_HOME,USERNAME)
self.jobDir = self.homeDir + '/.jobs'
if not os.path.exists(self.jobDir):
os.makedirs(self.jobDir)
self.userName = USERNAME
self.rogerRoot = '%s/%s'%(ROGER_PRJ, self.userName)
self.rogerJobDir = self.rogerRoot + '/.jobs'
self.relPath = os.path.relpath(os.getcwd(), self.homeDir)
self.rogerPath = self.rogerRoot + '/' + self.relPath
self.editMode = True
self.jobId = None
with open(os.path.dirname(__file__)+'/qsub.template') as input:
self.job_template=Template(input.read())
self.login()
def forward(self, x):
x = F.relu(self.bn1(self.conv1(x)))
x = F.relu(self.bn2(self.conv2(x)))
x = F.relu(self.bn3(self.conv3(x)))
return self.head(x.view(x.size(0), -1))
######################################################################
# Input extraction
# ^^^^^^^^^^^^^^^^
#
# The code below are utilities for extracting and processing rendered
# images from the environment. It uses the ``torchvision`` package, which
# makes it easy to compose image transforms. Once you run the cell it will
# display an example patch that it extracted.
#
def drawMolsByLabel(topicModel, label, idLabelToMatch=0, baseRad=0.5, molSize=(250,150),\
numRowsShown=3, tableHeader='', maxMols=100):
result = generateMoleculeSVGsbyLabel(topicModel, label, idLabelToMatch=idLabelToMatch,baseRad=baseRad,\
molSize=molSize, maxMols=maxMols)
if len(result) == 1:
print(result)
return
svgs, namesSVGs = result
finalsvgs = []
for svg in svgs:
# make the svg scalable
finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\
+' '+str(molSize[1])+'"'))
return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader='Molecules of '+str(label),
namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4)))
# produces a svg grid of the molecules of a certain label and highlights the most probable topic
def drawMolsByTopic(topicModel, topicIdx, idsLabelToShow=[0], topicProbThreshold = 0.5, baseRad=0.5, molSize=(250,150),\
numRowsShown=3, color=(.0,.0, 1.), maxMols=100):
result = generateMoleculeSVGsbyTopicIdx(topicModel, topicIdx, idsLabelToShow=idsLabelToShow, \
topicProbThreshold = topicProbThreshold, baseRad=baseRad,\
molSize=molSize,color=color, maxMols=maxMols)
if len(result) == 1:
print(result)
return
svgs, namesSVGs = result
finalsvgs = []
for svg in svgs:
# make the svg scalable
finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\
+' '+str(molSize[1])+'"'))
tableHeader = 'Molecules in topic '+str(topicIdx)+' (sorted by decending probability)'
return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader=tableHeader,\
namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4)))
# produces a svg grid of the molecules belonging to a certain topic and highlights this topic within the molecules
def __enter__(self):
from IPython.core.getipython import get_ipython
from IPython.core.displaypub import CapturingDisplayPublisher
self.sys_stdout = sys.stdout
self.sys_stderr = sys.stderr
if self.display:
self.shell = get_ipython()
if self.shell is None:
self.save_display_pub = None
self.display = False
stdout = stderr = outputs = None
if self.stdout:
stdout = sys.stdout = StringIO()
if self.stderr:
stderr = sys.stderr = StringIO()
if self.display:
self.save_display_pub = self.shell.display_pub
self.shell.display_pub = CapturingDisplayPublisher()
outputs = self.shell.display_pub.outputs
return CapturedIO(stdout, stderr, outputs)
def update_display(obj, *, display_id, **kwargs):
"""Update an existing display by id
Parameters
----------
obj:
The object with which to update the display
display_id: keyword-only
The id of the display to update
See Also
--------
:func:`display`
"""
kwargs['update'] = True
display(obj, display_id=display_id, **kwargs)
def display_markdown(*objs, **kwargs):
"""Displays the Markdown representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw markdown data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
metadata : dict (optional)
Metadata to be associated with the specific mimetype output.
"""
_display_mimetype('text/markdown', objs, **kwargs)
def display_pdf(*objs, **kwargs):
"""Display the PDF representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw javascript data to
display.
raw : bool
Are the data objects raw data or Python objects that need to be
formatted before display? [default: False]
metadata : dict (optional)
Metadata to be associated with the specific mimetype output.
"""
_display_mimetype('application/pdf', objs, **kwargs)
#-----------------------------------------------------------------------------
# Smart classes
#-----------------------------------------------------------------------------
def plot(self, show=True):
""" Assumes nothing in self.settings is None (i.e., there are no keys
in settings such that settings[key] == None"""
kwargs = {e['encoding']: _get_plot_command(e)
for e in self.settings['encodings']}
mark_opts = {k: v for k, v in self.settings['mark'].items()}
mark = mark_opts.pop('mark')
Chart_mark = getattr(altair.Chart(self.df), mark)
self.chart = Chart_mark(**mark_opts).encode(**kwargs)
if show and self.show:
clear_output()
display(self.chart)
def _add_dim(self, button):
i = len(self.controller.children) - 1
encoding = _get_encodings()[i]
shelf = self._create_shelf(i=i)
kids = self.controller.children
teens = list(kids)[:-1] + [shelf] + [list(kids)[-1]]
self.controller.children = teens
# clear_output()
# display(self.controller)
self.settings['encodings'] += [{'encoding': encoding}]
self.plot(self.settings)
def display(self, columns=[], msg=None):
data = self.data if len(self.data) <= 100 else self.data[:49] + [['...'] * (len(self.data[0]))] + self.data[-49:]
table_str = HTMLTable([columns] + data, self.id_)._repr_html_(n_rows=100, length=len(self.data))
table_str = table_str.replace('<table', '<table class="table-striped table-hover table-bordered"').replace("'", "\\'").replace('\n','')
display(
HTML(
"""
<script type="text/Javascript">
$('#dbinfo{id}').append('{msg}');
$('#table{id}').append('{table}');
</script>
""".format(msg=str(msg), table=table_str, id=self.id_)
)
)
def build_node(id_, node, xPos):
_node = {
'name': id_,
'nodetype': node.get('Plan', node).get('Node Type'),
'starttime': node.get('Plan', node).get('Actual Startup Time'),
'endtime': node.get('Plan', node).get('Actual Total Time'),
'subplan': node.get('Plan', node).get('Subplan Name'),
'display': str(node.get('Plan', node).get('Join Filter',
node.get('Filter',
node.get('Index Cond',
node.get('Hash Cond',
node.get('One-Time Filter',
node.get('Recheck Cond',
node.get('Group Key')
)
)
)
)
)
) or '') + (' using '
+ str(node.get('Index Name',
node.get('Relation Name',
node.get('Schema')))) + ' ' + str(node.get('Alias')or'')
if node.get('Index Name',
node.get('Relation Name',
node.get('Schema')))
else ''),
'rows': node.get('Plan', node).get('Plan Rows'),
'xPos': xPos
}
return _node
def load_js_files():
display(Javascript(
load_js_scripts()
))
return None