3D python import error - python-2.7

I installed Netbeans and Python IDE 2.7.1 as instructed in the standard installation guide. I would like to run the following code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = Axes3D(fig)
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20)
ys = np.random.rand(20)
ax.bar(xs, ys, zs=z, zdir='y', color=c, alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
After running the code, I am getting the following error message:
ImportError: No module named mpl_toolkits.mplot3d
Also, for almost all programs I have tested, I get the same import error message.
Could someone assist?

With this description it seems that you have an installation problem at hand. Questions:
can you import matplotlib at all (you may, e.g., try to import matplotlib and see if that throws an error)
if you can import matplotlib, what does matplotlib.__version__ say?
which OS, which python (import sys; print sys.version)
First guess is that you do not have matplotlib installed in a way your interpreter would find it.

Related

ImportError: cannot import name 'load_mnist' from 'pytorchcv'

---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-2cacdf187bba> in <module>
6 import numpy as np
7
----> 8 from pytorchcv import load_mnist, train, plot_results, plot_convolution, display_dataset
9 load_mnist(batch_size=128)
ImportError: cannot import name 'load_mnist' from 'pytorchcv' (/anaconda/envs/py37_pytorch/lib/python3.7/site-packages/pytorchcv/__init__.py)
How can fix this bug?
I use python 3.7 and Jupiter notebook. The code in Pytorch Fundamental of Microsoft: Link https://learn.microsoft.com/en-gb/learn/modules/intro-computer-vision-pytorch/5-convolutional-networks
import torch
import torch.nn as nn
import torchvision
import matplotlib.pyplot as plt
from torchinfo import summary
import numpy as np
from pytorchcv import load_mnist, train, plot_results, plot_convolution, display_dataset
load_mnist(batch_size=128)
I installed PyTorch by command: pip install pytorchcv
I assume you might have the wrong pytorchcv package. The one in pypy does not contain load_mnist
Starting from scratch you could download mnist as such:
data_train = torchvision.datasets.MNIST('./data',
download=True,train=True,transform=ToTensor()) data_test = torchvision.datasets.MNIST('./data',
download=True,train=False,transform=ToTensor())
They missed one command before importing pytorchcv.
This pytorchcv is different from pytorchcv in PyPI.
Run this before importing pytorchcv.
!wget https://raw.githubusercontent.com/MicrosoftDocs/pytorchfundamentals/main/computer-vision-pytorch/pytorchcv.py
Then it should work.
please download the prepared py file from the link https://raw.githubusercontent.com/MicrosoftDocs/pytorchfundamentals/main/computer-vision-pytorch/pytorchcv.py and put it into current folder, then VS Code could recognize it

Pickle figures from matplotlib: 2

Following Pickle figures from matplotlib, I am trying to load a figure from a pickle. I am using the same code with the modifications that are suggested in the responses.
Saving script:
import numpy as np
import matplotlib.pyplot as plt
import pickle as pl
# Plot simple sinus function
fig_handle = plt.figure()
x = np.linspace(0,2*np.pi)
y = np.sin(x)
plt.plot(x,y)
# plt.show()
# Save figure handle to disk
pl.dump(fig_handle,file('sinus.pickle','wb'))
Loading script:
import matplotlib.pyplot as plt
import pickle as pl
import numpy as np
# Load figure from disk and display
fig_handle = pl.load(open('sinus.pickle', 'rb'))
fig_handle.show()
The saving script produces a file named "sinus.pickle" but the loading file does not show the anticipated figure. Any suggestions?
Python 2.7.13
matplotlib 2.0.0
numpy 1.12.1
p.s. following a suggestion replaced fig_handle.show() with pat.show() which produced an error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/
site-packages/matplotlib/backends/backend_macosx.py", line 109,
in_set_device_scale
self.figure.dpi = self.figure.dpi / self._device_scale * value
File "/usr/local/lib/python2.7/site-packages/matplotlib/figure.py",
line 416, in _set_dpi
self.callbacks.process('dpi_changed', self)
File "/usr/local/lib/python2.7/site-packages/matplotlib/cbook.py",
line 546, in process
if s in self.callbacks:
AttributeError: 'CallbackRegistry' object has no attribute 'callbacks'
What you call your "loading script" doesn't make any sense.
From the very link that you provided in your question, loading the picked figure is as simple as:
# Load figure from disk and display
fig_handle2 = pl.load(open('sinus.pickle','rb'))
fig_handle2.show()
Final solution included modification of
fig_handle.show()
to
plt.show()
and modification of the backend to "TkAgg", based to an advice given by ImportanceOfBeingErnest

Problems using Colorama on Python 2.7

I'm learning to use colorama in Python, so I installed it and I'm able to import the module with no problems from the Primary Prompt.
>>> import colorama
>>> from colorama import *
>>> print(Fore.BLUE + 'BLUE TEXT')
BLUE TEXT
Now, if I create a small piece of code like this:
#!/usr/bin/env python2.7
from colorama import *
print(Fore.BLUE + 'BLUE TEXT')
I get the following message:
File "colorama_Test.py", line 3, in <module>
from colorama import *
File "/home/olg32/Python/colorama_Test.py", line 5, in <module>
print(Fore.BLUE + 'BLUE TEXT')
NameError: name 'Fore' is not defined
Which tells me that the module is not being found. But as mentioned it was installed and tested successfully from the Primary Prompt. Could it be a path definition issue or something like that? This is the current directory where the module is installed:
usr/local/lib/python2.7/dist-packages/colorama-0.3.7-py2.7.egg
Does this path needs to be defined somewhere? Sorry I'm new on Python.
Any help would be appreciated.
Thank you.
Hopefully you have worked out the answer by now but have you tried specifying Fore?
When I use the colorama module I start with this:
import os, colorama
from colorama import Fore,Style,Back #specifying all 3 types
os.system("mode con: cols=120 lines=30") #sometimes colorama doesnt work
#when double clicking a python app so I use this to "prompt" command line
#and then it works fine colorama.init() should work too
Example code:
import os, colorama
from colorama import Fore,Style,Back
os.system("mode con: cols=120 lines=30")
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
If this doesnt work for you let me know :)

