Error when using Tensorflow bucket_by_sequence_length() and tf.py_function() together - tensorflow

I have the following sample code:
import glob
import random
import tensorflow as tf
import cv2
def random_blur(image):
# do stuff which can't be done with a tf.image function...
random_x_blur = random.randint(1, 3)
random_y_blur = random.randint(1, 3)
return cv2.blur(image, (random_x_blur, random_y_blur))
def transform(image):
image = tf.image.random_jpeg_quality(image, 75, 100)
image = tf.image.random_brightness(image, 0.5)
image = tf.image.random_contrast(image, 0.2, 0.5)
# here's the problem...
# image = tf.py_function(func=random_blur, inp=[image], Tout=tf.uint8)
return image
def process_path(file_path):
image = tf.io.read_file(file_path)
image = tf.image.decode_png(image, channels=1)
return transform(image), image
train_directory = 'data/small/'
train_files = glob.glob(train_directory + '*.png')
ds_train = tf.data.Dataset.from_tensor_slices(train_files)
boundaries = [100, 200, 300, 400]
batch_sizes = [16, 16, 16, 16, 16]
ds_train = ds_train.map(process_path, 4)
ds_train = ds_train.bucket_by_sequence_length(element_length_func=lambda x, y: tf.shape(x)[1],
bucket_boundaries=boundaries,
bucket_batch_sizes=batch_sizes)
I'm trying to create a Tensorflow Dataset from variable-width 60px-high images in a directory, using the bucket_by_sequence_length() function to ensure the images in each minibatch have the same dimensions. This all works fine until I uncomment the line beneath "here's the problem" in the code above. When you uncomment that and run it, it produces the following error:
Traceback (most recent call last):
File "test.py", line 34, in <module>
ds_train = ds_train.bucket_by_sequence_length(element_length_func=lambda x, y: tf.shape(x)[1],
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 3120, in bucket_by_sequence_length
return self.group_by_window(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 2976, in group_by_window
return _GroupByWindowDataset(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 5841, in __init__
self._make_reduce_func(reduce_func, input_dataset)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 5890, in _make_reduce_func
self._reduce_func = structured_function.StructuredFunctionWrapper(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/structured_function.py", line 271, in __init__
self._function = fn_factory()
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/eager/function.py", line 2610, in get_concrete_function
graph_function = self._get_concrete_function_garbage_collected(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/eager/function.py", line 2576, in _get_concrete_function_garbage_collected
graph_function, _ = self._maybe_define_function(args, kwargs)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/eager/function.py", line 2760, in _maybe_define_function
graph_function = self._create_graph_function(args, kwargs)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/eager/function.py", line 2670, in _create_graph_function
func_graph_module.func_graph_from_py_func(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/framework/func_graph.py", line 1247, in func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/structured_function.py", line 248, in wrapped_fn
ret = wrapper_helper(*args)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/structured_function.py", line 177, in wrapper_helper
ret = autograph.tf_convert(self._func, ag_ctx)(*nested_args)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/autograph/impl/api.py", line 689, in wrapper
return converted_call(f, args, kwargs, options=options)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/autograph/impl/api.py", line 377, in converted_call
return _call_unconverted(f, args, kwargs, options)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/autograph/impl/api.py", line 458, in _call_unconverted
return f(*args, **kwargs)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 3111, in batching_fn
shapes = make_padded_shapes(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 3083, in make_padded_shapes
shape = [
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/framework/tensor_shape.py", line 882, in __iter__
raise ValueError("Cannot iterate over a shape with unknown rank.")
ValueError: Cannot iterate over a shape with unknown rank.
Likewise, my code works fine if I uncomment that line but remove the call to bucket_by_sequence_length() and limit my training data to images with identical dimensions.
It seems that bucket_by_sequence_length() and tf.py_function() don't play nice together, even with eager mode enabled. I need to do some image augmentations/transformations which the standard tf.image functions don't provide. Any ideas?

Related

MissingDataError: exog contains inf or nans

Input:
import statsmodels.api as sm
import pandas as pd
# reading data from the csv
data = pd.read_csv('/Users/justkiddings/Desktop/Python/TM/TM.csv')
# defining the variables
x = data['FSP'].tolist()
y = data['RSP'].tolist()
# adding the constant term
x = sm.add_constant(x)
# performing the regression
# and fitting the model
result = sm.OLS(y, x).fit()
# printing the summary table
print(result.summary())
Output:
runfile('/Users/justkiddings/Desktop/Python/Code/untitled28.py', wdir='/Users/justkiddings/Desktop/Python/Code')
Traceback (most recent call last):
File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/spyder_kernels/py3compat.py", line 356, in compat_exec
exec(code, globals, locals)
File "/Users/justkiddings/Desktop/Python/Code/untitled28.py", line 24, in <module>
result = sm.OLS(y, x).fit()
File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/regression/linear_model.py", line 890, in __init__
super(OLS, self).__init__(endog, exog, missing=missing,
File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/regression/linear_model.py", line 717, in __init__
super(WLS, self).__init__(endog, exog, missing=missing,
File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/regression/linear_model.py", line 191, in __init__
super(RegressionModel, self).__init__(endog, exog, **kwargs)
File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/model.py", line 267, in __init__
super().__init__(endog, exog, **kwargs)
File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/model.py", line 92, in __init__
self.data = self._handle_data(endog, exog, missing, hasconst,
File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/model.py", line 132, in _handle_data
data = handle_data(endog, exog, missing, hasconst, **kwargs)
File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/data.py", line 673, in handle_data
return klass(endog, exog=exog, missing=missing, hasconst=hasconst,
File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/data.py", line 86, in __init__
self._handle_constant(hasconst)
File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/data.py", line 132, in _handle_constant
raise MissingDataError('exog contains inf or nans')
MissingDataError: exog contains inf or nans
Some of the Data:
DATE,HOUR,STATION,CO,FSP,NO2,NOX,O3,RSP,SO2
1/1/2022,1,TUEN MUN,75,38,39,40,83,59,2
1/1/2022,2,TUEN MUN,72,35,29,30,90,61,2
1/1/2022,3,TUEN MUN,74,38,28,30,91,66,2
1/1/2022,4,TUEN MUN,76,39,31,32,79,61,2
1/1/2022,5,TUEN MUN,72,38,25,26,83,65,2
1/1/2022,6,TUEN MUN,74,37,24,25,86,60,2
I have removed the N.A. in my dataset and they have converted into blanks. (Eg. 3/1/2022,12,TUEN MUN,85,,53,70,59,,5) Why there is MissingDataError? How to fix it? Thanks.

Matplotlib memory leak in Ubuntu, but not in Windows 10

I have a code that reads images from folders and annotates the images. I have about 10K images of size 3K x 3K. I apply cell detection, and I put an annotation on the images. For simplicity, I in the snapshot code provided below, the code generates a random image and random annotations with X and Y location.
The code works fine, in windows 10, with python 3.6 for both multiprocessing and without multiprocessing. However, when I submit to the HPC server with ubuntu 18.04 and Python 3.6, I am getting memory error with Matplotlib. I have tried the following, but no luck in resolving the problem.
* plt.close(fig)
* plt.figure().clear()
* plt.clf()
* plt.close()
'''
import os
import matplotlib.pyplot as plot
import pandas as pd
import multiprocessing as mp
import numpy as np
import seaborn as sns
sns.set_palette('bright')
def mark_points(im, df, file_name):
# this code put scatter plot on the image and saves the the figure
dpi = 100
height, width, nbands = im.shape
# What size does the figure need to be in inches to fit the image?
fig_size = width / float(dpi), height / float(dpi)
# Create a figure of the right size with one axes that takes up the full figure
fig = plt.figure(figsize=fig_size)
ax = fig.add_axes([0, 0, 1, 1])
# Hide spines, ticks, etc.
ax.axis('off')
# Display the image.
ax.imshow(im, interpolation='nearest')
sns.scatterplot(x='X',
y='Y',
data=df,
hue='Class',
ax=ax,
s=2,
edgecolor=None,
legend=False)
ax.set(xlim=[0, width], ylim=[height, 0], aspect=1)
# save image with cell annotation
fig.savefig(file_name, dpi=dpi, transparent=True)
# plt.close(fig)
plt.figure().clear()
plt.clf()
plt.close()
def annotate_images(output_dir,
process_num):
# create an image and random X and Y location for annotation
os.makedirs(output_dir, exist_ok=True)
for j in range(10000):
# this approximately the size of image I am processing
im_height, im_width = 3000, 3000
# print('{}'.format(process_num))
file_name = 'my_file_name_{}.jpg'.format(process_num)
output_file = os.path.join(output_dir, file_name)
# generate dataframe with data to plot
df = pd.DataFrame(columns=['X', 'Y', 'Class'])
num_points = 20000
df['X'] = np.random.randint(0, im_width, size=(num_points), dtype='int32').tolist()
df['Y'] = np.random.randint(0, im_height, size=(num_points), dtype='int32').tolist()
classes_ = ['A', 'B', 'C']
df['Class'] = [classes_[np.random.randint(0, 3)] for _ in range(num_points)]
# generate a random image
im = np.random.randint(low=0, high=255, size=(im_height, im_width, 3), dtype=np.uint8)
mark_points(im=im, df=df, file_name=output_file)
def run(output_dir,
num_processes=1,
multi_process=False
):
# number of folders
n = 100
for i in range(n):
if multi_process is True:
processes = [
mp.Process(target=annotate_images, args=(output_dir, process_num)) for process_num in range(num_processes)]
print('{} processes created'.format(num_processes))
# Run processes
for p in processes:
p.start()
# Exit the completed processes
for p in processes:
p.join()
print('All Processes finished!!!')
else:
annotate_images(output_dir=output_dir,
process_num=0
)
if __name__ == '__main__':
num_processes = 4
multi_process = True
home_dir = r'Output'
for i in range(3):
params = dict(output_dir=home_dir,
num_processes=num_processes,
multi_process=multi_process)
run(**params)
'''
Error message
image_annotate_cells.py:44: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
plt.figure().clear()
image_annotate_cells.py:22: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
fig = plt.figure(figsize=fig_size)
Process Process-1:
Traceback (most recent call last):
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "image_annotate_cells.py", line 74, in annotate_images
mark_points(im=im, df=df, file_name=output_file)
File "image_annotate_cells.py", line 42, in mark_points
fig.savefig(file_name, dpi=dpi, transparent=True)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/figure.py", line 2203, in savefig
self.canvas.print_figure(fname, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 2126, in print_figure
**kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py", line 358, in wrapper
return func(*args, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 584, in print_jpg
FigureCanvasAgg.draw(self)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 393, in draw
self.figure.draw(self.renderer)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/figure.py", line 1736, in draw
renderer, self, artists, self.suppressComposite)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/image.py", line 137, in _draw_list_compositing_images
a.draw(renderer)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 2630, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/image.py", line 137, in _draw_list_compositing_images
a.draw(renderer)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/collections.py", line 894, in draw
Collection.draw(self, renderer)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/collections.py", line 369, in draw
self._offset_position)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/path.py", line 197, in vertices
#property
KeyboardInterrupt
Traceback (most recent call last):
File "image_annotate_cells.py", line 124, in <module>
run(**params)
File "image_annotate_cells.py", line 97, in run
p.join()
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/multiprocessing/process.py", line 124, in join
res = self._popen.wait(timeout)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/multiprocessing/popen_fork.py", line 50, in wait
return self.poll(os.WNOHANG if timeout == 0.0 else 0)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/multiprocessing/popen_fork.py", line 28, in poll
pid, sts = os.waitpid(self.pid, flag)
KeyboardInterrupt

Matplotlib error, [Errno 2] No such file or directory: 'latex': 'latex'?

When I try running the very simple code snippet from www.matplotlib.org,
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
import numpy as np
import matplotlib.pyplot as plt
# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(t, s)
plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)',fontsize=16)
plt.title(r"\TeX\ is Number "
r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
fontsize=16, color='gray')
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8)
plt.savefig('tex_demo')
plt.show()
This is highly unusual this code has worked for me before and I cannot figure out what the issue is. The error message that I receive is enormous and shown below. Does anybody know what the issue might be?
Thanks!!
Traceback (most recent call last):
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/IPython/core/formatters.py",
line 332, in call
return printer(obj)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py",
line 237, in
png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py",
line 121, in print_figure
fig.canvas.print_figure(bytes_io, **kw)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py",
line 2216, in print_figure
**kwargs)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py",
line 507, in print_png
FigureCanvasAgg.draw(self)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py",
line 430, in draw
self.figure.draw(self.renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py",
line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/figure.py",
line 1299, in draw
renderer, self, artists, self.suppressComposite)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/image.py",
line 138, in _draw_list_compositing_images
a.draw(renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py",
line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_base.py",
line 2437, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/image.py",
line 138, in _draw_list_compositing_images
a.draw(renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py",
line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py",
line 1135, in draw
renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py",
line 1075, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/text.py",
line 933, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/text.py",
line 308, in _get_layout
ismath=False)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py",
line 226, in get_text_width_height_descent
s, fontsize, renderer=self)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/texmanager.py",
line 602, in get_text_width_height_descent
dvifile = self.make_dvi(tex, fontsize)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/texmanager.py",
line 393, in make_dvi
stderr=subprocess.STDOUT)
File "/Users/evan/anaconda3/lib/python3.6/subprocess.py", line 336,
in check_output
**kwargs).stdout
File "/Users/evan/anaconda3/lib/python3.6/subprocess.py", line 403,
in run
with Popen(*popenargs, **kwargs) as process:
File "/Users/evan/anaconda3/lib/python3.6/subprocess.py", line 709,
in init
restore_signals, start_new_session)
File "/Users/evan/anaconda3/lib/python3.6/subprocess.py", line 1344,
in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'latex':
'latex'
For linux:
sudo yum install latex
sudo yum install dvipng
For Window:
install texlive.
ref. https://matplotlib.org/tutorials/text/usetex.html?highlight=latex
Download miktex and add the path in environment variables for Windows.

Conditioning pixelsnail on classes

I am trying to condition a pixelcnn model that I adapted, but there is needed some changes to condition the model on classes (series). I am working with time-series so in fact I would like to know how could I condition the model in some series as well. But the case, when I try to one hot encode my "Y"[batch,] labels that I am giving to it as an array of the same batch length that "X" [batch, sqrt(seq_len), sqrt(seq_len), channels]. To condition the model, I have the next code:
if args.class_conditional:
# raise NotImplementedError
num_labels = train_data.get_num_labels()
y_init = tf.placeholder(tf.int32, shape=(args.init_batch_size,))
h_init = tf.one_hot(y_init, num_labels)
y_sample = np.split(
np.mod(np.arange(args.batch_size), num_labels), args.nr_gpu)
h_sample = [tf.one_hot(tf.Variable(y_sample[i], trainable=False), num_labels)
for i in range(args.nr_gpu)]
ys = [tf.placeholder(tf.int32, shape=(args.batch_size,))
for i in range(args.nr_gpu)]
hs = [tf.one_hot(ys[i], num_labels) for i in range(args.nr_gpu)]
else:
h_init = None
h_sample = [None] * args.nr_gpu
hs = h_sample
The current output of "y_sample" that is where the shell is locating me the error:
[array([0. , 1. , 0.30521799, 1.30521799, 0.61043598,
1.61043598, 0.91565397, 0.22087195, 1.22087195, 0.52608994,
1.52608994, 0.83130793, 0.13652592, 1.13652592, 0.44174391,
1.44174391, 0.7469619 , 0.05217988, 1.05217988, 0.35739787,
1.35739787, 0.66261586, 1.66261586, 0.96783385, 0.27305184,
1.27305184, 0.57826983, 1.57826983, 0.88348781, 0.1887058 ,
1.1887058 , 0.49392379, 1.49392379, 0.79914178, 0.10435977,
1.10435977, 0.40957776, 1.40957776, 0.71479575, 0.02001373,
1.02001373, 0.32523172, 1.32523172, 0.63044971, 1.63044971,
0.9356677 , 0.24088569, 1.24088569, 0.54610368, 1.54610368])]
it is giving me an error in h_sample when it is going to do the one_hot
Traceback (most recent call last):
File "train.py", line 398, in <module>
main(FLAGS)
File "train.py", line 111, in main
for i in range(args.nr_gpu)]
File "train.py", line 111, in <listcomp>
for i in range(args.nr_gpu)]
File "/home/proto/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 2364, in one_hot
name)
File "/home/proto/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/gen_array_ops.py", line 2831, in _one_hot
off_value=off_value, axis=axis, name=name)
File "/home/proto/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 609, in _apply_op_helper
param_name=input_name)
File "/home/proto/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 60, in _SatisfiesTypeConstraint
", ".join(dtypes.as_dtype(x).name for x in allowed_list)))
TypeError: Value passed to parameter 'indices' has DataType float64 not in list of allowed values: uint8, int32, int64
I changed for i in range(args.nr_gpu)] hard-coded to 1 to see if it was the problem but it keeps giving me errors.

