Invalid operation is performed in: LinearFunction (Forward) - python-3.x

this is the main code. The images size is 420*420
import os
import chainer
from chainer import training
from chainer.training import extensions
batchsize = 64
epoch = 10
gpu = 0
dataset = "/content/gdrive/My Drive/images/"
out = "/content/gdrive/My Drive/DCGAN/"
resume = ""
n_hidden = 100
seed = 0
snapshot_interval = 200
display_interval = 100
# Set up a neural network to train
gen = Generator(n_hidden=n_hidden)
dis = Discriminator()
if gpu >= 0:
# Make a specified GPU current
chainer.backends.cuda.get_device_from_id(gpu).use()
gen.to_gpu() # Copy the model to the GPU
dis.to_gpu()
# Setup an optimizer
def make_optimizer(model, alpha=0.0002, beta1=0.5):
optimizer = chainer.optimizers.Adam(alpha=alpha, beta1=beta1)
optimizer.setup(model)
optimizer.add_hook(
chainer.optimizer_hooks.WeightDecay(0.0001), 'hook_dec')
return optimizer
opt_gen = make_optimizer(gen)
opt_dis = make_optimizer(dis)
if dataset == '':
# Load the CIFAR10 dataset if args.dataset is not specified
train, _ = chainer.datasets.get_cifar10(withlabel=False, scale=255.)
else:
all_files = os.listdir(dataset)
image_files = [f for f in all_files if ('png' in f or 'jpg' in f)]
print('{} contains {} image files'
.format(dataset, len(image_files)))
train = chainer.datasets\
.ImageDataset(paths=image_files, root=dataset)
# Setup an iterator
train_iter = chainer.iterators.SerialIterator(train, batchsize)
# Setup an updater
updater = DCGANUpdater(
models=(gen, dis),
iterator=train_iter,
optimizer={
'gen': opt_gen, 'dis': opt_dis},
device=gpu)
# Setup a trainer
trainer = training.Trainer(updater, (epoch, 'epoch'), out=out)
snapshot_interval = (snapshot_interval, 'iteration')
display_interval = (display_interval, 'iteration')
trainer.extend(
extensions.snapshot(filename='snapshot_iter_{.updater.iteration}.npz'),
trigger=snapshot_interval)
trainer.extend(extensions.snapshot_object(
gen, 'gen_iter_{.updater.iteration}.npz'), trigger=snapshot_interval)
trainer.extend(extensions.snapshot_object(
dis, 'dis_iter_{.updater.iteration}.npz'), trigger=snapshot_interval)
trainer.extend(extensions.LogReport(trigger=display_interval))
trainer.extend(extensions.PrintReport([
'epoch', 'iteration', 'gen/loss', 'dis/loss',
]), trigger=display_interval)
trainer.extend(extensions.ProgressBar(update_interval=10))
trainer.extend(
out_generated_image(
gen, dis,
420, 420, seed, out),
trigger=snapshot_interval)
if resume:
# Resume from a snapshot
chainer.serializers.load_npz(resume, trainer)
# Run the training
trainer.run()
Full error code
Exception in main training loop:
Invalid operation is performed in: LinearFunction (Forward)
Expect: x.shape[1] == W.shape[1]
Actual: 1384448 != 8192
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/chainer/training/trainer.py", line 315, in run
update()
File "/usr/local/lib/python3.6/dist-packages/chainer/training/updaters/standard_updater.py", line 165, in update
self.update_core()
File "<ipython-input-3-1c9eda353b43>", line 37, in update_core
y_real = dis(x_real)
File "/usr/local/lib/python3.6/dist-packages/chainer/link.py", line 242, in __call__
out = forward(*args, **kwargs)
File "<ipython-input-2-8321f7283f65>", line 81, in forward
return self.l4(h)
File "/usr/local/lib/python3.6/dist-packages/chainer/link.py", line 242, in __call__
out = forward(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/chainer/links/connection/linear.py", line 138, in forward
return linear.linear(x, self.W, self.b, n_batch_axes=n_batch_axes)
File "/usr/local/lib/python3.6/dist-packages/chainer/functions/connection/linear.py", line 289, in linear
y, = LinearFunction().apply(args)
File "/usr/local/lib/python3.6/dist-packages/chainer/function_node.py", line 245, in apply
self._check_data_type_forward(in_data)
File "/usr/local/lib/python3.6/dist-packages/chainer/function_node.py", line 330, in _check_data_type_forward
self.check_type_forward(in_type)
File "/usr/local/lib/python3.6/dist-packages/chainer/functions/connection/linear.py", line 27, in check_type_forward
x_type.shape[1] == w_type.shape[1],
File "/usr/local/lib/python3.6/dist-packages/chainer/utils/type_check.py", line 546, in expect
expr.expect()
File "/usr/local/lib/python3.6/dist-packages/chainer/utils/type_check.py", line 483, in expect
'{0} {1} {2}'.format(left, self.inv, right))
Will finalize trainer extensions and updater before reraising the exception.
---------------------------------------------------------------------------
InvalidType Traceback (most recent call last)
<ipython-input-8-a0fb675be455> in <module>()
89
90 # Run the training
---> 91 trainer.run()
92
93
/usr/local/lib/python3.6/dist-packages/chainer/training/trainer.py in run(self, show_loop_exception_msg)
327 f.write('Will finalize trainer extensions and updater before '
328 'reraising the exception.\n')
--> 329 six.reraise(*sys.exc_info())
330 finally:
331 for _, entry in extensions:
/usr/local/lib/python3.6/dist-packages/six.py in reraise(tp, value, tb)
691 if value.__traceback__ is not tb:
692 raise value.with_traceback(tb)
--> 693 raise value
694 finally:
695 value = None
/usr/local/lib/python3.6/dist-packages/chainer/training/trainer.py in run(self, show_loop_exception_msg)
313 self.observation = {}
314 with reporter.scope(self.observation):
--> 315 update()
316 for name, entry in extensions:
317 if entry.trigger(self):
/usr/local/lib/python3.6/dist-packages/chainer/training/updaters/standard_updater.py in update(self)
163
164 """
--> 165 self.update_core()
166 self.iteration += 1
167
<ipython-input-3-1c9eda353b43> in update_core(self)
35 batchsize = len(batch)
36
---> 37 y_real = dis(x_real)
38
39 z = Variable(xp.asarray(gen.make_hidden(batchsize)))
/usr/local/lib/python3.6/dist-packages/chainer/link.py in __call__(self, *args, **kwargs)
240 if forward is None:
241 forward = self.forward
--> 242 out = forward(*args, **kwargs)
243
244 # Call forward_postprocess hook
<ipython-input-2-8321f7283f65> in forward(self, x)
79 h = F.leaky_relu(add_noise(self.bn2_1(self.c2_1(h))))
80 h = F.leaky_relu(add_noise(self.bn3_0(self.c3_0(h))))
---> 81 return self.l4(h)
/usr/local/lib/python3.6/dist-packages/chainer/link.py in __call__(self, *args, **kwargs)
240 if forward is None:
241 forward = self.forward
--> 242 out = forward(*args, **kwargs)
243
244 # Call forward_postprocess hook
/usr/local/lib/python3.6/dist-packages/chainer/links/connection/linear.py in forward(self, x, n_batch_axes)
136 in_size = functools.reduce(operator.mul, x.shape[1:], 1)
137 self._initialize_params(in_size)
--> 138 return linear.linear(x, self.W, self.b, n_batch_axes=n_batch_axes)
/usr/local/lib/python3.6/dist-packages/chainer/functions/connection/linear.py in linear(x, W, b, n_batch_axes)
287 args = x, W, b
288
--> 289 y, = LinearFunction().apply(args)
290 if n_batch_axes > 1:
291 y = y.reshape(batch_shape + (-1,))
/usr/local/lib/python3.6/dist-packages/chainer/function_node.py in apply(self, inputs)
243
244 if configuration.config.type_check:
--> 245 self._check_data_type_forward(in_data)
246
247 hooks = chainer.get_function_hooks()
/usr/local/lib/python3.6/dist-packages/chainer/function_node.py in _check_data_type_forward(self, in_data)
328 in_type = type_check.get_types(in_data, 'in_types', False)
329 with type_check.get_function_check_context(self):
--> 330 self.check_type_forward(in_type)
331
332 def check_type_forward(self, in_types):
/usr/local/lib/python3.6/dist-packages/chainer/functions/connection/linear.py in check_type_forward(self, in_types)
25 x_type.ndim == 2,
26 w_type.ndim == 2,
---> 27 x_type.shape[1] == w_type.shape[1],
28 )
29 if type_check.eval(n_in) == 3:
/usr/local/lib/python3.6/dist-packages/chainer/utils/type_check.py in expect(*bool_exprs)
544 for expr in bool_exprs:
545 assert isinstance(expr, Testable)
--> 546 expr.expect()
547
548
/usr/local/lib/python3.6/dist-packages/chainer/utils/type_check.py in expect(self)
481 raise InvalidType(
482 '{0} {1} {2}'.format(self.lhs, self.exp, self.rhs),
--> 483 '{0} {1} {2}'.format(left, self.inv, right))
484
485
InvalidType:
Invalid operation is performed in: LinearFunction (Forward)
Expect: x.shape[1] == W.shape[1]
Actual: 1384448 != 8192
The Discriminator
class Discriminator(chainer.Chain):
def __init__(self, bottom_width=4, ch=512, wscale=0.02):
w = chainer.initializers.Normal(wscale)
super(Discriminator, self).__init__()
with self.init_scope():
self.c0_0 = L.Convolution2D(3, ch // 8, 3, 1, 1, initialW=w)
self.c0_1 = L.Convolution2D(ch // 8, ch // 4, 4, 2, 1, initialW=w)
self.c1_0 = L.Convolution2D(ch // 4, ch // 4, 3, 1, 1, initialW=w)
self.c1_1 = L.Convolution2D(ch // 4, ch // 2, 4, 2, 1, initialW=w)
self.c2_0 = L.Convolution2D(ch // 2, ch // 2, 3, 1, 1, initialW=w)
self.c2_1 = L.Convolution2D(ch // 2, ch // 1, 4, 2, 1, initialW=w)
self.c3_0 = L.Convolution2D(ch // 1, ch // 1, 3, 1, 1, initialW=w)
self.l4 = L.Linear(bottom_width * bottom_width * ch, 1, initialW=w)
self.bn0_1 = L.BatchNormalization(ch // 4, use_gamma=False)
self.bn1_0 = L.BatchNormalization(ch // 4, use_gamma=False)
self.bn1_1 = L.BatchNormalization(ch // 2, use_gamma=False)
self.bn2_0 = L.BatchNormalization(ch // 2, use_gamma=False)
self.bn2_1 = L.BatchNormalization(ch // 1, use_gamma=False)
self.bn3_0 = L.BatchNormalization(ch // 1, use_gamma=False)
def forward(self, x):
h = add_noise(x)
h = F.leaky_relu(add_noise(self.c0_0(h)))
h = F.leaky_relu(add_noise(self.bn0_1(self.c0_1(h))))
h = F.leaky_relu(add_noise(self.bn1_0(self.c1_0(h))))
h = F.leaky_relu(add_noise(self.bn1_1(self.c1_1(h))))
h = F.leaky_relu(add_noise(self.bn2_0(self.c2_0(h))))
h = F.leaky_relu(add_noise(self.bn2_1(self.c2_1(h))))
h = F.leaky_relu(add_noise(self.bn3_0(self.c3_0(h))))
return self.l4(h)

So the problem was the value of bottom_width in the Discriminator it should be equal to the (image size)/(2^3). in this case it would be 420/2^3 = 52.5 but if the result is a float then you get the int value which is 52

Related

Result type Float can’t be cast to the desired output type Byte

I am trying to make a model to classify knee MRIs. I am using the torchio library and I have succesfully train a classifier to the raw data. Now, I am adding masks to the MRI object and I want to pass them to a model. I use the same code but now I am getting this error:
RuntimeError Traceback (most recent call last)
<ipython-input-56-2a7d5ddf84fc> in <module>()
26 for epoch in range(1, num_epochs+1):
27
---> 28 train_loss, train_accuracy = training(epoch,model,train_loader,optimizer,criterion)
29 valid_loss, valid_accuracy = validation(epoch,model,valid_loader,criterion)
30
6 frames
<ipython-input-55-59a55a26f2b7> in training(epoch, model, train_loader, optimizer, criterion)
8 model.train()
9
---> 10 for i, batch in tqdm(enumerate(train_loader,0)):
11 images = batch['t1'][tio.DATA].cuda()
12 labels = batch['label']
/usr/local/lib/python3.7/dist-packages/tqdm/notebook.py in __iter__(self)
255 def __iter__(self):
256 try:
--> 257 for obj in super(tqdm_notebook, self).__iter__():
258 # return super(tqdm...) will not catch exception
259 yield obj
/usr/local/lib/python3.7/dist-packages/tqdm/std.py in __iter__(self)
1193
1194 try:
-> 1195 for obj in iterable:
1196 yield obj
1197 # Update and possibly print the progressbar.
/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py in __next__(self)
519 if self._sampler_iter is None:
520 self._reset()
--> 521 data = self._next_data()
522 self._num_yielded += 1
523 if self._dataset_kind == _DatasetKind.Iterable and \
/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py in _next_data(self)
1201 else:
1202 del self._task_info[idx]
-> 1203 return self._process_data(data)
1204
1205 def _try_put_index(self):
/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py in _process_data(self, data)
1227 self._try_put_index()
1228 if isinstance(data, ExceptionWrapper):
-> 1229 data.reraise()
1230 return data
1231
/usr/local/lib/python3.7/dist-packages/torch/_utils.py in reraise(self)
432 # instantiate since we don't know how to
433 raise RuntimeError(msg) from None
--> 434 raise exception
435
436
RuntimeError: Caught RuntimeError in DataLoader worker process 0.
Original Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/worker.py", line 287, in _worker_loop
data = fetcher.fetch(index)
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/fetch.py", line 52, in fetch
return self.collate_fn(data)
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/collate.py", line 74, in default_collate
return {key: default_collate([d[key] for d in batch]) for key in elem}
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/collate.py", line 74, in <dictcomp>
return {key: default_collate([d[key] for d in batch]) for key in elem}
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/collate.py", line 74, in default_collate
return {key: default_collate([d[key] for d in batch]) for key in elem}
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/collate.py", line 74, in <dictcomp>
return {key: default_collate([d[key] for d in batch]) for key in elem}
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/collate.py", line 56, in default_collate
return torch.stack(batch, 0, out=out)
RuntimeError: result type Float can't be cast to the desired output type Byte
The training() function is this:
def training(epoch, model, train_loader, optimizer, criterion):
"Training over an epoch"
metric_monitor = MetricMonitor()
model.train()
for i, batch in tqdm(enumerate(train_loader,0)):
images = batch['t1'][tio.DATA].cuda()
labels = batch['label'].cuda()
if images.sum() != 0:
output = F.softmax(model(images), dim =1)
loss = criterion(output, labels)
output = output.data.max(dim=1,keepdim=True)[1]
output = output.view(-1)
acc = calculate_acc(output, labels)
metric_monitor.update("Loss", loss.item())
metric_monitor.update("Accuracy", acc)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print("[Epoch: {epoch:03d}] Train | {metric_monitor}".format(epoch=epoch, metric_monitor=metric_monitor))
return metric_monitor.metrics['Loss']['avg'], metric_monitor.metrics['Accuracy']['avg']
When I run the code some batches pass but it stops on some batches and produces this error. I have checked my data and all of them are torch.FloatTensor
The labels are integers. Does anybody know how to fix this ?

How do I fix the ResourceExhaustedError: Traceback (most recent call last)/2 root error(s) found errors I am getting

I am working on an ESPCN model and I tried to build it like this,
upscale_factor = 3
inputs = keras.Input(shape=(None, None, 1))
conv1 = layers.Conv2D(64, 5, activation="tanh", padding="same")(inputs)
conv2 = layers.Conv2D(32, 3, activation="tanh", padding="same")(conv1)
conv3 = layers.Conv2D((upscale_factor*upscale_factor), 3, activation="sigmoid", padding="same")(conv2)
outputs = tf.nn.depth_to_space(conv3, upscale_factor, data_format='NHWC')
model = Model(inputs=inputs, outputs=outputs)
def gen_dataset(filenames, scale):
crop_size_lr = 128
crop_size_hr = 128 * scale
for p in filenames:
image_decoded = cv2.imread("Training/DF2K/"+p.decode(), 3).astype(np.float32) / 255.0
imgYCC = cv2.cvtColor(image_decoded, cv2.COLOR_BGR2YCrCb)
cropped = imgYCC[0:(imgYCC.shape[0] - (imgYCC.shape[0] % scale)),
0:(imgYCC.shape[1] - (imgYCC.shape[1] % scale)), :]
lr = cv2.resize(cropped, (int(cropped.shape[1] / scale), int(cropped.shape[0] / scale)),
interpolation=cv2.INTER_CUBIC)
hr_y = imgYCC[:, :, 0]
lr_y = lr[:, :, 0]
numx = int(lr.shape[0] / crop_size_lr)
numy = int(lr.shape[1] / crop_size_lr)
for i in range(0, numx):
startx = i * crop_size_lr
endx = (i * crop_size_lr) + crop_size_lr
startx_hr = i * crop_size_hr
endx_hr = (i * crop_size_hr) + crop_size_hr
for j in range(0, numy):
starty = j * crop_size_lr
endy = (j * crop_size_lr) + crop_size_lr
starty_hr = j * crop_size_hr
endy_hr = (j * crop_size_hr) + crop_size_hr
crop_lr = lr_y[startx:endx, starty:endy]
crop_hr = hr_y[startx_hr:endx_hr, starty_hr:endy_hr]
hr = crop_hr.reshape((crop_size_hr, crop_size_hr, 1))
lr = crop_lr.reshape((crop_size_lr, crop_size_lr, 1))
yield lr, hr
import os
filenames = os.listdir("Training/DF2K/")
ds = tf.data.Dataset.from_generator(
gen_dataset, (tf.float32, tf.float32), (tf.TensorShape([None, None, 1]), tf.TensorShape([None, None, 1])),
args=[filenames, upscale_factor]).batch(32).shuffle(buffer_size=5000)
def PSNR(y_true, y_pred):
max_pixel = 1.0
return tf.image.psnr(y_true, y_pred, max_val=max_pixel)
opt=tf.keras.optimizers.Adamax(
learning_rate=0.001)
model.compile(optimizer=opt,
loss='mse',
metrics=[PSNR])
model.fit(ds, epochs=60, verbose=2)
But when I try to train the model I get the following error:
---------------------------------------------------------------------------
ResourceExhaustedError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11332/3038405447.py in <module>
----> 1 model.fit(ds, epochs=60, verbose=2)
C:\ProgramData\Anaconda3\envs\gpu2\lib\site-packages\keras\utils\traceback_utils.py in error_handler(*args, **kwargs)
65 except Exception as e: # pylint: disable=broad-except
66 filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67 raise e.with_traceback(filtered_tb) from None
68 finally:
69 del filtered_tb
~\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
56 try:
57 ctx.ensure_initialized()
---> 58 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
59 inputs, attrs, num_outputs)
60 except core._NotOkStatusException as e:
ResourceExhaustedError: 2 root error(s) found.
(0) RESOURCE_EXHAUSTED: MemoryError: Unable to allocate 35.6 MiB for an array with shape (1524, 2040, 3) and data type float32
Traceback (most recent call last):
File "C:\Users\TanveerU\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\ops\script_ops.py", line 275, in __call__
ret = func(*args)
File "C:\Users\TanveerU\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\autograph\impl\api.py", line 649, in wrapper
return func(*args, **kwargs)
File "C:\Users\TanveerU\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 992, in generator_py_func
values = next(generator_state.get_iterator(iterator_id))
File "C:\Users\TanveerU\AppData\Local\Temp/ipykernel_11332/1792224485.py", line 7, in gen_dataset
image_decoded = cv2.imread("Training/DF2K/"+p.decode(), 3).astype(np.float32) / 255.0
numpy.core._exceptions._ArrayMemoryError: Unable to allocate 35.6 MiB for an array with shape (1524, 2040, 3) and data type float32
[[{{node PyFunc}}]]
[[IteratorGetNext]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. This isn't available when running in Eager mode.
[[gradient_tape/mean_squared_error/Shape_5/_10]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. This isn't available when running in Eager mode.
(1) RESOURCE_EXHAUSTED: MemoryError: Unable to allocate 35.6 MiB for an array with shape (1524, 2040, 3) and data type float32
Traceback (most recent call last):
File "C:\Users\TanveerU\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\ops\script_ops.py", line 275, in __call__
ret = func(*args)
File "C:\Users\TanveerU\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\autograph\impl\api.py", line 649, in wrapper
return func(*args, **kwargs)
File "C:\Users\TanveerU\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\data\ops\dataset_ops.py", line 992, in generator_py_func
values = next(generator_state.get_iterator(iterator_id))
File "C:\Users\TanveerU\AppData\Local\Temp/ipykernel_11332/1792224485.py", line 7, in gen_dataset
image_decoded = cv2.imread("Training/DF2K/"+p.decode(), 3).astype(np.float32) / 255.0
numpy.core._exceptions._ArrayMemoryError: Unable to allocate 35.6 MiB for an array with shape (1524, 2040, 3) and data type float32
[[{{node PyFunc}}]]
[[IteratorGetNext]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. This isn't available when running in Eager mode.
0 successful operations.
0 derived errors ignored. [Op:__inference_train_function_752]
Function call stack:
train_function -> train_function
I brought down the batch size to 8 and the buffer_size to 5000 from 64 and 10000 respectively but still am facing this issue. The dataset is the DF2K dataset(~15Gb) and am using my personal computer with the GTX 1650 GPU.
Thank you for reading this and helping me :)

'Line2D' object has no property 'ylabel' error with pd.plot()

I am trying to plot using df.plot from the pandas plotting library, and was using the following code:
df_mean.plot(kind='line', subplots=True, layout=(1,8), figsize=(40,8),
sharey=True, ylabel = "Percent Change", title="Average movement")
I thought it might have something to do with using np.transpose() since it would convert it into a numpy array, but after conversion back to a pd.DataFrame(), the error still persists.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-269-85f6c80ca026> in <module>
1 df_mean = pd.DataFrame(df_mean)
2
----> 3 df_mean.plot(kind='line', subplots=True, layout=(1,8), figsize=(40,8),
4 title="Average movement",
5 sharey=True, ylabel = "Percent Change")
~\anaconda3\lib\site-packages\pandas\plotting\_core.py in __call__(self, *args,
**kwargs)
845 keyword_args = ", ".join(
846 f"{name}={repr(value)}" for (name, default), value in
zip(arg_def, args)
--> 847 )
848 msg = (
849 "`Series.plot()` should not be called with positional "
~\anaconda3\lib\site-packages\pandas\plotting\_matplotlib\__init__.py in plot(data,
kind, **kwargs)
59 kwargs["ax"] = getattr(ax, "left_ax", ax)
60 plot_obj = PLOT_CLASSES[kind](data, **kwargs)
---> 61 plot_obj.generate()
62 plot_obj.draw()
63 return plot_obj.result
~\anaconda3\lib\site-packages\pandas\plotting\_matplotlib\core.py in generate(self)
261 else:
262 return self.data.shape[1]
--> 263
264 def draw(self):
265 self.plt.draw_if_interactive()
~\anaconda3\lib\site-packages\pandas\plotting\_matplotlib\core.py in
_make_plot(self)
1075 self.data = self.data.fillna(value=0)
1076 self.x_compat = plot_params["x_compat"]
-> 1077 if "x_compat" in self.kwds:
1078 self.x_compat = bool(self.kwds.pop("x_compat"))
1079
~\anaconda3\lib\site-packages\pandas\plotting\_matplotlib\core.py in _plot(cls, ax,
x, y, style, column_num, stacking_id, **kwds)
1102
1103 stacking_id = self._get_stacking_id()
-> 1104 is_errorbar = com.any_not_none(*self.errors.values())
1105
1106 colors = self._get_colors()
~\anaconda3\lib\site-packages\pandas\plotting\_matplotlib\converter.py in
wrapper(*args, **kwargs)
64 with pandas_converters():
65 return func(*args, **kwargs)
---> 66
67 return wrapper
68
~\anaconda3\lib\site-packages\pandas\plotting\_matplotlib\core.py in _plot(cls, ax,
x, y, style, is_errorbar, **kwds)
654
655 if is_errorbar:
--> 656 if "xerr" in kwds:
657 kwds["xerr"] = np.array(kwds.get("xerr"))
658 if "yerr" in kwds:
~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex,
scaley, data, *args, **kwargs)
1741
1742 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1743 lines = [*self._get_lines(*args, data=data, **kwargs)]
1744 for line in lines:
1745 self.add_line(line)
~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in __call__(self, data,
*args, **kwargs)
271 this += args[0],
272 args = args[1:]
--> 273 yield from self._plot_args(this, kwargs)
274
275 def get_next_color(self):
~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup,
kwargs)
416 if ncx > 1 and ncy > 1 and ncx != ncy:
417 raise ValueError(f"x has {ncx} columns but y has {ncy}
columns")
--> 418 return [func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
419 for j in range(max(ncx, ncy))]
420
~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in <listcomp>(.0)
416 if ncx > 1 and ncy > 1 and ncx != ncy:
417 raise ValueError(f"x has {ncx} columns but y has {ncy}
columns")
--> 418 return [func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
419 for j in range(max(ncx, ncy))]
420
~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in _makeline(self, x, y,
kw, kwargs)
310 default_dict = self._getdefaults(set(), kw)
311 self._setdefaults(default_dict, kw)
--> 312 seg = mlines.Line2D(x, y, **kw)
313 return seg
314
~\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)
388 # update kwargs before updating data to give the caller a
389 # chance to init axes (and hence unit support)
--> 390 self.update(kwargs)
391 self.pickradius = pickradius
392 self.ind_offset = 0
~\anaconda3\lib\site-packages\matplotlib\artist.py in update(self, props)
994 func = getattr(self, f"set_{k}", None)
995 if not callable(func):
--> 996 raise AttributeError(f"{type(self).__name__!r}
object "
997 f"has no property {k!r}")
998 ret.append(func(v))
AttributeError: 'Line2D' object has no property 'ylabel'
I was able to run this code fine on my mac, but when I transferred it over to my desktop, I get this error, and I'm not sure why. I thought it could be a version problem, but I updated pandas and it didn't fix anything.
Anybody have an idea what could be causing something like this?
You can try this trick:
If the ylabel parameter is the problem, remove it and set it directly to ax.
ax = df_mean.plot(kind='line', subplots=True, layout=(1,8), figsize=(40,8),
sharey=True, title="Average movement")
ax.set_ylabel('Percent Change')
plt.show()

AttributeError: /home/hp/anaconda3/lib/libxgboost.so: undefined symbol: XGDMatrixSetDenseInfo

I have installed XGBoost with pip3.
While trying to run this line:
clf = GridSearchCV(estimator=xgb.XGBClassifier(use_label_encoder =False), param_grid=params, scoring = 'accuracy', cv=20).fit(data_train, label_train)
I get this error :
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-90-718a4a11a2ba> in <module>
4 startTime = time.time()
5
----> 6 clf = GridSearchCV(estimator=xgb.XGBClassifier(use_label_encoder =False), param_grid=params, scoring = 'accuracy', cv=20).fit(data_train, label_train)
7 print(clf.best_estimator_)
8 print('--------------------------------------------------')
~/anaconda3/lib/python3.8/site-packages/sklearn/utils/validation.py in inner_f(*args, **kwargs)
61 extra_args = len(args) - len(all_args)
62 if extra_args <= 0:
---> 63 return f(*args, **kwargs)
64
65 # extra_args > 0
~/anaconda3/lib/python3.8/site-packages/sklearn/model_selection/_search.py in fit(self, X, y, groups, **fit_params)
878 refit_start_time = time.time()
879 if y is not None:
--> 880 self.best_estimator_.fit(X, y, **fit_params)
881 else:
882 self.best_estimator_.fit(X, **fit_params)
~/anaconda3/lib/python3.8/site-packages/xgboost/core.py in inner_f(*args, **kwargs)
420 for k, arg in zip(sig.parameters, args):
421 kwargs[k] = arg
--> 422 return f(**kwargs)
423
424 return inner_f
~/anaconda3/lib/python3.8/site-packages/xgboost/sklearn.py in fit(self, X, y, sample_weight, base_margin, eval_set, eval_metric, early_stopping_rounds, verbose, xgb_model, sample_weight_eval_set, feature_weights, callbacks)
901 self.n_features_in_ = self._features_count
902
--> 903 train_dmatrix, evals = self._wrap_evaluation_matrices(
904 X, y, group=None, sample_weight=sample_weight, base_margin=base_margin,
905 feature_weights=feature_weights,
~/anaconda3/lib/python3.8/site-packages/xgboost/sklearn.py in _wrap_evaluation_matrices(self, X, y, group, sample_weight, base_margin, feature_weights, eval_set, sample_weight_eval_set, eval_group, label_transform)
263
264 y = label_transform(y)
--> 265 train_dmatrix = DMatrix(data=X, label=y, weight=sample_weight,
266 base_margin=base_margin,
267 missing=self.missing, nthread=self.n_jobs)
~/anaconda3/lib/python3.8/site-packages/xgboost/core.py in __init__(self, data, label, weight, base_margin, missing, silent, feature_names, feature_types, nthread, enable_categorical)
507 self.handle = handle
508
--> 509 self.set_info(label=label, weight=weight, base_margin=base_margin)
510
511 self.feature_names = feature_names
~/anaconda3/lib/python3.8/site-packages/xgboost/core.py in inner_f(*args, **kwargs)
420 for k, arg in zip(sig.parameters, args):
421 kwargs[k] = arg
--> 422 return f(**kwargs)
423
424 return inner_f
~/anaconda3/lib/python3.8/site-packages/xgboost/core.py in set_info(self, label, weight, base_margin, group, label_lower_bound, label_upper_bound, feature_names, feature_types, feature_weights)
528 '''Set meta info for DMatrix.'''
529 if label is not None:
--> 530 self.set_label(label)
531 if weight is not None:
532 self.set_weight(weight)
~/anaconda3/lib/python3.8/site-packages/xgboost/core.py in set_label(self, label)
657 """
658 from .data import dispatch_meta_backend
--> 659 dispatch_meta_backend(self, label, 'label', 'float')
660
661 def set_weight(self, weight):
~/anaconda3/lib/python3.8/site-packages/xgboost/data.py in dispatch_meta_backend(matrix, data, name, dtype)
674 data = data.values.astype('float')
675 assert len(data.shape) == 1 or data.shape[1] == 0 or data.shape[1] == 1
--> 676 _meta_from_numpy(data, name, dtype, handle)
677 return
678 if _is_dlpack(data):
~/anaconda3/lib/python3.8/site-packages/xgboost/data.py in _meta_from_numpy(data, field, dtype, handle)
598 ptr = interface['data'][0]
599 ptr = ctypes.c_void_p(ptr)
--> 600 _check_call(_LIB.XGDMatrixSetDenseInfo(
601 handle,
602 c_str(field),
~/anaconda3/lib/python3.8/ctypes/__init__.py in __getattr__(self, name)
392 if name.startswith('__') and name.endswith('__'):
393 raise AttributeError(name)
--> 394 func = self.__getitem__(name)
395 setattr(self, name, func)
396 return func
~/anaconda3/lib/python3.8/ctypes/__init__.py in __getitem__(self, name_or_ordinal)
397
398 def __getitem__(self, name_or_ordinal):
--> 399 func = self._FuncPtr((name_or_ordinal, self))
400 if not isinstance(name_or_ordinal, int):
401 func.__name__ = name_or_ordinal
AttributeError: /home/hp/anaconda3/lib/libxgboost.so: undefined symbol: XGDMatrixSetDenseInfo

how to run auto.arima using rpy2

I want to call R's auto.arima function from Python. I think i have not yet fully understood this interface. Can someone help me here - to send a time series obj to R, call forecast related functions and get back the results?
This is what I have done so far:
from rpy2.robjects import r
from rpy2.robjects import pandas2ri
#create a python time series
count = range(1, 51)
df['count'] = count
df['date'] = pd.date_range('2016-01-01', '2016-02-19')
df.set_index('date', inlace = True)
df.sort_index(inplace = True)
pandas2ri.activate()
r_timeseries = pandas2ri.py2ri(df)
r('fit <- auto.arima(r_timeseries)')
I think I have to import some R packages (like forecast). Not sure how to go about doing that in Python, properly pass the python time series object to R etc.
In [63]: r_ts = pandas2ri.py2ri(df)
In [64]: r_ts
Out[64]:
<DataFrame - Python:0x1126a93f8 / R:0x7ff7bfa51bc8>
[IntVector]
X0: <class 'rpy2.robjects.vectors.IntVector'>
<IntVector - Python:0x1126a96c8 / R:0x7ff7be1af1c0>
[ 1, 2, 3, ..., 48, 49, 50]
And, when I attempt to call forecast
In [83]: x = r('forecast(r_ts)')
/Library/Python/2.7/site-packages/rpy2/robjects/functions.py:106: UserWarning: Error in forecast(r_ts) : object 'r_ts' not found
res = super(Function, self).__call__(*new_args, **new_kwargs)
---------------------------------------------------------------------------
RRuntimeError Traceback (most recent call last)
<ipython-input-83-0765ffc30741> in <module>()
----> 1 x = r('forecast(r_ts)')
/Library/Python/2.7/site-packages/rpy2/robjects/__init__.pyc in __call__(self, string)
319 def __call__(self, string):
320 p = _rparse(text=StrSexpVector((string,)))
--> 321 res = self.eval(p)
322 return conversion.ri2py(res)
323
/Library/Python/2.7/site-packages/rpy2/robjects/functions.pyc in __call__(self, *args, **kwargs)
176 v = kwargs.pop(k)
177 kwargs[r_k] = v
--> 178 return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
179
180 pattern_link = re.compile(r'\\link\{(.+?)\}')
/Library/Python/2.7/site-packages/rpy2/robjects/functions.pyc in __call__(self, *args, **kwargs)
104 for k, v in kwargs.items():
105 new_kwargs[k] = conversion.py2ri(v)
--> 106 res = super(Function, self).__call__(*new_args, **new_kwargs)
107 res = conversion.ri2ro(res)
108 return res
RRuntimeError: Error in forecast(r_ts) : object 'r_ts' not found
I tried the following as well:
In [99]: f = r('forecast.auto.arima(r_ts)')
---------------------------------------------------------------------------
RRuntimeError Traceback (most recent call last)
<ipython-input-99-1c4610d2740d> in <module>()
----> 1 f = r('forecast.auto.arima(r_ts)')
/Library/Python/2.7/site-packages/rpy2/robjects/__init__.pyc in __call__(self, string)
319 def __call__(self, string):
320 p = _rparse(text=StrSexpVector((string,)))
--> 321 res = self.eval(p)
322 return conversion.ri2py(res)
323
/Library/Python/2.7/site-packages/rpy2/robjects/functions.pyc in __call__(self, *args, **kwargs)
176 v = kwargs.pop(k)
177 kwargs[r_k] = v
--> 178 return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
179
180 pattern_link = re.compile(r'\\link\{(.+?)\}')
/Library/Python/2.7/site-packages/rpy2/robjects/functions.pyc in __call__(self, *args, **kwargs)
104 for k, v in kwargs.items():
105 new_kwargs[k] = conversion.py2ri(v)
--> 106 res = super(Function, self).__call__(*new_args, **new_kwargs)
107 res = conversion.ri2ro(res)
108 return res
RRuntimeError: Error in eval(expr, envir, enclos) :
could not find function "forecast.auto.arima"
you could try what I do
import rpy2.robjects as ro
from rpy2.robjects import pandas2ri
pandas2ri.activate()
ro.r('library(forecast)')
rdf = pandas2ri.py2ri(df)
ro.globalenv['r_timeseries'] = rdf
pred = ro.r('as.data.frame(forecast(auto.arima(r_timeseries),h=5))')
this way, you can handle pred as a data frame like this
Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
51 51 51 51 51 51
52 52 52 52 52 52
53 53 53 53 53 53
54 54 54 54 54 54
55 55 55 55 55 55
In the first attempt you are telling R to use a variable r_ts that it does not now much about (the name r_ts is defined in your Python namespace), and in the second attempt you are added to this a function name R does not know anything about. Both error message are precisely reporting this as a problem.
Your first attempt could be rewritten as:
x = r('forecast')(r_ts)

Resources