I'm trying to use bokeh and pandas to create a graph. If ", responsive = True" is not included, the code works. If it is included, it doesn't work. Any suggestions for what I'm doing wrong? Thanks!
from bokeh.plotting import Figure, output_file, show
import pandas
file="adbe.csv"
df=pandas.read_csv(file, parse_dates=["Date"])
p=figure(width=500, height=500, x_axis_type="datetime", responsive = True)
p.line(df["Date"],df["Close"],color="Orange", alpha=0.5)
output_file("Time_Series.html")
show(p)
Here's the full error message:
AttributeError Traceback (most recent call last)
in
6 df=pandas.read_csv(file, parse_dates=["Date"])
7
----> 8 p=figure(width=500, height=500, x_axis_type="datetime", responsive = True)
9
10 p.line(df["Date"],df["Close"],color="Orange", alpha=0.5)
c:\users\jason\appdata\local\programs\python\python37\lib\site-packages\bokeh\plotting\figure.py in figure(**kwargs)
1530
1531 def figure(**kwargs):
-> 1532 return Figure(**kwargs)
1533 figure.__doc__ = Figure.__doc__
1534
c:\users\jason\appdata\local\programs\python\python37\lib\site-packages\bokeh\plotting\figure.py in __init__(self, *arg, **kw)
163 kw['title'] = Title(text=title)
164
--> 165 super().__init__(*arg, **kw)
166
167 self.x_range = get_range(opts.x_range)
c:\users\jason\appdata\local\programs\python\python37\lib\site-packages\bokeh\model.py in __init__(self, **kwargs)
232 kwargs.pop("id", None)
233
--> 234 super().__init__(**kwargs)
235 default_theme.apply_to_model(self)
236
c:\users\jason\appdata\local\programs\python\python37\lib\site-packages\bokeh\core\has_props.py in __init__(self, **properties)
245
246 for name, value in properties.items():
--> 247 setattr(self, name, value)
248
249 def __setattr__(self, name, value):
c:\users\jason\appdata\local\programs\python\python37\lib\site-packages\bokeh\core\has_props.py in __setattr__(self, name, value)
280
281 raise AttributeError("unexpected attribute '%s' to %s, %s attributes are %s" %
--> 282 (name, self.__class__.__name__, text, nice_join(matches)))
283
284 def __str__(self):
AttributeError: unexpected attribute 'responsive' to Figure, possible attributes are above, align, aspect_ratio, aspect_scale, background, background_fill_alpha, background_fill_color, below, border_fill_alpha, border_fill_color, center, css_classes, disabled, extra_x_ranges, extra_y_ranges, frame_height, frame_width, height, height_policy, hidpi, inner_height, inner_width, js_event_callbacks, js_property_callbacks, left, lod_factor, lod_interval, lod_threshold, lod_timeout, margin, match_aspect, max_height, max_width, min_border, min_border_bottom, min_border_left, min_border_right, min_border_top, min_height, min_width, name, outer_height, outer_width, outline_line_alpha, outline_line_cap, outline_line_color, outline_line_dash, outline_line_dash_offset, outline_line_join, outline_line_width, output_backend, plot_height, plot_width, renderers, reset_policy, right, sizing_mode, subscribed_events, tags, title, title_location, toolbar, toolbar_location, toolbar_sticky, visible, width, width_policy, x_range, x_scale, y_range or y_scale
The responsive parameter was removed several years ago. (https://docs.bokeh.org/en/dev-3.0/docs/releases.html)
Deprecations Removed:
The following functions, arguments, or features have were previously deprecated with warnings and instructions for new usage, and have now been permanently removed:
--host argument to bokeh serve
responsive argument to plots and layout functions
Plot.toolbar_sticky property
Tool.plot property
bokeh.sampledata.population.load_population function
bokeh.util.notebook module
In modern versions of Bokeh you can use sizing_mode instead, or you can try deleting it from your code. (https://docs.bokeh.org/en/latest/docs/user_guide/layout.html?highlight=sizing_mode#sizing-mode)
Like the error said, Figure has not attribute 'responsive', so, don't use it.
You can check the documentation
Are you doing Ardit Sulce's tutorial? Because I stumbled upoh the same issue. I looked that up and found more explanation on this at https://github.com/bokeh/bokeh/issues/4620
I managed to get the similar output to responsive = True by using sizing_mode = "scale_width"
I hope this helps others who stumbled upon the same issue while following the tutorial.
Related
hello I've trained a PPO model from stabel_baselines3 on collab I saved it
model.save("model")
but when I tried loading it I got the following error:
m = PPO.load("model", env=env)
AttributeError Traceback (most recent call last)
/tmp/ipykernel_25649/121834194.py in <module>
2 env = e.MinitaurBulletEnv(render=False)
3 env.reset()
----> 4 m2 = PPO.load("model", env=env)
5 for episode in range(1, 6):
6 obs = env.reset()
~/anaconda3/lib/python3.8/site-packages/stable_baselines3/common/base_class.py in load(cls, path, env, device, custom_objects, **kwargs)
668 env = cls._wrap_env(env, data["verbose"])
669 # Check if given env is valid
--> 670 check_for_correct_spaces(env, data["observation_space"], data["action_space"])
671 else:
672 # Use stored env, if one exists. If not, continue as is (can be used for predict)
~/anaconda3/lib/python3.8/site-packages/stable_baselines3/common/utils.py in check_for_correct_spaces(env, observation_space, action_space)
217 :param action_space: Action space to check against
218 """
--> 219 if observation_space != env.observation_space:
220 raise ValueError(f"Observation spaces do not match: {observation_space} != {env.observation_space}")
221 if action_space != env.action_space:
~/anaconda3/lib/python3.8/site-packages/gym/spaces/box.py in __eq__(self, other)
138
139 def __eq__(self, other):
--> 140 return isinstance(other, Box) and (self.shape == other.shape) and np.allclose(self.low, other.low) and np.allclose(self.high, other.high)
AttributeError: 'Box' object has no attribute 'shape'
knowing that the env is a box env from pybullet
import pybullet_envs.bullet.minitaur_gym_env as e
import gym
env = e.MinitaurBulletEnv(render=False)
env.reset()
additional info is that the model loaded perfectly in collab
From your question, I can't tell if you are or aren't working on Google Colab, but if you are, I think you should definitely include the whole path to the saved model when you load it. Maybe you need to do this even if not in Colab.
What I mean is that your line of code should probably look something like this when you're loading the model:
m = PPO.load("./model.zip/", env=env)
I hope this helps!
I am trying to replicate Keras-LSTM DeepExplainer example. I am getting the following error when trying to compute the shap values:
This warning: keras is no longer supported, please use tf.keras instead.
Your TensorFlow version is newer than 2.4.0 and so graph support has been removed in eager mode and some static graphs may not be supported. See PR #1483 for discussion.
And this error:
TypeError Traceback (most recent call last)
in
1 import shap
2 explainer = shap.DeepExplainer(model, x_train[:100])
----> 3 shap_values = explainer.shap_values(x_test[:10])
~/miniconda3/envs/mtq/lib/python3.8/site-packages/shap/explainers/_deep/init.py
in shap_values(self, X, ranked_outputs, output_rank_order,
check_additivity)
122 were chosen as "top".
123 """
--> 124 return self.explainer.shap_values(X, ranked_outputs, output_rank_order, check_additivity=check_additivity)
~/miniconda3/envs/mtq/lib/python3.8/site-packages/shap/explainers/_deep/deep_tf.py
in shap_values(self, X, ranked_outputs, output_rank_order,
check_additivity)
306 # run attribution computation graph
307 feature_ind = model_output_ranks[j,i]
--> 308 sample_phis = self.run(self.phi_symbolic(feature_ind), self.model_inputs,
joint_input) 309
310 # assign the attributions to the right part of the output arrays
~/miniconda3/envs/mtq/lib/python3.8/site-packages/shap/explainers/_deep/deep_tf.py
in run(self, out, model_inputs, X)
363
364 return final_out
--> 365 return self.execute_with_overridden_gradients(anon)
366
367 def custom_grad(self, op, *grads):
~/miniconda3/envs/mtq/lib/python3.8/site-packages/shap/explainers/_deep/deep_tf.py
in execute_with_overridden_gradients(self, f)
399 # define the computation graph for the attribution values using a custom gradient-like computation
400 try:
--> 401 out = f()
402 finally:
403 # reinstate the backpropagatable check
~/miniconda3/envs/mtq/lib/python3.8/site-packages/shap/explainers/_deep/deep_tf.py
in anon()
356 shape = list(self.model_inputs[i].shape)
357 shape[0] = -1
--> 358 data = X[i].reshape(shape)
359 v = tf.constant(data, dtype=self.model_inputs[i].dtype)
360 inputs.append(v)
TypeError: 'NoneType' object cannot be interpreted as an integer
I have checked out the PR#1483, but couldn't find a relevant fix there. Please suggest on what tensorflow, keras, and shap versions are needed to successfully replicate the example.
Hallo I try to create a decisiontree with my csv datasheet. I installed in anaconda and python the graphviz package with the following command:
conda install graphviz
pip install graphviz
to get my tree visible. Here is my code that I have wrote in Jupyther Notebook:
import pandas as pd
import graphviz
from sklearn import metrics
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.model_selection import train_test_split
file = 'automotive_data.csv'
COLS = np.arange(0,22,1).tolist()#gibt später bei usecols eine andere möglichkeit die spalten anzusprechen
data = pd.read_csv(file, header=0, sep = ",", index_col=0, usecols=COLS)
x = data.iloc[:,1:]
x = x.to_numpy()
y = data[['Ausfall']]
y
xTrain, xTest, yTrain, yTest = train_test_split(x, y, test_size=0.3, random_state=1)
model = DecisionTreeClassifier (
criterion='entropy',
splitter='best',
min_samples_split= 0.3,
max_features=10,
max_depth=None
)
#Danach mit fit erstellt
model.fit(xTrain, yTrain)
dot=export_graphviz(model, out_file=None,filled=True,
feature_names=data.columns[1:24],
class_names=['ja','nein']);
# Erzeuge Graphviz-Graphen aus dot-Quellcode
graph = graphviz.Source(dot)
graph#Here I get an error
In the last row I get the error:
Format: "svg" not recognized. Use one of:
CalledProcessError Traceback (most recent call last)
~\anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
343 method = get_real_method(obj, self.print_method)
344 if method is not None:
--> 345 return method()
346 return None
347 else:
~\anaconda3\lib\site-packages\graphviz\files.py in _repr_svg_(self)
111
112 def _repr_svg_(self):
--> 113 return self.pipe(format='svg').decode(self._encoding)
114
115 def pipe(self, format=None, renderer=None, formatter=None, quiet=False):
~\anaconda3\lib\site-packages\graphviz\files.py in pipe(self, format, renderer, formatter, quiet)
136 out = backend.pipe(self._engine, format, data,
137 renderer=renderer, formatter=formatter,
--> 138 quiet=quiet)
139
140 return out
~\anaconda3\lib\site-packages\graphviz\backend.py in pipe(engine, format, data, renderer, formatter, quiet)
242 """
243 cmd, _ = command(engine, format, None, renderer, formatter)
--> 244 out, _ = run(cmd, input=data, capture_output=True, check=True, quiet=quiet)
245 return out
246
~\anaconda3\lib\site-packages\graphviz\backend.py in run(cmd, input, capture_output, check, encoding, quiet, **kwargs)
182 if check and proc.returncode:
183 raise CalledProcessError(proc.returncode, cmd,
--> 184 output=out, stderr=err)
185
186 return out, err
CalledProcessError: Command '['dot', '-Tsvg']' returned non-zero exit status 1. [stderr: b'Format: "svg" not recognized. Use one of:\r\n']
I also tried to use PNG as my format but it didn't work too. I have no idea how to solve this problem.
So apparently the issue is you have to configure the graphviz plugins first.
Open a terminal in administrator mode and run dot -c. (This assumes that the graphviz binaries are in your path)
I had the same problem, I solved it by installing version 2.38 instead of 2.44
https://www2.graphviz.org/Packages/stable/windows/10/msbuild/Release/Win32/
scratching my head on this issue. i dont know how to identify the positional indexers. am i even passing them?
attempting this for my first kaggle comp, can pass in the csv to a dataframe and make the needed edits. trying to create the ImageDataBunch so training a cnn can begin. This error pops up no matter which method is tried. Any advice would be appreciated.
data = ImageDataBunch.from_df(path, df, ds_tfms=tfms, size=24)
data.classes
Backtrace
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-25-5588812820e8> in <module>
----> 1 data = ImageDataBunch.from_df(path, df, ds_tfms=tfms, size=24)
2 data.classes
/opt/conda/lib/python3.7/site-packages/fastai/vision/data.py in from_df(cls, path, df, folder, label_delim, valid_pct, seed, fn_col, label_col, suffix, **kwargs)
117 src = (ImageList.from_df(df, path=path, folder=folder, suffix=suffix, cols=fn_col)
118 .split_by_rand_pct(valid_pct, seed)
--> 119 .label_from_df(label_delim=label_delim, cols=label_col))
120 return cls.create_from_ll(src, **kwargs)
121
/opt/conda/lib/python3.7/site-packages/fastai/data_block.py in _inner(*args, **kwargs)
477 assert isinstance(fv, Callable)
478 def _inner(*args, **kwargs):
--> 479 self.train = ft(*args, from_item_lists=True, **kwargs)
480 assert isinstance(self.train, LabelList)
481 kwargs['label_cls'] = self.train.y.__class__
/opt/conda/lib/python3.7/site-packages/fastai/data_block.py in label_from_df(self, cols, label_cls, **kwargs)
283 def label_from_df(self, cols:IntsOrStrs=1, label_cls:Callable=None, **kwargs):
284 "Label `self.items` from the values in `cols` in `self.inner_df`."
--> 285 labels = self.inner_df.iloc[:,df_names_to_idx(cols, self.inner_df)]
286 assert labels.isna().sum().sum() == 0, f"You have NaN values in column(s) {cols} of your dataframe, please fix it."
287 if is_listy(cols) and len(cols) > 1 and (label_cls is None or label_cls == MultiCategoryList):
/opt/conda/lib/python3.7/site-packages/pandas/core/indexing.py in __getitem__(self, key)
1760 except (KeyError, IndexError, AttributeError):
1761 pass
-> 1762 return self._getitem_tuple(key)
1763 else:
1764 # we by definition only have the 0th axis
/opt/conda/lib/python3.7/site-packages/pandas/core/indexing.py in _getitem_tuple(self, tup)
2065 def _getitem_tuple(self, tup: Tuple):
2066
-> 2067 self._has_valid_tuple(tup)
2068 try:
2069 return self._getitem_lowerdim(tup)
/opt/conda/lib/python3.7/site-packages/pandas/core/indexing.py in _has_valid_tuple(self, key)
701 raise IndexingError("Too many indexers")
702 try:
--> 703 self._validate_key(k, i)
704 except ValueError:
705 raise ValueError(
/opt/conda/lib/python3.7/site-packages/pandas/core/indexing.py in _validate_key(self, key, axis)
2007 # check that the key does not exceed the maximum size of the index
2008 if len(arr) and (arr.max() >= len_axis or arr.min() < -len_axis):
-> 2009 raise IndexError("positional indexers are out-of-bounds")
2010 else:
2011 raise ValueError(f"Can only index by location with a [{self._valid_types}]")
IndexError: positional indexers are out-of-bounds
I faced this error while creating a DataBunch when my dataframe/CSV did not have a class label explicitly defined.
I created a dummy column which stored 1's for all my rows in the dataframe and it seemed to work. Also please be sure to store your independent variable in the second column and the label(dummy variable in this case) in the first column.
I believe this error happens if there's just one column in the Pandas DataFrame.
Thanks.
Code:
df = pd.DataFrame(lines, columns=["dummy_value", "text"])
df.to_csv("./train.csv")
data_lm = TextLMDataBunch.from_csv(path, "train.csv", min_freq=1)
Note: This is my first attempt at answering a StackOverflow question. Hope it helped!
This error also appears when your dataset is not correctly split between test and validation.
In the case of dataframes, it assumes there is a column is_valid that indicates which rows are in validation set.
If all rows have True, then the training set is empty, so fastai cannot index into it to prepare the first example, thus raising this error.
Example:
data = pd.DataFrame({
'fname': [f'{x}.png' for x in range(10)],
'label': np.arange(10)%2,
'is_valid': True
})
blk = DataBlock((ImageBlock, CategoryBlock),
splitter=ColSplitter(),
get_x=ColReader('fname'),
get_y=ColReader('label'),
item_tfms=Resize(224, method=ResizeMethod.Squish),
)
blk.summary(data)
Results in the error.
Solution
The solution is to check that your data can be split correctly into train and valid sets. In the above example, it suffices to have one row that is not in validation set:
data.loc[0, 'is_valid'] = False
How to figure it out?
Work in a jupyter notebook. After the error, type %debug in a cell, and enter the post mortem debugging. Go to the frame of the setup function ( fastai/data/core.py(273) setup() ) by going up 5 frames.
This takes you to this line that is throwing the error.
You can then print(self.splits) and observe that the first one is empty.
I am trying to segment hand from the depth image attached in this question. In the process, I wrote the below code which process the histogram of the image first and then does median filtering on the processed image. But this code is giving an error continuously even after trying hard to solve it.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import scipy
from scipy import ndimage, misc
from scipy.misc import imshow
import skimage
img = mpimg.imread('C:/Users/Prachi/Desktop/kinect_leap_dataset/acquisitions/P1/G1/1_depth.png')
plt.hist(img.ravel(), bins=256, range=(0.0, 1.0))
plt.show()
imgplot = plt.imshow(img, clim=(0.064, 0.068))
#plt.axis('off')
plt.show()
mod_img = ndimage.median_filter(imgplot, 20)
plt.imshow(mod_img)
plt.show()
This is the error I am getting. Kindly help in solving this error. I have checked each and every thread regarding this error, but was not successful in solving it.
It seems that the code is doing median filtering but is not able to display the image as the error is occuring on the line:
plt.imshow(mod_img)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-129-8482175fdf0e> in <module>()
16 plt.show()
17 mod_img = ndimage.median_filter(imgplot, 20)
---> 18 plt.imshow(mod_img)
19 plt.show()
C:\Users\Prachi\AppData\Local\Programs\Python\Python36-32\Anaconda3\lib\site-packages\matplotlib\pyplot.py in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, hold, data, **kwargs)
3155 filternorm=filternorm, filterrad=filterrad,
3156 imlim=imlim, resample=resample, url=url, data=data,
-> 3157 **kwargs)
3158 finally:
3159 ax._hold = washold
C:\Users\Prachi\AppData\Local\Programs\Python\Python36-32\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1895 warnings.warn(msg % (label_namer, func.__name__),
1896 RuntimeWarning, stacklevel=2)
-> 1897 return func(ax, *args, **kwargs)
1898 pre_doc = inner.__doc__
1899 if pre_doc is None:
C:\Users\Prachi\AppData\Local\Programs\Python\Python36-32\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)
5122 resample=resample, **kwargs)
5123
-> 5124 im.set_data(X)
5125 im.set_alpha(alpha)
5126 if im.get_clip_path() is None:
C:\Users\Prachi\AppData\Local\Programs\Python\Python36-32\Anaconda3\lib\site-packages\matplotlib\image.py in set_data(self, A)
594 if (self._A.dtype != np.uint8 and
595 not np.can_cast(self._A.dtype, np.float)):
--> 596 raise TypeError("Image data can not convert to float")
597
598 if (self._A.ndim not in (2, 3) or
TypeError: Image data can not convert to float
As I cannot attach image so here are the details of the image.
The image (gray) is the '1_depth.png' from the dataset "Microsoft Kinect and Leap Motion" at
http://lttm.dei.unipd.it/downloads/gesture/
You are trying to apply an image filter to a matplotlib plot. That is not supposed to work. plt.imshow() returns an matplotlib.image.AxesImage, which is a complex class an as such cannot be converted to float.
Instead you should of course apply the filter to the image itself.
img = ...
plt.imshow(img, clim=(0.064, 0.068))
mod_img = ndimage.median_filter(img, 20)
plt.imshow(mod_img)
I had a similar problem with mpimg.imread and plt.imread. Both raised the TypeError.
Instead I resorted to cv2.imread which worked:
import cv2 as cv
im_plt = plt.imread("kangaroo/images/00090.jpg")
im_cv = cv.imread("kangaroo/images/00090.jpg")[:, :, ::-1] #OpenCV users BGR instead of RGB
plt.axis("off")
#plt.imshow(im_plt) # does not work due to TypeError: Image data of dtype object cannot be converted to float
plt.imshow(im_cv) # works
Well from my experience i think it is from the path specified. Try shortening the path. Put it in the same folder it works.
Instead of C:/Users/Prachi/Desktop/kinect_leap_dataset/acquisitions/P1/G1/1_depth.png
just put the image in the G1 folder and make it
G1/1_depth.png