When trying to generate a word cloud in Python 3.10. I get a deprecation warning stating that:
08: DeprecationWarning: textsize is deprecated and will be removed in Pillow 10 (2023-07-01). Use textbbox or textlength instead.
I used to run the same code with Python 3.7 without any warning. Does anyone have any idea what is going on?
I get a very long list of this warning repeatedly in my notebook. I am looking for a way to fix this warning.
Here is the code I am using:
def wordcloud(self) -> None:
"""Function to generate wordcloud"""
long_string = ','.join(self.corpus)
# Create a WordCloud object
wordcloud = WordCloud(background_color="white",
max_words=5000,
contour_width=3,
contour_color='steelblue')
# Generate a word cloud
wordcloud.generate(long_string)
# Visualize the word cloud
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis('off')
plt.show()
Related
I'm trying to use matplotlib and numpy to plot a graph but keep running into this error:
MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute was deprecated in Matplotlib 3.6 and will be removed two minor releases later.
plt.plot(cache_sizes, hit_rates[i])
Any idea how to solve it?
Here's the code:
#!/usr/bin/env python3
import os
import subprocess
import matplotlib.pyplot as plt
import numpy as np
# cache_sizes = np.arange(0, 120, 20)
cache_sizes = np.arange(1, 5)
policies = ["FIFO", "LRU", "OPT", "UNOPT", "RAND", "CLOCK"]
# these were acheived after running `run.sh`
hit_rates = [
# FIFO
[45.03, 83.08, 93.53, 97.42],
# LRU
[45.03, 88.04, 95.20, 98.30],
# OPT
[45.03, 88.46, 96.35, 98.73],
# UNOPT
# NOTE: was unable to finish running this one, as it took too long.
[45.03, None, None, None],
# RAND
[45.03, 82.06, 93.16, 97.36],
# CLOCK
[45.03, 83.59, 94.09, 97.73],
]
for i in range(len(policies)):
plt.plot(cache_sizes, hit_rates[i])
plt.legend(policies)
plt.margins(0)
plt.xticks(cache_sizes, cache_sizes)
plt.xlabel("Cache Size (Blocks)")
plt.ylabel("Hit Rate")
plt.savefig("workload.png", dpi=227)
Best I can tell, this is related to the backend you're using and how it generates the FigureCanvas object. Matplotlib has introduced a deprecation and some other softwares are still in the process of being updated accordingly. Sadly, for now, it's generating a warning that is not very user friendly and the matplotlib documentation provides no help.
I was seeing this error in PyCharm, which by default uses its own internal backend for matplotlib: 'module://backend_interagg'. Google provides a bunch of examples of people getting errors to do with FigureCanvas and backend_interagg. Fortunately, updating to the newest version of PyCharm solved it for me.
If your problem is not PyCharm related, then perhaps try checking which backend you're using, and perhaps use a different one.
import matplotlib
matplotlib.get_backend()
will show you which backend you're using
matplotlib.use('')
will give you a list of available backends to try and then use will also allow you to select one. e.g. matplotlib.use('GTK3Agg')
hi guys I'm trying to do audio classification using python and I installed a package and when I tried to use the functions, it said "TypeError: TypeError: reduce_noise() got an unexpected keyword argument 'audio_clip' hear the code of function.
import librosa
import numpy as np
import noisereduce as nr
def save_STFT(file, name, activity, subject):
#read audio data
audio_data, sample_rate = librosa.load(file)
print(file)
#noise reduction
noisy_part = audio_data[0:25000]
reduced_noise = nr.reduce_noise(audio_clip=audio_data, noise_clip=noisy_part, verbose=False)
#trimming
trimmed, index = librosa.effects.trim(reduced_noise, top_db=20, frame_length=512, hop_length=64)
#extract features
stft = np.abs(librosa.stft(trimmed, n_fft=512, hop_length=256, win_length=512))
# save features
np.save("STFT_features/stft_257_1/" + subject + "_" + name[:-4] + "_" + activity + ".npy", stft)
this code running in jupyternote book with Conda environment but It's not running in pycharm.
I installed conda environment in PYcharm but it does not work. Could you please help me know how to fix this error?
Answer to your question is in the error message.
"TypeError: TypeError: reduce_noise() got an unexpected keyword argument 'audio_clip'
I am guessing you are using noisereduce Python library. If you check the docs, it does not have audio_clip on parameters' list.
Example of correct code:
reduced_noise = nr.reduce_noise(y=audio_data, y_noise=noisy_part, sr=SAMPLING_FREQUENCY) # check the SAMPLING_FREQUENCY
Probably you are referring old APIs for newer version of library
The work around to use old APIs in newer version of library is
from noisereduce.noisereducev1 import reduce_noise
Now you can reuse your code as
reduced_noise = reduce_noise(audio_clip=audio_data, noise_clip=noisy_part, verbose=False)
I am performing a time series analysis using statsmodels and the exponential smoothing method. I am trying to reproduce the results from
https://www.statsmodels.org/devel/examples/notebooks/generated/exponential_smoothing.html
with a particular dataframe (with the same format as the example, but only one outcome).
Here are the lines of code:
from statsmodels.tsa.api import ExponentialSmoothing, SimpleExpSmoothing, Holt
fit = ExponentialSmoothing(dataframe, seasonal_periods=4, trend='add', seasonal='mul', initialization_method="estimated").fit()
simulations = fit.simulate(5, repetitions=100, error='mul')
fit.fittedvalues.plot(ax=ax, style='--', color='green')
simulations.plot(ax=ax, style='-', alpha=0.05, color='grey', legend=False)
fit.forecast(8).rename('Holt-Winters (add-mul-seasonal)').plot(ax=ax, style='--', marker='o', color='green', legend=True)
However, when I run it, I get the error
TypeError: __init__() got an unexpected keyword argument 'initialization_method'
but when I check the parameters of ExponentialSmoothing in statsmodel, initialization_method is one of them, so I don't know what happens there.
Moving forward, I removed initialization_method from the parameters of ExponentialSmoothing within the code, then I get another error the line below
AttributeError: 'ExponentialSmoothing' object has no attribute 'simulate'
Again, I go and check if simulate is not deprecated in the latest version of statsmodels and no, it is still an attribute.
I upgraded the statsmodels, I upgraded pip and I still get the same errors.
What is it going on there?
Thanks in advance for any help!
Indeed, there was a bug in the previous version, that was corrected in the new version of statsmodels. One only needs to update to statsmodels 0.12.0 and this issue is solved.
I am working on this python notebook in Google Collab:
https://github.com/AllenDowney/ModSimPy/blob/master/notebooks/chap01.ipynb
I had to change the configuration line because the one stated in the original was erroring out:
# Configure Jupyter to display the assigned value after an assignment
# Line commented below because errors out
# %config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# Edit solution given below
%config InteractiveShell.ast_node_interactivity='last_expr'
However, I think the original statement was meant to show values of assignments (if I'm not mistaken), so that when I run the following cell in the notebook, I should see an output:
meter = UNITS.meter
second = UNITS.second
a = 9.8 * meter / second**2
If so how can I make the notebook on google collab show output of assignments?
The short answer is: you can not show output of assignments in Colab.
Your confusion comes from how Google Colab works. The original script is meant to run in IPython. But Colab is not a regular IPython. When you run IPython shell, your %config InteractiveShell.ast_node_interactivity options are (citing documentation)
‘all’, ‘last’, ‘last_expr’ , ‘last_expr_or_assign’ or ‘none’,
specifying which nodes should be run interactively (displaying output
from expressions). ‘last_expr’ will run the last node interactively
only if it is an expression (i.e. expressions in loops or other blocks
are not displayed) ‘last_expr_or_assign’ will run the last expression
or the last assignment. Other values for this parameter will raise a
ValueError.
all will display all the variables, but not the assignments, for example
x = 5
x
y = 7
y
Out[]:
5
7
The differences between the options become more significant when you want to display variables in the loop.
In Colab your options are restricted to ['all', 'last', 'last_expr', 'none']. If you select all, the result for the above cell will be
Out[]:
57
Summarizing all that, there is no way of showing the result of assignment in Colab. Your only option (AFAIK) is to add the variable you want to see to the cell where it is assigned (which is similar to regular print):
meter = UNITS.meter
second = UNITS.second
a = 9.8 * meter / second**2
a
Google Colab has not yet been upgraded to the latest IPython version- if you explicitly upgrade with
!pip install -U ipython
then last_expr_or_assign will work.
Well the easy way is to just wrap your values in print statements like:
print(meter)
print(second)
print(a)
However, if you want to do it the jupyter way, looks like the answer is
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Found the above from this link: https://stackoverflow.com/a/36835741/7086982
As mentioned by others, it doesn't work as last_expr_or_assign was introduced in juptyer v6.1, and colab is using v5.x. Upgrading the jupyter version on colab might cause some instability (warning shown by colab):
WARNING: Upgrading ipython, ipykernel, tornado, prompt-toolkit or pyzmq can
cause your runtime to repeatedly crash or behave in unexpected ways and is not
recommended
One other solution is to use an extension such as ipydex, which provides magic comments (like ##:, ##:T, ##:S) which cause that either the return value or the right hand side of an assignment of a line is displayed.
!pip install ipydex
%load_ext ipydex.displaytools
e.g.
a = 4
c = 5 ##:
output
c := 5
---
I am writing a custom client (a web-based graph representation of an IPython Notebook) for an IPython application and the easiest way to manage IPython programmatically seems to be using the IPython.core.InteractiveShell instance.
Consider this example: when a Jupyter Notebook cell that uses rich output is executed with inline magic, Notebook shows the appropriate rich representation (a plotted image) of plt.show() inline:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.grid(True)
plt.show()
I want to be able to retrieve the image when using IPython programmatically via its API, namely InteractiveShell, like this:
from IPython.core.interactiveshell import InteractiveShell
shell = InteractiveShell()
result = shell.run_cell("...above code of the cell here...")
# result either gives an error when using %matplotlib inline or retrieves
# no useful info if no line magic is present
Problem is that InteractiveShell instance will not accept the %matplotlib inline magic, giving a NotImplementedError in its enable_gui method which is, wll, not implemented. I found very few information about this apart from a single issue on IPython's Github.
I know I can do this manually by using plt.save() but that doesn't seem right to me as I don't want to write manual interpretations each time I need another rich representation of the result. I feel like I'm missing a lot here in the way IPython works, so I'm asking for help in retrieving the results. What exactly does Jupyter Notebook do to retrieve the rich representation and perhaps can it be done painlessly via other means? I'm looking at using jupyter_client but for now that seems to be even more confusing.
UPDATE:
The io.capture_output context manager seems to be the way to go but I've been able to capture string outputs only (pretty much the same as using %%capture cell magic):
with io.capture_output() as captured:
result = shell.run_cell(cell)
#captures strings only:
captured.stdout = {str} '<matplotlib.figure.Figure at 0x4f486d8>'