Upgraded to pandas 0.13.1, getting DeprecationWarning with sklearn

I'm using Python 2.7.3. I just upgraded from Pandas 0.12.0 to 0.13.1, and made no other changes. I upgraded to be able to use the new eval() method in the DataFrame class.
The following code runs perfectly, with no errors or warnings:
from numpy.random import randn
from pandas import DataFrame
df = DataFrame(randn(10, 2), columns=list('ab'))
df.eval('a + b')
However, if I import any classes from scikit-learn (version 0.14.1), the same code gives me a Deprecation warning. The following code:
from sklearn import naive_bayes
from numpy.random import randn
from pandas import DataFrame
df = DataFrame(randn(10, 2), columns=list('ab'))
df.eval('a + b')
gives me the following warning:
/usr/local/lib64/python2.7/site-packages/pandas/computation/ops.py:62:DeprecationWarning: object.__new__() takes no parameters
return supr_new(klass, name, env, side=side, encoding=encoding)
I'm using numpy version 1.6.2
What am I doing wrong?

How to resolve UserWarning: findfont: Could not match :family=Bitstream Vera Sans

Following this example:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
for i, label in enumerate(('A', 'B', 'C', 'D')):
ax = fig.add_subplot(2,2,i+1)
ax.text(0.05, 0.95, label, transform=ax.transAxes,
fontsize=16, fontweight='bold', va='top')
plt.show()
I get this output:
Why are my labels normal weight, while the documentation shows this should create bold letters A, B, C, D?
I also get this warning:
Warning (from warnings module):
File "C:\Python27\lib\site-packages\matplotlib\font_manager.py", line 1228
UserWarning)
UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=italic:variant=normal:weight=bold:stretch=normal:size=x-small. Returning C:\Python27\lib\site-packages\matplotlib\mpl-data\fonts\ttf\Vera.ttf
OP Resolution
From a deleted answer posted by the OP on Sep 15, 2013
Ok, it was a problem with the installation of matplotlib
Try using weight instead of fontweight.
Maybe try using this -
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.labelweight'] = 'bold'
Do this at a global level in your program.
The example from your question works on my machine. Hence you definately have a library problem. Have you considered using latex to make bold text? Here an example
Code
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 1)
ax0, ax1, ax2 = axs
ax0.text(0.05, 0.95, 'example from question',
transform=ax0.transAxes, fontsize=16, fontweight='bold', va='top')
ax1.text(0.05, 0.8, 'you can try \\textbf{this} using \\LaTeX', usetex=True,
transform=ax1.transAxes, fontsize=16, va='top')
ax2.text(0.05, 0.95,
'or $\\bf{this}$ (latex math mode with things like '
'$x_\mathrm{test}^2$)',
transform=ax2.transAxes, fontsize=10, va='top')
plt.show()
Not sure if you're still having the issue. I tried your code in Anaconda/Spyder, Python 2.7. The plots appear with Bold labels (A,B,C,D). I agree the issue is probably with the library. Try replacing / updating font_manager.py or confirming font files are present:
Lib\site-packages\matplotlib\mpl-data\fonts\ttf\
I had the same problem and spent quite a few hours today on that. Here`s the solution that helped me:
import matplotlib
matplotlib.font_manager._rebuild()
With this, the font_manager could be upgraded easily.