Cartopy set_extent() errors - geospatial

I'm trying to map a contour plot for a certain area on a map, I can create the contour on the map with no problem, but when I set the extent as below, with or without the contour plot, I get the error below (Cartopy version 0.20.3):
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
p = ccrs.Mercator()
ax = plt.axes(projection=p)
ax.set_extent([-140, -60, 20, 70], crs=ccrs.Mercator())
ax.coastlines()
ax.gridlines()
plt.show()
TypeError Traceback (most recent call last) Input In [5], in <cell line: 7>()
5 p = ccrs.Mercator()
6 ax = plt.axes(projection=p)
----> 7 ax.set_extent([-140, -60, 20, 70], crs=ccrs.Mercator())
8 ax.coastlines()
9 ax.gridlines()
File ~\Anaconda3\envs\geospatial\lib\site-packages\cartopy\mpl\geoaxes.py:904,
in GeoAxes.set_extent(self, extents, crs)
901 projected = boundary
903 if projected is None:
--> 904 projected = self.projection.project_geometry(domain_in_crs, crs)
905 try:
906 # This might fail with an unhelpful error message ('need more
907 # than 0 values to unpack') if the specified extents fall outside
908 # the projection extents, so try and give a better error message.
909 x1, y1, x2, y2 = projected.bounds
File ~\Anaconda3\envs\geospatial\lib\site-packages\cartopy\crs.py:805, in Projection.project_geometry(self, geometry, src_crs)
803 if not method_name:
804 raise ValueError(f'Unsupported geometry type {geom_type!r}')
--> 805 return getattr(self, method_name)(geometry, src_crs)
File ~\Anaconda3\envs\geospatial\lib\site-packages\cartopy\crs.py:811, in Projection._project_line_string(self, geometry, src_crs)
810 def _project_line_string(self, geometry, src_crs):
--> 811 return cartopy.trace.project_linear(geometry, src_crs, self)
File lib/cartopy/trace.pyx:628, in cartopy.trace.project_linear()
File lib/cartopy/trace.pyx:100, in cartopy.trace.geos_from_shapely()
TypeError: an integer is required

Change
ax.set_extent([-140, -60, 20, 70], crs=ccrs.Mercator())
(Because values and crs do not match)
to
ax.set_extent([-140, -60, 20, 70], crs=ccrs.PlateCarree())

Related

I am getting the error: shape mismatch: objects cannot be broadcast to a single shape

