In Jupyter Notebook, how do you use latex symbols like $\times$ or $\nu$? - jupyter-notebook

I'd like to express a label on one of my plots in scientific notation. I write it like this in Jupyter:
...
myLabel = $c=0.46 \times 10^{15} cm^2/n_\textrm{eq}$
plt.text(0.55,39,myLabel,fontsize=16)
...
The problem is that the \t character creates a tab and then prints the "imes". Same problem with the \textrm. I've also run into this problem trying to write the greek letter nu, but I got around it with an italic v.
I've googled around and found no good solution. Any fix will be greatly appreciated!

You could try something like this post provides.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['text.usetex'] = True
t = np.linspace(0.0, 1.0, 100)
s = np.cos(4 * np.pi * t) + 2
fig, ax = plt.subplots(figsize=(6, 4), tight_layout=True)
ax.plot(t, s)
ax.set_xlabel(r'\textbf{time (s)}')
ax.set_ylabel('\\textit{Velocity (\N{DEGREE SIGN}/sec)}', fontsize=16)
ax.set_title(r'\TeX\ is Number $\displaystyle\sum_{n=1}^\infty'
r'\frac{-e^{i\pi}}{2^n}$!', fontsize=16, color='r')
First, set plt.rcParams['text.usetex'] = True. Then, instead of using the $ symbol, try it with r'c=0.46 \times 10^{15} cm^2/n_\textrm{eq}', as in the previous example.
I hope this is helpful!

Could the method "Latex" from the display module of IPython be of service here? (Note that you do need to add quotes to your string definition, and to double you backslashes for them to be left untouched on input):
from IPython.display import Latex
myLabel = "$c=0.46 \\times 10^{15} cm^2/n_{\\textrm{eq}}$"
print(myLabel)
Latex(myLabel)
In a standard colab.research.google.com python notebook, it yields the following result:

Related

BertModel transformers outputs string instead of tensor

I'm following this tutorial that codes a sentiment analysis classifier using BERT with the huggingface library and I'm having a very odd behavior. When trying the BERT model with a sample text I get a string instead of the hidden state. This is the code I'm using:
import transformers
from transformers import BertModel, BertTokenizer
print(transformers.__version__)
PRE_TRAINED_MODEL_NAME = 'bert-base-cased'
PATH_OF_CACHE = "/home/mwon/data-mwon/paperChega/src_classificador/data/hugingface"
tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME,cache_dir = PATH_OF_CACHE)
sample_txt = 'When was I last outside? I am stuck at home for 2 weeks.'
encoding_sample = tokenizer.encode_plus(
sample_txt,
max_length=32,
add_special_tokens=True, # Add '[CLS]' and '[SEP]'
return_token_type_ids=False,
padding=True,
truncation = True,
return_attention_mask=True,
return_tensors='pt', # Return PyTorch tensors
)
bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME,cache_dir = PATH_OF_CACHE)
last_hidden_state, pooled_output = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask']
)
print([last_hidden_state,pooled_output])
that outputs:
4.0.0
['last_hidden_state', 'pooler_output']
While the answer from Aakash provides a solution to the problem, it does not explain the issue. Since one of the 3.X releases of the transformers library, the models do not return tuples anymore but specific output objects:
o = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask']
)
print(type(o))
print(o.keys())
Output:
transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions
odict_keys(['last_hidden_state', 'pooler_output'])
You can return to the previous behavior by adding return_dict=False to get a tuple:
o = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask'],
return_dict=False
)
print(type(o))
Output:
<class 'tuple'>
I do not recommend that, because it is now unambiguous to select a specific part of the output without turning to the documentation as shown in the example below:
o = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'], return_dict=False, output_attentions=True, output_hidden_states=True)
print('I am a tuple with {} elements. You do not know what each element presents without checking the documentation'.format(len(o)))
o = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'], output_attentions=True, output_hidden_states=True)
print('I am a cool object and you can acces my elements with o.last_hidden_state, o["last_hidden_state"] or even o[0]. My keys are; {} '.format(o.keys()))
Output:
I am a tuple with 4 elements. You do not know what each element presents without checking the documentation
I am a cool object and you can acces my elements with o.last_hidden_state, o["last_hidden_state"] or even o[0]. My keys are; odict_keys(['last_hidden_state', 'pooler_output', 'hidden_states', 'attentions'])
I faced the same issue while learning how to implement Bert. I noticed that using
last_hidden_state, pooled_output = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'])
is the issue. Use:
outputs = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'])
and extract the last_hidden state using
output[0]
You can refer to the documentation here which tells you what is returned by the BertModel

Append to file names in folder