tensorflow tutorial mnist_with_summary throws TypeError

I am running the mnist_with_summary tutorial to see how the TensorBoard works. It throws a TypeError right away.
Extracting /tmp/data/train-images-idx3-ubyte.gz
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):
File "/Users/bruceho/workspace/TestTensorflow/mysrc/examples/tutorials/mnist/mnist_with_summaries.py", line 166, in <module>
tf.app.run()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/platform/app.py", line 30, in run
sys.exit(main(sys.argv[:1] + flags_passthrough))
File "/Users/bruceho/workspace/TestTensorflow/mysrc/examples/tutorials/mnist/mnist_with_summaries.py", line 163, in main
train()
File "/Users/bruceho/workspace/TestTensorflow/mysrc/examples/tutorials/mnist/mnist_with_summaries.py", line 110, in train
y = nn_layer(dropped, 500, 10, 'layer2', act=tf.nn.softmax)
File "/Users/bruceho/workspace/TestTensorflow/mysrc/examples/tutorials/mnist/mnist_with_summaries.py", line 104, in nn_layer
activations = act(preactivate, 'activation')
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/ops/nn_ops.py", line 582, in softmax
return _softmax(logits, gen_nn_ops._softmax, dim, name)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/ops/nn_ops.py", line 542, in _softmax
logits = _swap_axis(logits, dim, math_ops.sub(input_rank, 1))
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/ops/nn_ops.py", line 518, in _swap_axis
0, [math_ops.range(dim_index), [last_index],
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/ops/math_ops.py", line 991, in range
return gen_math_ops._range(start, limit, delta, name=name)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/ops/gen_math_ops.py", line 1675, in _range
delta=delta, name=name)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/framework/op_def_library.py", line 490, in apply_op
preferred_dtype=default_dtype)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 657, in convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/framework/constant_op.py", line 180, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/framework/constant_op.py", line 163, in constant
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape))
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/framework/tensor_util.py", line 353, in make_tensor_proto
_AssertCompatible(values, dtype)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/tensorflow/python/framework/tensor_util.py", line 290, in _AssertCompatible
(dtype.name, repr(mismatch), type(mismatch).__name__))
TypeError: Expected int32, got 'activation' of type 'str' instead.
I tried running from inside eclipse and command line with the same results. Any one experience the same problem?
I think you must have modified the original code somehow. Your problem lies in this line:activations = act(preactivate, 'activation'). So if you check the api of tf.nn.softmax, you would find that the second argument represents dim instead of name. So to fix the problem, just change this line into:activations = act(preactivate, name='activation')
Besides, I don't know if you have changed
diff = tf.nn.softmax_cross_entropy_with_logits(y, y_)
If not, you probably have softmax the output twice.