I want to plot a bar graph for labels in y axis and on x axis the number of datapoints each label has. But I am getting the following error, can anyone please help me with the correct code?
I am writing this code to visualize the number of datapoints divided among labels (0,1,2,3,4...9).
%matplotlib inline
import matplotlib.pyplot as plt
pip install watermark
%load_ext watermark
%watermark -u -v -d -p matplotlib,numpy
%matplotlib inline
import matplotlib.pyplot as plt
# input data
mean_values = [0, 1500, 0, 0, 6000, 1000, 1500, 2000, 1200] #y labels
bar_labels = ['0', '1', '2', '3', '4', '5','6', '7', '8','9'] #x_labels
# plot bars
x_pos = list(range(len(bar_labels)))
rects = plt.bar(x_pos, mean_values, align='center', alpha=0.5)
# label bars
def autolabel(rects):
for ii,rect in enumerate(rects):
height = rect.get_height()
plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, '%s'% (mean_values[ii]),
ha='center', va='bottom')
autolabel(rects)
# set height of the y-axis
max_y = max(zip(mean_values, variance)) # returns a tuple, here: (3, 5)
plt.ylim([0, (max_y[0] + max_y[1]) * 1.1])
# set axes labels and title
plt.ylabel('variable y')
plt.xticks(x_pos, bar_labels)
plt.title('Bar plot with labels')
plt.show()
Error message:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-25c2776ed492> in <module>
7 # plot bars
8 x_pos = list(range(len(bar_labels)))
----> 9 rects = plt.bar(x_pos, mean_values, align='center', alpha=0.5)
10
11 # label bars
4 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/pyplot.py in bar(x, height, width, bottom, align, data, **kwargs)
2407 return gca().bar(
2408 x, height, width=width, bottom=bottom, align=align,
-> 2409 **({"data": data} if data is not None else {}), **kwargs)
2410
2411
/usr/local/lib/python3.7/dist-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
1563 def inner(ax, *args, data=None, **kwargs):
1564 if data is None:
-> 1565 return func(ax, *map(sanitize_sequence, args), **kwargs)
1566
1567 bound = new_sig.bind(ax, *args, **kwargs)
/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_axes.py in bar(self, x, height, width, bottom, align, **kwargs)
2340 x, height, width, y, linewidth = np.broadcast_arrays(
2341 # Make args iterable too.
-> 2342 np.atleast_1d(x), height, width, y, linewidth)
2343
2344 # Now that units have been converted, set the tick locations.
<__array_function__ internals> in broadcast_arrays(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/numpy/lib/stride_tricks.py in broadcast_arrays(subok, *args)
536 args = [np.array(_m, copy=False, subok=subok) for _m in args]
537
--> 538 shape = _broadcast_shape(*args)
539
540 if all(array.shape == shape for array in args):
/usr/local/lib/python3.7/dist-packages/numpy/lib/stride_tricks.py in _broadcast_shape(*args)
418 # use the old-iterator because np.nditer does not handle size 0 arrays
419 # consistently
--> 420 b = np.broadcast(*args[:32])
421 # unfortunately, it cannot handle 32 or more arguments directly
422 for pos in range(32, len(args), 31):
ValueError: shape mismatch: objects cannot be broadcast to a single shape

I keep getting "TypeError: only integer scalar arrays can be converted to a scalar index" while using custom-defined metric in KNeighborsClassifier

I am using a custom-defined metric in SKlearn's KNeighborsClassifier. Here's my code:
def chi_squared(x,y):
return np.divide(np.square(np.subtract(x,y)), np.sum(x,y))
Above function implementation of chi squared distance function. I have used NumPy functions because according to scikit-learn docs, metric function takes two one-dimensional numpy arrays.
I have passed the chi_squared function as an argument to KNeighborsClassifier().
knn = KNeighborsClassifier(algorithm='ball_tree', metric=chi_squared)
However, I keep getting following error:
TypeError Traceback (most recent call last)
<ipython-input-29-d2a365ebb538> in <module>
4
5 knn = KNeighborsClassifier(algorithm='ball_tree', metric=chi_squared)
----> 6 knn.fit(X_train, Y_train)
7 predictions = knn.predict(X_test)
8 print(accuracy_score(Y_test, predictions))
~/.local/lib/python3.8/site-packages/sklearn/neighbors/_classification.py in fit(self, X, y)
177 The fitted k-nearest neighbors classifier.
178 """
--> 179 return self._fit(X, y)
180
181 def predict(self, X):
~/.local/lib/python3.8/site-packages/sklearn/neighbors/_base.py in _fit(self, X, y)
497
498 if self._fit_method == 'ball_tree':
--> 499 self._tree = BallTree(X, self.leaf_size,
500 metric=self.effective_metric_,
501 **self.effective_metric_params_)
sklearn/neighbors/_binary_tree.pxi in sklearn.neighbors._ball_tree.BinaryTree.__init__()
sklearn/neighbors/_binary_tree.pxi in sklearn.neighbors._ball_tree.BinaryTree._recursive_build()
sklearn/neighbors/_ball_tree.pyx in sklearn.neighbors._ball_tree.init_node()
sklearn/neighbors/_binary_tree.pxi in sklearn.neighbors._ball_tree.BinaryTree.rdist()
sklearn/neighbors/_dist_metrics.pyx in sklearn.neighbors._dist_metrics.DistanceMetric.rdist()
sklearn/neighbors/_dist_metrics.pyx in sklearn.neighbors._dist_metrics.PyFuncDistance.dist()
sklearn/neighbors/_dist_metrics.pyx in sklearn.neighbors._dist_metrics.PyFuncDistance._dist()
<ipython-input-29-d2a365ebb538> in chi_squared(x, y)
1 def chi_squared(x,y):
----> 2 return np.divide(np.square(np.subtract(x,y)), np.sum(x,y))
3
4
5 knn = KNeighborsClassifier(algorithm='ball_tree', metric=chi_squared)
<__array_function__ internals> in sum(*args, **kwargs)
~/.local/lib/python3.8/site-packages/numpy/core/fromnumeric.py in sum(a, axis, dtype, out, keepdims, initial, where)
2239 return res
2240
-> 2241 return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims,
2242 initial=initial, where=where)
2243
~/.local/lib/python3.8/site-packages/numpy/core/fromnumeric.py in _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs)
85 return reduction(axis=axis, out=out, **passkwargs)
86
---> 87 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
88
89
TypeError: only integer scalar arrays can be converted to a scalar index
I can reproduce your error message with:
In [173]: x=np.arange(3); y=np.array([2,3,4])
In [174]: np.sum(x,y)
Traceback (most recent call last):
File "<ipython-input-174-1a1a267ebd82>", line 1, in <module>
np.sum(x,y)
File "<__array_function__ internals>", line 5, in sum
File "/usr/local/lib/python3.8/dist-packages/numpy/core/fromnumeric.py", line 2247, in sum
return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims,
File "/usr/local/lib/python3.8/dist-packages/numpy/core/fromnumeric.py", line 87, in _wrapreduction
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
TypeError: only integer scalar arrays can be converted to a scalar index
Correct use(s) of np.sum:
In [175]: np.sum(x)
Out[175]: 3
In [177]: np.sum(np.arange(6).reshape(2,3), axis=0)
Out[177]: array([3, 5, 7])
In [178]: np.sum(np.arange(6).reshape(2,3), 0)
Out[178]: array([3, 5, 7])
(re)read the np.sum docs if necessary!
Using np.add instead of np.sum:
In [179]: np.add(x,y)
Out[179]: array([2, 4, 6])
In [180]: x+y
Out[180]: array([2, 4, 6])
The following should be equivalent:
np.divide(np.square(np.subtract(x,y)), np.add(x,y))
(x-y)**2/(x+y)

Draw vertical line in seaborn pairplot [duplicate]

This question already has an answer here:
How to add individual vlines to every subplot of seaborn FacetGrid
(1 answer)
Closed 1 year ago.
I have the following plot code in seaborn
import seaborn as sns
import matplotlib.pyplot as plt
iris= sns.load_dataset("iris")
g= sns.pairplot(iris,
x_vars=["sepal_width", "sepal_length"],
y_vars=["petal_width"])
This produces the following output
Now I am trying to add a vertical line at x=3 on both plots
I have tried using plt.axvline(x=3, ls='--', linewidth=3, color='red') however that draws the line only on the last plot, as shown below
How can I have the vertical line drawn on both plots?
I have tried g.map_offdiag(plt.axvline(x=1, ls='--', linewidth=3, color='red')) and the g.map() variant, however I get the following error.
TypeError Traceback (most recent call last)
<ipython-input-12-612fcf2a7fef> in <module>
9
10 # plt.axvline(x=3, ls='--', linewidth=3, color='red')
---> 11 g.map_offdiag(plt.axvline(x=1, ls='--', linewidth=3, color='red'))
12
13
~/PycharmProjects/venv/lib/python3.8/site-packages/seaborn/axisgrid.py in map_offdiag(self, func, **kwargs)
1318 if x_var != y_var:
1319 indices.append((i, j))
-> 1320 self._map_bivariate(func, indices, **kwargs)
1321 return self
1322
~/PycharmProjects/venv/lib/python3.8/site-packages/seaborn/axisgrid.py in _map_bivariate(self, func, indices, **kwargs)
1463 if ax is None: # i.e. we are in corner mode
1464 continue
-> 1465 self._plot_bivariate(x_var, y_var, ax, func, **kws)
1466 self._add_axis_labels()
1467
~/PycharmProjects/venv/lib/python3.8/site-packages/seaborn/axisgrid.py in _plot_bivariate(self, x_var, y_var, ax, func, **kwargs)
1471 def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs):
1472 """Draw a bivariate plot on the specified axes."""
-> 1473 if "hue" not in signature(func).parameters:
1474 self._plot_bivariate_iter_hue(x_var, y_var, ax, func, **kwargs)
1475 return
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/inspect.py in signature(obj, follow_wrapped)
3091 def signature(obj, *, follow_wrapped=True):
3092 """Get a signature object for the passed callable."""
-> 3093 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
3094
3095
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/inspect.py in from_callable(cls, obj, follow_wrapped)
2840 def from_callable(cls, obj, *, follow_wrapped=True):
2841 """Constructs Signature for the given callable object."""
-> 2842 return _signature_from_callable(obj, sigcls=cls,
2843 follow_wrapper_chains=follow_wrapped)
2844
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/inspect.py in _signature_from_callable(obj, follow_wrapper_chains, skip_bound_arg, sigcls)
2214
2215 if not callable(obj):
-> 2216 raise TypeError('{!r} is not a callable object'.format(obj))
2217
2218 if isinstance(obj, types.MethodType):
TypeError: <matplotlib.lines.Line2D object at 0x1287cc580> is not a callable object
Any suggestions?
The easiest way is to loop through the axes and call axvline() on each of them. Note that .ravel() converts the 2D array of axes to a 1D array.
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")
g = sns.pairplot(iris,
x_vars=["sepal_width", "sepal_length"],
y_vars=["petal_width"])
for ax in g.axes.ravel():
ax.axvline(x=3, ls='--', linewidth=3, c='red')
plt.show()
To use g.map() or its variants, the first parameter needs to be a function (without calling), followed by the parameters. So, in theory it would be g.map(plt.axvline, x=1, ls='--', linewidth=3, color='red'). But for a pairplot, the mapped function gets called with an x and y parameter from the pairplot, which conflict with the x as parameter for axvline.

AttributeError: Unknown property column in Geopandas plotting of events in zipcode shp file

I am trying to create a Choropleth map showing fire incidents throughout a county in NC. I have the data in a Dataframe and last night I was able to export maps. The only problem was that the data exported was not accurate--so there was a problem with my code. I think I managed to fix that, by merging the shapefiles and data dataframes together, but now, when I run the portion that creates the map, I get AttributeError: Unknown property column Full message:
AttributeError Traceback (most recent call last)
<ipython-input-74-61a60b41abbe> in <module>()
13 # create map
14
---> 15 merged_df.plot(column=variable, cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8');
16
17 ax.axis('off')
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
2939 fontsize=fontsize, colormap=colormap, table=table,
2940 yerr=yerr, xerr=xerr, secondary_y=secondary_y,
-> 2941 sort_columns=sort_columns, **kwds)
2942 __call__.__doc__ = plot_frame.__doc__
2943
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
1975 yerr=yerr, xerr=xerr,
1976 secondary_y=secondary_y, sort_columns=sort_columns,
-> 1977 **kwds)
1978
1979
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _plot(data, x, y, subplots, ax, kind, **kwds)
1802 plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
1803
-> 1804 plot_obj.generate()
1805 plot_obj.draw()
1806 return plot_obj.result
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in generate(self)
258 self._compute_plot_data()
259 self._setup_subplots()
--> 260 self._make_plot()
261 self._add_table()
262 self._make_legend()
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _make_plot(self)
983 stacking_id=stacking_id,
984 is_errorbar=is_errorbar,
--> 985 **kwds)
986 self._add_legend_handle(newlines[0], label, index=i)
987
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _plot(cls, ax, x, y, style, column_num, stacking_id, **kwds)
999 cls._initialize_stacker(ax, stacking_id, len(y))
1000 y_values = cls._get_stacked_values(ax, stacking_id, y, kwds['label'])
-> 1001 lines = MPLPlot._plot(ax, x, y_values, style=style, **kwds)
1002 cls._update_stacker(ax, stacking_id, y)
1003 return lines
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _plot(cls, ax, x, y, style, is_errorbar, **kwds)
613 else:
614 args = (x, y)
--> 615 return ax.plot(*args, **kwds)
616
617 def _get_index_name(self):
~\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
1808 "the Matplotlib list!)" % (label_namer, func.__name__),
1809 RuntimeWarning, stacklevel=2)
-> 1810 return func(ax, *args, **kwargs)
1811
1812 inner.__doc__ = _add_data_doc(inner.__doc__,
~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, *args, **kwargs)
1609 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
1610
-> 1611 for line in self._get_lines(*args, **kwargs):
1612 self.add_line(line)
1613 lines.append(line)
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _grab_next_args(self, *args, **kwargs)
391 this += args[0],
392 args = args[1:]
--> 393 yield from self._plot_args(this, kwargs)
394
395
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
381 "with non-matching shapes is deprecated.")
382 for j in range(max(ncx, ncy)):
--> 383 seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
384 ret.append(seg)
385 return ret
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _makeline(self, x, y, kw, kwargs)
286 default_dict = self._getdefaults(None, kw)
287 self._setdefaults(default_dict, kw)
--> 288 seg = mlines.Line2D(x, y, **kw)
289 return seg
290
~\Anaconda3\lib\site-packages\matplotlib\lines.py in __init__(self, xdata, ydata, linewidth, linestyle, color, marker, markersize, markeredgewidth, markeredgecolor, markerfacecolor, markerfacecoloralt, fillstyle, antialiased, dash_capstyle, solid_capstyle, dash_joinstyle, solid_joinstyle, pickradius, drawstyle, markevery, **kwargs)
408 # update kwargs before updating data to give the caller a
409 # chance to init axes (and hence unit support)
--> 410 self.update(kwargs)
411 self.pickradius = pickradius
412 self.ind_offset = 0
~\Anaconda3\lib\site-packages\matplotlib\artist.py in update(self, props)
914
915 with cbook._setattr_cm(self, eventson=False):
--> 916 ret = [_update_property(self, k, v) for k, v in props.items()]
917
918 if len(ret):
~\Anaconda3\lib\site-packages\matplotlib\artist.py in <listcomp>(.0)
914
915 with cbook._setattr_cm(self, eventson=False):
--> 916 ret = [_update_property(self, k, v) for k, v in props.items()]
917
918 if len(ret):
~\Anaconda3\lib\site-packages\matplotlib\artist.py in _update_property(self, k, v)
910 func = getattr(self, 'set_' + k, None)
911 if not callable(func):
--> 912 raise AttributeError('Unknown property %s' % k)
913 return func(v)
914
AttributeError: Unknown property column
I have no idea how to fix this. I've googled and tried changing the dtype from float to int, tried different columns, but no change. I don't understand because it worked last night, but didn't work when I tried to run it today before making changes. Thank you in advance for any help. Below is the bulk of my code that contains the data frame and mapping, everything else is just getting data from csvs:
import pandas as pd
import numpy as np
#import googlemaps
import gmaps
import gmaps.datasets
import geopandas as gpd
#import matplotlib as plt
import matplotlib.pyplot as plt
import os
import plotly.plotly as py
import plotly.tools as tls
This is what the merged dataframe looks like:
OBJECTID_x int64
ZIPNUM float64
address object
address2 object
apt_room object
arrive_date_time object
cleared_date_time object
dispatch_date_time object
exposure int64
incident_number object
incident_type int64
incident_type_description object
platoon object
station float64
Longitude object
Latitude object
Year int64
Date object
Arr Time object
Seconds float64
Incident object
OBJECTID_y int64
ZIPNAME object
ZIPCODE object
NAME object
SHAPEAREA float64
SHAPELEN float64
LAST_EDITE object
geometry object
dtype: object
# set a variable that will call column to visualise on the map
variable = 'ZIPNUM'
# set the range for the choropleth
vmin, vmax = 50, 2000
# create figure and axes for Matplotlib
fig, ax = plt.subplots(1, figsize=(15, 15))
# create map
merged_df.plot(column=variable, cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8');
ax.axis('off')
ax.set_title('Fire Incident Rate in Wake County', fontdict={'fontsize': '25', 'fontweight' : '3'})
# Create colorbar as a legend
sm = plt.cm.ScalarMappable(cmap='Reds', norm=plt.Normalize(vmin=vmin, vmax=vmax))
# empty array for the data range
sm._A = []
# add the colorbar to the figure
cbar = fig.colorbar(sm)
ax.annotate('2008-2018',
xy=(0.001, .225), xycoords='figure fraction',
horizontalalignment='left', verticalalignment='top',
fontsize=35)
fig.savefig("Fire Incident Rate in Wake County 2008-2018.png", dpi=300)
The problem is that you are trying to use column as a keyword argument. Since you want to plot the 'ZIPNUM' column of the DataFrame, which you store in a variable called variable, you can just pass it as a positional argument to plot(). If you want to plot a relationship between two variables, you can use keyword arguments merged_df.plot(x=variable1, y=variable2)
For you case, you can use
variable = 'ZIPNUM'
merged_df.plot(variable, cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8');
EDIT (based on comments)
You should use markeredgecolor only if you use marker for plotting. edgecolor is not the correct keyword. Moreover, you are assigning a number (string) as color which is again incorrect. Below is a simple example.
df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["A", "B"])
column='A'
df.plot(column, linewidth=0.8, color='r', marker ='o', markeredgewidth=2,
markeredgecolor='blue')

Reconstruct Image from overlapping patches of image

I have used tf.extract_image_patches() to get a tensor of overlapping patches
from the image as described in this link. The answer in the mentioned link suggests to use tf.space_to_depth() to reconstruct the image from overlapping patches. But the problem is that this does not give the desirable results in my case and upon researching I came to know that tf.space_to_depth() does not deal with the overlapping blocks. My code looks like:
import tensorflow as tf
import numpy as np
c = 3
height = 3900
width = 6000
ksizes = [1, 150, 150, 1]
strides = [1, 75, 75, 1]
image = #image of shape [1, height, width, 3]
patches = tf.extract_image_patches(image, ksizes = ksizes, strides= strides, [1, 1, 1, 1], 'VALID')
patches = tf.reshape(patches, [-1, 150, 150, 3])
reconstructed = tf.reshape(patches, [1, height, width, 3])
rec_new = tf.space_to_depth(reconstructed,75)
rec_new = tf.reshape(rec_new,[height,width,3])
This gives me error:
InvalidArgumentError Traceback (most recent call
last)
D:\AnacondaIDE\lib\site-packages\tensorflow\python\framework\common_shapes.py
in _call_cpp_shape_fn_impl(op, input_tensors_needed,
input_tensors_as_shapes_needed, require_shape_fn)
653 graph_def_version, node_def_str, input_shapes, input_tensors,
--> 654 input_tensors_as_shapes, status)
655 except errors.InvalidArgumentError as err:
D:\AnacondaIDE\lib\contextlib.py in exit(self, type, value,
traceback)
87 try:
---> 88 next(self.gen)
89 except StopIteration:
D:\AnacondaIDE\lib\site-packages\tensorflow\python\framework\errors_impl.py
in raise_exception_on_not_ok_status()
465 compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466 pywrap_tensorflow.TF_GetCode(status))
467 finally:
InvalidArgumentError: Dimension size must be evenly divisible by
70200000 but is 271957500 for 'Reshape_22' (op: 'Reshape') with input
shapes: [4029,150,150,3], [4] and with input tensors computed as
partial shapes: input1 = [?,3900,6000,3].
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call
last) in ()
----> 1 reconstructed = tf.reshape(features, [-1, height, width, channel])
2 rec_new = tf.space_to_depth(reconstructed,75)
3 rec_new = tf.reshape(rec_new,[h,h,c])
D:\AnacondaIDE\lib\site-packages\tensorflow\python\ops\gen_array_ops.py
in reshape(tensor, shape, name) 2617 """ 2618 result =
_op_def_lib.apply_op("Reshape", tensor=tensor, shape=shape,
-> 2619 name=name) 2620 return result 2621
D:\AnacondaIDE\lib\site-packages\tensorflow\python\framework\op_def_library.py
in apply_op(self, op_type_name, name, **keywords)
765 op = g.create_op(op_type_name, inputs, output_types, name=scope,
766 input_types=input_types, attrs=attr_protos,
--> 767 op_def=op_def)
768 if output_structure:
769 outputs = op.outputs
D:\AnacondaIDE\lib\site-packages\tensorflow\python\framework\ops.py in
create_op(self, op_type, inputs, dtypes, input_types, name, attrs,
op_def, compute_shapes, compute_device) 2630
original_op=self._default_original_op, op_def=op_def) 2631 if
compute_shapes:
-> 2632 set_shapes_for_outputs(ret) 2633 self._add_op(ret) 2634
self._record_op_seen_by_control_dependencies(ret)
D:\AnacondaIDE\lib\site-packages\tensorflow\python\framework\ops.py in
set_shapes_for_outputs(op) 1909 shape_func =
_call_cpp_shape_fn_and_require_op 1910
-> 1911 shapes = shape_func(op) 1912 if shapes is None: 1913 raise RuntimeError(
D:\AnacondaIDE\lib\site-packages\tensorflow\python\framework\ops.py in
call_with_requiring(op) 1859 1860 def
call_with_requiring(op):
-> 1861 return call_cpp_shape_fn(op, require_shape_fn=True) 1862 1863 _call_cpp_shape_fn_and_require_op =
call_with_requiring
D:\AnacondaIDE\lib\site-packages\tensorflow\python\framework\common_shapes.py
in call_cpp_shape_fn(op, require_shape_fn)
593 res = _call_cpp_shape_fn_impl(op, input_tensors_needed,
594 input_tensors_as_shapes_needed,
--> 595 require_shape_fn)
596 if not isinstance(res, dict):
597 # Handles the case where _call_cpp_shape_fn_impl calls unknown_shape(op).
D:\AnacondaIDE\lib\site-packages\tensorflow\python\framework\common_shapes.py
in _call_cpp_shape_fn_impl(op, input_tensors_needed,
input_tensors_as_shapes_needed, require_shape_fn)
657 missing_shape_fn = True
658 else:
--> 659 raise ValueError(err.message)
660
661 if missing_shape_fn:
ValueError: Dimension size must be evenly divisible by 70200000 but is
271957500 for 'Reshape_22' (op: 'Reshape') with input shapes:
[4029,150,150,3], [4] and with input tensors computed as partial
shapes: input1 = [?,3900,6000,3].
I know this is error due to non-compatible dimensions, but it should be that way, right? Please help me to solve this.
I guess that the problem is that in the link you posted the author is using the same value for strides and ksizes, while you are using strides equal to one half of ksizes. This is the reason why the dimensions do not match, you should write the logic of reducing the size of the patches before gluing them (for instance by selecting the central square of each patch).

Resources