How to append filenames in a folder
Filenames:
abc.wav
wjejrt.wav
13567tin.wav
Desired Output
abc_ENG.wav
wjejrt_ENG.wav
13567tin_ENG.wav
Tried this line code below but getting an error, maybe because I don't know the right use of file.rename function. Please help...
file.rename(list.files(pattern="*.wav"), paste0("_ENG"))
With base Ryou can do:
Filenames <- c("abc.wav", "wjejrt.wav", "13567tin.wav")
Fnames_new <- sub(".wav", "_ENG.wav", Filenames, fixed = TRUE)
file.rename(Filenames, Fnames_new)
Since you tagged Python, you could use os.rename() to rename your files:
from os import rename
from os import listdir
from os.path import splitext
# Current directory script is being run in
# You can change this to any path you want
path_to_folder = "."
for f in listdir(path_to_folder):
if f.endswith(".wav"):
name, ext = splitext(f)
rename(f, name + "_ENG" + ext)
You can try this one
^.*(?=\\.wav)
Explanation
^ - Anchor to start of string.
.* - Match anything except new line.
(?=\\.wav) - Positive look ahead matches .wav.
Change your code to this
file.rename(list.files(pattern=".*(?=\\.wav)"), paste0("_ENG"))
Demo

How to add edge labels (interactive or permanent ones) for networkx graph in bokeh?

I would like to add label for edges in networkx graph using bokeh. How can I do this?
This question is similar to How to add permanent name labels (not interactive ones) on nodes for a networkx graph in bokeh? but different enough to warrant its own reply. As discussed in the other issue, this is currently a task that is probably harder than it should be to accomplish. I'd really encourage you to open a GitHub Issue to start a discussion of how this can be improved for users.
Here is complete example.
import networkx as nx
from bokeh.io import output_file, show
from bokeh.models import CustomJSTransform, LabelSet
from bokeh.models.graphs import from_networkx
from bokeh.plotting import figure
G=nx.barbell_graph(3,2)
p = figure(x_range=(-3,3), y_range=(-3,3))
p.grid.grid_line_color = None
r = from_networkx(G, nx.spring_layout, scale=3, center=(0,0))
r.node_renderer.glyph.size=15
r.edge_renderer.glyph.line_alpha=0.2
p.renderers.append(r)
This part is all fairly standard. To put labels on edges we must define transforms to extract the start and end coordinates from the layout provider. This code just averages the coordinates to put a label in the center of each edge (labelled by the start-end node numbers):
from bokeh.transform import transform
# add the labels to the edge renderer data source
source = r.edge_renderer.data_source
source.data['names'] = ["%d-%d" % (x, y) for (x,y) in zip(source.data['start'], source.data['end'])]
# create a transform that can extract and average the actual x,y positions
code = """
const result = new Float64Array(xs.length)
const coords = provider.get_edge_coordinates(source)[%s]
for (let i = 0; i < xs.length; i++) {
result[i] = (coords[i][0] + coords[i][1])/2
}
return result
"""
xcoord = CustomJSTransform(v_func=code % "0", args=dict(provider=r.layout_provider, source=source))
ycoord = CustomJSTransform(v_func=code % "1", args=dict(provider=r.layout_provider, source=source))
# Use the transforms to supply coords to a LabelSet
labels = LabelSet(x=transform('start', xcoord),
y=transform('start', ycoord),
text='names', text_font_size="12px",
x_offset=5, y_offset=5,
source=source, render_mode='canvas')
p.add_layout(labels)
show(p)
Edit 07/2022: Added missing var keyword to JavaScript part, would not show labels otherwise in current bokeh version.
I faced the same problem, I did check https://docs.bokeh.org/en/latest/docs/user_guide/styling.html and found it seems bokeh does not support well for the knowledge graph, including edge labels.

Figure title with underline by LaTeXStrings.jl and PyPlot.jl

I want to generate a figure whose title is rendered by LaTeXStrings.jl
However, when I try to use \underline, ValueError is returned.
What should I do?
Sample code is
using PyPlot
using LaTeXStrings
title = L"\underline{\theta}"
fig, ax = subplots()
ax[:plot](randn(100))
ax[:set_title](title, useTex=true)
The error is
PyError (:PyObject_Call) <type 'exceptions.ValueError'>
ValueError(u'\n\\underline{\\theta}\n^\nUnknown symbol: \\underline (at char 0), (line:1, col:1)',)
Adding rc("text", usetex=true) solves the issue

iPython Notebook not embedding animations

I've been trying to embed an animation into an iPython notebook but without success. I'm using the latest version of Enthought Canopy (python 2.7.3) on a Mac running 10.8.5 using Safari as my default browser.
After much failed experimentation, I tried using this code
%pylab inline
from tempfile import NamedTemporaryFile
VIDEO_TAG = """<video controls>
<source src="data:video/x-m4v;base64,{0}" type="video/mp4">
Your browser does not support the video tag.
</video>"""
def anim_to_html(anim):
if not hasattr(anim, '_encoded_video'):
with NamedTemporaryFile(suffix='.mp4') as f:
anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
video = open(f.name, "rb").read()
anim._encoded_video = video.encode("base64")
return VIDEO_TAG.format(anim._encoded_video)
from IPython.display import HTML
def display_animation(anim):
plt.close(anim._fig)
return HTML(anim_to_html(anim))
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)
# call our new function to display the animation
display_animation(anim)
from jake Vanderplas on the web. I installed ffmpeg.
On running the code I get the video progress bar, but no graph, just an empty space above the video progress bar.
After a couple of days of working on this I've not found a solution (the above is the closest I've come to). Can anyone see what's going wrong or suggestions to try?
Many thanks.
This problem is solved in Jessica Hamrick's comment on Jake Vanderplas's blog at https://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/
She added added two additional items to the extra_args argument:
extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p']

Resources