GraphViz's executables not found error in python - python

I wrote the following code in pycharm to build the decision tree, but I got the following error. can you help me?
GraphViz's executables not found
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from six import StringIO
from sklearn.tree import export_graphviz
from sklearn import tree
import pydot
from IPython.display import Image
import pydotplus
import graphviz
dot_data = StringIO()
export_graphviz(decisionTree1, out_file =dot_data, filled=True,
rounded =True, special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
Image(graph.create_png())

Related

ModuleNotFoundError: No module named 'u8darts'

I am trying to use darts library to forecast price using transformer neural nets. through ubuntu20.4 terminal and python 3.10.
The below is my code, where I just calling and Importing necessary libraries:
from os.path import dirname, basename
from os import getcwd
import sys
def fix_pythonpath_if_working_locally():
"""Add the parent path to pythonpath if current working dir is darts/examples"""
cwd = getcwd()
if basename(cwd) == 'examples':
sys.path.insert(0, dirname(cwd))
fix_pythonpath_if_working_locally()
# Commented out IPython magic to ensure Python compatibility.
# %load_ext autoreload
# %autoreload 2
# %matplotlib inl
import pandas as pd
import numpy as np
import datetime
import time
from datetime import datetime
from sklearn import preprocessing
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import shutil
import os
import seaborn as sns
import torch
from torch import nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm_notebook as tqdm
import u8darts
from u8darts import TimeSeries
from u8darts.dataprocessing.transformers import Scaler
from u8darts.models import TransformerModel, ExponentialSmoothing
from u8darts.metrics import mape
from u8darts.utils.statistics import check_seasonality, plot_acf
import warnings
warnings.filterwarnings("ignore")
import logging
But I have got this error:
Traceback (most recent call last):
File "/vol/0/home/kherad/reihane/darts.py", line 59, in <module>
import u8darts
ModuleNotFoundError: No module named 'u8darts'
How can I fix this error?(I have use pip install u8darts in terminal and installed successfully)

No such file or directory: './dataset/time_series_covid19_confirmed_global.csv'

from google.colab import drive
drive.mount('/content/drive')
%cd /content/drive/MyDrive/AIP
[Errno 2] No such file or directory: '/content/drive/MyDrive/AIP' /content/drive/My Drive/Colab Notebooks
import os
import os.path
import requests
from scipy.integrate import odeint
import torch
from torch import nn, optim
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from pylab import rcParams
from pandas.plotting import register_matplotlib_converters
from sklearn.preprocessing import MinMaxScaler, StandardScaler
%matplotlib inline
%config InlineBackend.figure_format='retina'
sns.set(style='whitegrid',font_scale=0.6)
rcParams['figure.figsize'] = 6,4
register_matplotlib_converters()
# DATA
URL = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/"
CONFIRMED="time_series_covid19_confirmed_global.csv"
DEATH="time_series_covid19_deaths_global.csv"
RECOVERED="time_series_covid19_recovered_global.csv"
# Fixed random seed
RANDOM_SEED = 42 np.random.seed(RANDOM_SEED) torch.manual_seed(RANDOM_SEED)
# Download dataset from GitHub which was provided by the Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE).
if not os.path.isfile(f"./dataset/{CONFIRMED}"):
for name in [CONFIRMED, DEATH, RECOVERED]:
url = os.path.join(URL, name)
r = requests.get(url)
file_csv = open(os.path.join("./dataset", name), 'wb')
file_csv.write(r.content)
file_csv.close()
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-14-d47d8c7d4415> in <module>()
4 url = os.path.join(URL, name)
5 r = requests.get(url)
----> 6 file_csv = open(os.path.join("./dataset", name), 'wb')
7 file_csv.write(r.content)
8 file_csv.close()
FileNotFoundError: [Errno 2] No such file or directory: './dataset/time_series_covid19_confirmed_global.csv'
I have trying to run this code but I have some problem please can someone help me to solve this
How can I solve this problem in google collab ??????
also how to correct this problem No such file or directory: '/content/drive/MyDrive/AIP' /content/drive/My Drive/Colab Notebooks
Add content to path
file_csv = open(os.path.join("/content/dataset", name), 'wb')
Also check this file repository to check if your data is well downloaded in content file

What is the json file I need to read?

enter image description hereI need to download satellite images using python. I have found a code in GitHub but I did not understand what at this line. Please help me what it exactly is.
Visit https://github.com/kscottz/PythonFromSpace/blob/master/TheBasics.ipynb
import sys
import os
import json
import scipy
import urllib
import datetime
import urllib3
import rasterio
import subprocess
import numpy as np
import pandas as pd
import seaborn as sns
from osgeo import gdal
from planet import api
from planet.api import filters
from traitlets import link
import rasterio.tools.mask as rio_mask
from shapely.geometry import mapping, shape
from IPython.display import display, Image, HTML
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
urllib3.disable_warnings()
from ipyleaflet import (
Map,
Marker,
TileLayer, ImageOverlay,
Polyline, Polygon, Rectangle, Circle, CircleMarker,
GeoJSON,
DrawControl
)
%matplotlib inline
# will pick up api_key via environment variable PL_API_KEY
# but can be specified using `api_key` named argument
api_keys = json.load(open("apikeys.json",'r'))
client = api.ClientV1(api_key=api_keys["PLANET_API_KEY"])
# Make a slippy map to get GeoJSON
api_keys = json.load(open("apikeys.json",'r'))
client = api.ClientV1(api_key=api_keys["PLANET_API_KEY"])
What is the meaning of these two lines. What file should I upload for apikeys.json
You should follow this link to get an API Key.
https://support.planet.com/hc/en-us/articles/212318178-What-is-my-API-key-
apikeys.json is a JSON file of following format/content in json:
{"PLANET_API_KEY":"<Some API Key here>"}
json.load(...) API loads this json file as a dictionary

How can i convert type IPython.core.display.Image to base64 string using tempfile?

I am trying to visualize a Decision Tree from a Random Forest Classifier.
However the type of the image that is being generated is of the type IPython.core.display.Image I wish to convert this into a base64 string by using the tempfile library
import tempfile
import base64
from IPython.display import Image
from sklearn import tree
import pydotplus
dot_data = tree.export_graphviz(model.best_estimator_[0], out_file=None,
feature_names=X_train.columns,
class_names=unique_target)
graph = pydotplus.graph_from_dot_data(dot_data)
# Show graph
image= Image(graph.create_png())
with tempfile.TemporaryFile(suffix=".png") as tmpfile:
fig = image.get_figure()
"AttributeError: 'Image' object has no attribute 'get_figure'"
type(image)
Out[32]: IPython.core.display.Image
I am getting the error as:
"AttributeError: 'Image' object has no attribute 'get_figure'"
I am kind of lost on how to
convert this into a base64 without explicitly saving the file.
It worked. I tried with a friend for a couple of hours.
import base64
from IPython.display import Image
from sklearn import tree
import pydotplus
dot_data = tree.export_graphviz(model.best_estimator_[0], out_file=None,
feature_names=X_train.columns,
class_names=unique_target)
graph = pydotplus.graph_from_dot_data(dot_data)
image= Image(graph.create_png())
Encoded_Image=str(base64.b64encode(image.data)) ##That's the line you add before you save it as an Encoded String
There is no need to add the tempfile part of the code.

python just import fails but works with from

Why does this not work:
import matplotlib.pyplot as plt
import os
import skimage
camera = skimage.io.imread(os.path.join(skimage.data_dir, 'camera.png'))
#plt.show(io.imshow(camera))
But using from skimage import io does. So this works:
import matplotlib.pyplot as plt
import os
import skimage # I still need to import skimage to get the data_dir
from skimage import io
camera = io.imread(os.path.join(skimage.data_dir, 'camera.png'))
#plt.show(io.imshow(camera))
I thought
import skimage
skimage.io."something"
Was equivalent to
from skimage import io
io."something"
I thought
import skimage
skimage.io."something"
Was equivalent to
from skimage import io
io."something"
It's not.
import skimage
causes python to look for the skimage module. Maybe there's a __init__.py that sets up what becomes visible and what is done when you import that module.

Categories