ValueError: assignment destination is read-only [Solved]

avatar

Last updated: Apr 11, 2024 Reading time · 2 min

banner

# ValueError: assignment destination is read-only [Solved]

The NumPy "ValueError: assignment destination is read-only" occurs when you try to assign a value to a read-only array.

To solve the error, create a copy of the read-only array and modify the copy.

You can use the flags attribute to check if the array is WRITABLE .

Running the code sample produces the following output:

check if writeable

In your case, WRITEABLE will likely be set to False .

In older NumPy versions, you used to be able to set the flag to true by calling the setflags() method.

However, setting the WRITEABLE flag to True ( 1 ) will likely fail if the OWNDATA flag is set to False .

You will likely get the following error:

  • "ValueError: cannot set WRITEABLE flag to True of this array"

To solve the error, create a copy of the array when converting it from a Pillow Image to a NumPy array.

Passing the Pillow Image to the numpy.array() method creates a copy of the array.

You can also explicitly call the copy() method.

check if writable is set to true

You can also call the copy() method on the Pillow Image and modify the copy.

The image copy isn't read-only and allows assignment.

You can change the img_copy variable without getting the "assignment destination is read-only" error.

You can also use the numpy.copy() method.

The numpy.copy() method returns an array copy of the given object.

The only argument we passed to the method is the image.

You can safely modify the img_copy variable without running into issues.

You most likely don't want to make changes to the original image.

Creating a copy and modifying the copy should be your preferred approach.

If you got the error when using the np.asarray() method, try changing it to np.array() .

Change the following:

To the following:

As long as the WRITEABLE flag is set to True , you will be able to modify the array.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • TypeError: Object of type ndarray is not JSON serializable
  • ValueError: numpy.ndarray size changed, may indicate binary incompatibility
  • NumPy RuntimeWarning: divide by zero encountered in log10
  • ValueError: x and y must have same first dimension, but have shapes

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

HatchJS Logo

HatchJS.com

Cracking the Shell of Mystery

ValueError: Assignment destination is read-only

Avatar

Have you ever tried to assign a value to a variable that was read-only? If so, you may have encountered a `ValueError` with the message `assignment destination is read-only`. This error occurs when you try to change the value of a variable that is either immutable or has been marked as read-only.

In this article, we’ll take a closer look at what `ValueError` is and what causes it. We’ll also discuss how to avoid this error in your own code.

What is `ValueError`?

A `ValueError` is a type of `Exception` that is raised when a value is invalid for a particular operation. In the case of `assignment destination is read-only`, the value that you are trying to assign to the variable is not compatible with the type of the variable.

For example, you cannot assign a string value to a variable that has been declared as an integer. This will cause a `ValueError` with the message `assignment destination is read-only`.

What causes `ValueError`?

There are a few different things that can cause a `ValueError`. Here are some of the most common causes:

  • Trying to assign a value to a variable that is immutable. Immutable variables cannot be changed once they have been created. This includes variables that are declared as `int`, `float`, `bool`, or `tuple`.
  • Trying to assign a value to a variable that has been marked as read-only. You can mark a variable as read-only by using the `@property` decorator. This prevents the value of the variable from being changed directly.
  • Trying to assign a value to a variable that does not exist. If you try to assign a value to a variable that does not exist, a `ValueError` will be raised.

How to avoid `ValueError`

To avoid `ValueError`, you should make sure that you are not trying to assign an invalid value to a variable. Here are some tips:

  • Check the type of the variable before assigning a value to it. If the variable is immutable, you will not be able to change its value.
  • Use the `@property` decorator to mark variables as read-only. This will prevent other parts of your code from accidentally changing the value of the variable.
  • Check to make sure that the variable exists before assigning a value to it. If the variable does not exist, a `ValueError` will be raised.

By following these tips, you can help to avoid `ValueError` in your code.

| Column 1 | Column 2 | Column 3 | |—|—|—| | Error message | `ValueError: assignment destination is read-only` | `This error occurs when you try to assign a value to a variable that is read-only.` | | Causes | * Trying to assign a value to a constant.

  • Trying to assign a value to a property that is read-only.
  • Trying to assign a value to a variable that is already assigned to a value. |

| Solutions | * Use a different variable name.

  • Use the `readonly` attribute to make the variable read-only.
  • Use the `setter` method to assign a value to a property that is read-only. |

In this tutorial, we will discuss the ValueError exception in Python. We will cover what a ValueError is, what the error message “assignment destination is read-only” means, and how to fix this error.

What is a ValueError?

A ValueError is a Python exception that occurs when a value is passed to a function that is not of the correct type or format. For example, trying to assign a string to a variable that is expecting an integer would raise a ValueError.

The error message for a ValueError typically includes the name of the function that raised the error, as well as the value that was passed to the function that caused the error.

>>> a = ‘123’ >>> b = int(a) Traceback (most recent call last): File “ “, line 1, in ValueError: invalid literal for int() with base 10: ‘123’

In this example, we tried to assign the string “123” to the variable `b`, which is expecting an integer. This caused a ValueError to be raised.

What does “assignment destination is read-only” mean?

When you get a ValueError with the message “assignment destination is read-only”, it means that you are trying to assign a value to a variable that is not writable. This can happen for a number of reasons, such as:

  • The variable is defined as a constant.
  • The variable is read-only by default.
  • The variable is being used as a keyword argument in a function call.

The variable is defined as a constant

One common reason for getting a ValueError with the message “assignment destination is read-only” is that the variable is defined as a constant. A constant is a variable that cannot be changed after it has been assigned a value.

To define a variable as a constant, you can use the `const` keyword. For example:

const a = 10

Once a variable has been defined as a constant, you cannot assign a new value to it. If you try to do so, you will get a ValueError with the message “assignment destination is read-only”.

The variable is read-only by default

Some variables are read-only by default. This means that they cannot be assigned a new value after they have been created.

One example of a read-only variable is the `sys.argv` variable. The `sys.argv` variable contains a list of the command-line arguments that were passed to the Python interpreter when the program was started. This variable is read-only because it cannot be changed after the program has been started.

If you try to assign a new value to the `sys.argv` variable, you will get a ValueError with the message “assignment destination is read-only”.

The variable is being used as a keyword argument in a function call

Another common reason for getting a ValueError with the message “assignment destination is read-only” is that the variable is being used as a keyword argument in a function call.

When you use a keyword argument in a function call, the value of the argument is assigned to the corresponding keyword argument in the function definition. This means that the value of the argument is not actually assigned to the variable that you used in the function call.

For example, the following code will not raise a ValueError:

def f(a, b): print(a, b)

In this code, the value of the `a` argument is assigned to the `a` keyword argument in the `f()` function definition. This means that the value of the `a` argument is not actually assigned to the variable `a` that was used in the function call.

However, the following code will raise a ValueError:

def f(a, b): a = b

In this code, the value of the `b` argument is assigned to the `a` variable. This means that the value of the `b` argument is actually assigned to the variable `a` that was used in the function call. This will cause a ValueError to be raised because the `a` variable is read-only.

How to fix the “assignment destination is read-only” error

There are a few ways to fix the “assignment destination is read-only” error.

Change the variable to a mutable type

If the variable is defined as a constant, you can change it to a mutable type. A mutable type is a type of variable that can be changed after it has been

How to fix a ValueError with the message “assignment destination is read-only”

A ValueError with the message “assignment destination is read-only” occurs when you try to assign a value to a variable that is read-only. This can happen for a few reasons:

  • The variable may be defined as a constant.
  • The variable may be a property of an object that is read-only.
  • The variable may be a member of a tuple or a list.

To fix this error, you need to make sure that the variable is not read-only. Here are a few ways to do this:

Make sure that the variable is not defined as a constant

If the variable is defined as a constant, you cannot assign a new value to it. To fix this, you can either remove the `const` keyword from the definition of the variable, or you can use a different variable name.

For example, the following code will raise a ValueError:

python const_value = 10 const_value = 20

To fix this, you can remove the `const` keyword from the definition of `const_value`:

python value = 10 value = 20

Or, you can use a different variable name:

python value = 10 new_value = 20

Make sure that the variable is not read-only by default

Some variables are read-only by default. For example, the `__init__` method of a class is read-only by default. This means that you cannot assign a new value to the `__init__` method.

To fix this, you can either make the variable mutable, or you can use a keyword argument to pass the value to the method.

python class MyClass: def __init__(self, value): self.value = value

my_class = MyClass(10) my_class.value = 20

To fix this, you can make the `value` attribute mutable:

def set_value(self, value): self.value = value

my_class = MyClass(10) my_class.set_value(20)

Or, you can use a keyword argument to pass the value to the `__init__` method:

my_class = MyClass(value=10) my_class.value = 20

Use a mutable object instead of an immutable object

If the variable is an immutable object, you cannot assign a new value to it. For example, the following code will raise a ValueError:

python my_list = [1, 2, 3] my_list[0] = 10

To fix this, you can use a mutable object instead of an immutable object. For example, you can use a list instead of a tuple:

Use a keyword argument instead of a positional argument

If you are passing a value to a function as a positional argument, and the function is expecting a keyword argument, you will get a ValueError with the message “assignment destination is read-only”.

python def my_function(value): value = 10

my_function(10)

To fix this, you can use a keyword argument instead of a positional argument:

my_function(value=10)

A ValueError with the message “assignment destination is read-only” can be a frustrating error to deal with, but it is usually easy to fix. By following the steps in this outline, you should be able to resolve this error and get your code working properly.

Question 1: What is a ValueError?

Answer: A ValueError is a Python exception that is raised when a value is not valid for the operation being performed. For example, trying to assign a string to a variable that is expecting an integer would raise a ValueError.

Question 2: What does the error message “ValueError: assignment destination is read-only” mean?

Answer: This error message means that you are trying to assign a value to a variable that is read-only. This can happen for a few reasons. First, the variable may be defined as read-only using the `readonly` keyword. Second, the variable may be a property of an object that is read-only. Third, the variable may be a global variable that is defined in a module that is being imported with the `readonly` flag.

Question 3: How can I fix the error “ValueError: assignment destination is read-only”?

Answer: There are a few ways to fix this error. First, you can check to make sure that the variable is not defined as read-only. Second, you can check to make sure that the variable is not a property of an object that is read-only. Third, you can check to make sure that the variable is not a global variable that is being imported with the `readonly` flag.

Question 4: What are some common causes of the error “ValueError: assignment destination is read-only”?

Answer: Some common causes of this error include:

  • Trying to assign a value to a variable that is defined as read-only.
  • Trying to assign a value to a property of an object that is read-only.
  • Trying to assign a value to a global variable that is being imported with the `readonly` flag.

Question 5: How can I prevent the error “ValueError: assignment destination is read-only” from happening in the future?

Answer: There are a few things you can do to prevent this error from happening in the future. First, you can be careful not to define variables as read-only. Second, you can be careful not to assign values to properties of objects that are read-only. Third, you can be careful not to import global variables with the `readonly` flag.

In this blog post, we discussed the ValueError: assignment destination is read-only error. We first explained what the error means and then provided several common causes of the error. We then discussed how to fix the error in each of the cases we presented. Finally, we provided some tips for avoiding the error in the future.

We hope that this blog post has been helpful in understanding the ValueError: assignment destination is read-only error. If you have any other questions about the error, please feel free to leave a comment below.

Author Profile

Marcus Greenwood

Latest entries

  • December 26, 2023 Error Fixing User: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
  • December 26, 2023 How To Guides Valid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
  • December 26, 2023 Error Fixing How to Fix the The Root Filesystem Requires a Manual fsck Error
  • December 26, 2023 Troubleshooting How to Fix the `sed unterminated s` Command

Similar Posts

How to fix error: failed building wheel for aiohttp.

Have you ever encountered the error “failed building wheel for aiohttp”? If so, you’re not alone. This is a common error that can occur when you’re trying to install aiohttp, a Python library for asynchronous HTTP requests. In this article, we’ll take a look at what causes this error and how you can fix it….

ValueError: Object too deep for desired array: How to fix this error

ValueError: Object Too Deep for Desired Array Have you ever tried to use a list comprehension to create a new list from an existing list, but you got an error message like “ValueError: object too deep for desired array”? If so, you’re not alone. This error is a common one, and it can be tricky…

Troubleshooting TypeError: ClientMissingIntents: Valid intents must be provided for the client

Have you ever tried to use a new app or website, only to be met with an error message? If so, you’re not alone. Type errors are a common problem that can occur when there is a mismatch between the expected and actual data. In this article, we’ll take a closer look at one type…

AttributeError: HTMLParser object has no attribute unescape

AttributeError: HTMLParser object has no attribute unescape Have you ever encountered the following error message when trying to parse HTML code? AttributeError: HTMLParser object has no attribute unescape If so, you’re not alone. This is a common error that occurs when you try to use the `unescape()` method on an `HTMLParser` object. The `unescape()` method…

Powershell Not in List: How to Fix This Error

PowerShell Not in List: What It Means and How to Fix It If you’re a PowerShell user, you may have encountered the error message “PowerShell not in list.” This error can occur for a variety of reasons, but it typically means that PowerShell is not installed on your system or that it is not configured…

AttributeError: module ‘enum’ has no attribute ‘IntFlag’

AttributeError: module enum has no attribute intflag This error occurs when you try to access the `intflag` attribute of the `enum` module. This attribute does not exist, so the Python interpreter raises an `AttributeError`. There are a few possible causes of this error. One possibility is that you are using an outdated version of the…

Valueerror assignment destination is read-only

One of the errors that developers often come across is the ValueError: assignment destination is read-only .

This error typically occurs when you try to modify a read-only object or variable.

What does the ValueError: assignment destination is read-only error mean?

How the error occurs.

Example 1: Modifying an Immutable Tuple

However, in Python, constants are typically immutable and cannot be modified once defined.

Therefore, this code will likely raise a valueerror .

Example 4: Altering an Immutable Data Structure

The code then changes the value associated with the ‘key’ to ‘ new_value ‘ by assigning it directly using indexing.

Solutions for ValueError: assignment destination is read-only

Solution 1: use mutable data structures.

Instead of using immutable data structures like tuples or strings, switch to mutable ones such as lists or dictionaries.

For example:

Solution 2: Reassign Variables

Solution 3: check documentation and restrictions.

It’s important to consult the documentation or source code to understand any restrictions required.

Solution 4: Use a Copy or Clone

If the object you’re working with is meant to be read-only, consider creating a copy or clone of it.

Solution 5: Identify Context-Specific Solutions

Understanding the possible cause will aid in finding a proper resolution.

Solution 6: Seek Help from the Community

Online forums, developer communities, and platforms like Stack Overflow can provide valuable insights and guidance from experienced programmers.

Frequently Asked Questions

To resolve this valueerror, you can apply different solutions such as using mutable data structures, reassigning variables, checking documentation and restrictions, using copies or clones, identifying context-specific solutions, or seeking help from the programming community.

Yes, there are similar errors that you may encounter in different programming languages. For example, in JavaScript, you might encounter the error TypeError: Assignment to a constant variable when trying to modify a constant.

By following the solutions provided in this article, such as using mutable data structures, reassigning variables, checking restrictions, making copies or clones, considering context-specific solutions, and seeking community help, you can effectively resolve this error.

Additional Resources

Leave a comment cancel reply.

System error: assignment destination is read-only

  • High: It blocks me to complete my task.

I would like to ask about an issue that I encountered when I try to distribute my work on multiple cpu nodes using ray.

My input file is a simulation file consisting of multiple time frames, so I would like to distribute the calculation of one frame to one task. It works fine when I just used pool from the multiprocessing python library, where only one node (128 tasks in total) can be used. Since I have more than 2,000 time frames, I would like to use multiple nodes in this calculation, and the multiprocessing python library isn’t the best choice.

I created my code using this template: ray/simple-trainer.py at master · ray-project/ray · GitHub . Here’s a brief summary of my code:

import socket import sys import time import ray

@ray.remote def hydration_water_calculation2(t, u): # in one frame return xyz

ray.init(address=os.environ[“ip_head”])

print(“Nodes in the Ray cluster:”) print(ray.nodes())

for i in frame_values: ip_addresses = ray.get([hydration_water_calculation2.remote(i, u0) for _ in range(1)]) print(Counter(ip_addresses))

But I got the following error: Traceback (most recent call last): File “…/…/hydration_whole_global2_ray.py”, line 269, in ip_addresses = ray.get([hydration_water_calculation2.remote(i, u0) for _ in range(1)]) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/_private/client_mode_hook.py”, line 105, in wrapper return func(*args, **kwargs) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/worker.py”, line 1809, in get raise value.as_instanceof_cause() ray.exceptions.RayTaskError: ray::hydration_water_calculation2() (pid=27283, ip=10.8.9.236) At least one of the input arguments for this task could not be computed: ray.exceptions.RaySystemError: System error: assignment destination is read-only traceback: Traceback (most recent call last): File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 332, in deserialize_objects obj = self._deserialize_object(data, metadata, object_ref) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 235, in _deserialize_object return self._deserialize_msgpack_data(data, metadata_fields) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 190, in _deserialize_msgpack_data python_objects = self._deserialize_pickle5_data(pickle5_data) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 178, in _deserialize_pickle5_data obj = pickle.loads(in_band, buffers=buffers) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 2106, in setstate self[self.ts.frame] File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 1610, in getitem return self._read_frame_with_aux(frame) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 1642, in _read_frame_with_aux ts = self._read_frame(frame) # pylint: disable=assignment-from-no-return File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XDR.py”, line 255, in _read_frame timestep = self._read_next_timestep() File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XDR.py”, line 273, in _read_next_timestep self._frame_to_ts(frame, ts) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XTC.py”, line 144, in _frame_to_ts ts.dimensions = triclinic_box(*frame.box) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 810, in dimensions self._unitcell[:] = box ValueError: assignment destination is read-only (hydration_water_calculation2 pid=27283) 2022-05-01 22:53:55,714 ERROR serialization.py:334 – assignment destination is read-only (hydration_water_calculation2 pid=27283) Traceback (most recent call last): (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 332, in deserialize_objects (hydration_water_calculation2 pid=27283) obj = self._deserialize_object(data, metadata, object_ref) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 235, in _deserialize_object (hydration_water_calculation2 pid=27283) return self._deserialize_msgpack_data(data, metadata_fields) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 190, in _deserialize_msgpack_data (hydration_water_calculation2 pid=27283) python_objects = self._deserialize_pickle5_data(pickle5_data) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/ray/serialization.py”, line 178, in _deserialize_pickle5_data (hydration_water_calculation2 pid=27283) obj = pickle.loads(in_band, buffers=buffers) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 2106, in setstate (hydration_water_calculation2 pid=27283) self[self.ts.frame] (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 1610, in getitem (hydration_water_calculation2 pid=27283) return self._read_frame_with_aux(frame) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 1642, in _read_frame_with_aux (hydration_water_calculation2 pid=27283) ts = self._read_frame(frame) # pylint: disable=assignment-from-no-return (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XDR.py”, line 255, in _read_frame (hydration_water_calculation2 pid=27283) timestep = self._read_next_timestep() (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XDR.py”, line 273, in _read_next_timestep (hydration_water_calculation2 pid=27283) self._frame_to_ts(frame, ts) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/XTC.py”, line 144, in _frame_to_ts (hydration_water_calculation2 pid=27283) ts.dimensions = triclinic_box(*frame.box) (hydration_water_calculation2 pid=27283) File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 810, in dimensions (hydration_water_calculation2 pid=27283) self._unitcell[:] = box (hydration_water_calculation2 pid=27283) ValueError: assignment destination is read-only

Could anyone help me diagnose the issue? I’m new to ray and still learning why I was getting the “assignment destination is read-only” error. Many thanks in advance!

Hey @Chengeng-Yang , the read-only errors are happening because Ray stores arguments in the shared memory object store. This allows arguments to be shared with process very efficiently with zero memory copies, but has a side-effect of rendering numpy arrays immutable.

In this case, it seems that during setstate for your program an assignment is made that will update an existing array. Is it possible to modify the code around there to make a copy of the array prior to calling self._unitcell[:] = box ? I.e., self._unitcell = self._unitcell.copy(); self._unitcell[:] = box . That should fix the deserialization problem.

Reference stack line: File “/jet/home/chy20004/.conda/envs/ray/lib/python3.8/site-packages/MDAnalysis/coordinates/base.py”, line 2106, in setstate

Hi @ericl , many thanks for your help! Your suggestion DID work. The deserialization issue has been fixed after I made a copy of self._unitcell.

Thanks again and have a wonderful day :))

Related Topics

Topic Replies Views Activity
0 353 August 14, 2023
Ray Core 4 697 July 8, 2021
Ray Core 5 316 August 25, 2022
Ray Core 1 606 March 10, 2021
Ray Core 2 826 November 30, 2022

Scikit-learn: ValueError: assignment destination is read-only, when paralleling with n_jobs > 1

When I run SparseCoder with n_jobs > 1, there is a chance to raise exception ValueError: assignment destination is read-only . The code is shown as follow:

The bigger data_dims is, the higher chance get. When data_dims is small (lower than 2000, I verified), everything works fine. Once data_dims is bigger than 2000, there is a chance to get the exception. When data_dims is bigger than 5000, it is 100% raised.

My version infor:

OS: OS X 10.11.1 python: Python 2.7.10 |Anaconda 2.2.0 numpy: 1.10.1 sklearn: 0.17

The full error information is shown as follow

 picture

Most helpful comment

@coldfog @garciaev I don't know if it is still relevant for you, but I ran into the same problem using joblib without scikit-learn.

The reason is the max_nbytes parameter within the Parallel invocation of the Joblib-library when you set n_jobs>1, which is 1M by default. The definition of this parameter is: "Threshold on the size of arrays passed to the workers that triggers automated memory mapping in temp_folder". More details can be found here: https://joblib.readthedocs.io/en/latest/generated/joblib.Parallel.html#

So, once the arrays pass the size of 1M, joblib will throw the error "ValueError: assignment destination is read-only". In order to overcome this, the parameter has to be set higher, e.g. max_nbytes='50M'.

If you want a quick-fix, you can add max_nbytes='50M' to the file "sklearn/decomposition/dict_learning.py" at line 297 in the Parallel class initiation to increase the allowed size of temporary files.

 picture

All 23 comments

I am taking a look at this

vighneshbirodkar picture

Is it not related to #5481, which seems more generic?

lesteve picture

It is, but SparseEncoder is not an estimator

Not that it matters but SparseCoder is an estimator:

I guess the error wasn't detected in #4807 as it is raised only when using algorithm='omp' . It should be raised when testing read only data on OrthogonalMatchingPursuit though.

arthurmensch picture

Was there a resolution to this bug? I've run into something similar while doing n_jobs=-1 on RandomizedLogisticRegression, and didn't know whether I should open a new issue here. Here's the top of my stack:

Someone ran into the same exact problem on StackOverflow - ValueError: output array is read-only . Both provided solutions on SO are useless (the first one doesn't even bother solving the problem, and the second one is solving the problem by bypassing joblib completely).

alichaudry picture

@alichaudry I just commented on a similar issue here .

I confirm that there is an error and it is floating in nature.

sklearn.decomposition.SparseCoder(D, transform_algorithm = 'omp', n_jobs=64).transform(X)

if X.shape[0] > 4000 it fails with ValueError: assignment destination is read-only If X.shape[0] <100 it is ok.

OS: Linux 3.10.0-327.13.1.el7.x86_64 python: Python 2.7.5 numpy: 1.10.1 sklearn: 0.17

fkrasnov picture

Hi there, I'm running into the same problem, using MiniBatchDictionaryLearning with jobs>1. I see a lot of referencing to other issues, but was there ever a solution to this? Sorry in advance if a solution was mentioned and I missed it.

OS: OSX python: 3.5 numpy: 1.10.1 sklearn: 0.17

zaino picture

The problem is in modifying arrays in-place. @lesteve close as duplicate of #5481?

amueller picture

currently I am still dealing with this issue and it is nearly a year since. this is still an open issue.

wderekjones picture

If you have a solution, please contribute it, @williamdjones

jnothman picture

https://github.com/scikit-learn/scikit-learn/pull/4807 is probably the more advanced effort to address this.

agramfort picture

@williamdjones I was not suggesting that it's solved, but that it's an issue that is reported at a different place, and having multiple issues related to the same problem makes keeping track of it harder.

Not sure where to report this, or if it's related, but I get the ValueError: output array is read-only when using n_jobs > 1 with RandomizedLasso and other functions.

ghost picture

@JGH1000 NOT A SOLUTION, but I would try using a random forest for feature selection instead since it is stable and has working joblib functionality.

Thanks @williamdjones , I used several different methods but found that RandomizedLasso works best for couple of particular datasets. In any case, it works but a bit slow. Not a deal breaker.

@JGH1000 No problem. If you don't mind, I'm curious about the dimensionality of the datasets for which RLasso was useful versus those for which it was not.

@williamdjones it was a small sample size (40-50), high-dimension (40,000-50,000) dataset. I would not say that other methods were bad, but RLasso provided results/ranking that were much more consistent with several univariate tests + domain knowledge. I guess this might not be the 'right' features but I had more trust in this method. Shame to hear it will be removed from scikit.

The problem still seems to exist on 24 core Ubuntu processor for RLasso with n_jobs = -1 and sklearn 0.19.1

garciaev picture

Just to complement @lvermue answer. I did what he suggested, but instead inside sklearn/decomposition/dict_learning.py the Parallel class that is instantiated doesn't have the max_nbytes set. What worked for me was to increase the default max_nbytes inside sklearn/externals/joblib/parallel.py from "1M" to "10M" I think you can put more if needed.

chriys picture

And you can find max_nbytes at line 475 of file parallel.py

rishabhgarg7 picture

Related issues

StevenLOL picture

Determine how a param is being set as readonly

I have a class similar to the example below

I’m using this basic example to test the usage pattern where I store a numpy.ndarray once but keep both a numpy recarray and pandas Dataframe view of the same data to allow for different access patterns a viewing with panel without duplicating the large array in memory.

this example works as you can see from the example below

However I have this same basic pattern in a much larger class but when I try to assign a value to the main numpy array I get a ValueError: assignment destination is read-only . I have not declared any of the paramerters in param.Parameterized class as readonly or constant but continue to get this simple ValueError.

Is there a way to track down were the readonly designation is being applied via some other more detailed stack trace? I’m beyond frustrated with trying ot figure out why the main array is being assigned as readonly when I have made no such designation in my code.

I have found the source of my error. It appears this is an issue associated with reading numpy arrays from a buffer not with the parameters themselves.

Hopefully this helps someone avoid a couple of days of frustrating searching in the future.

If you read a numpy array in from a buffer and would like to manipulate the values across views add a .copy() to the end of the initial read so that the array is not set as read-only.

Just out of curiosity, did the error message ( ValueError: assignment ... ) have anything to do with Param itself?

No. I have been really impressed with param so I’m rewriting my old code into param.Parameterized classes to better document the purpose of the code and to take advantage of the visualization capabilities of panel. One of the features I was using in Jupyter as I get better at parm and panel was the with param.exceptions_summarized(): context manager.

I mistakenly thought this context manager would only summarize the param related exceptions since the code was previously working as non-param classes. The ValueError was the only thing being dumped out so I assumed it was a param related error. Once I removed the context manager and explored the full trace I found the numpy related issue. This more a gap in my understanding than a real issue with any one library.

Thanks for all the help. My 2022 resolution is to get all my code into param and panel related classes so I’m sure I will be pestering everyone with issues that may end up being more me than the libraries themselves. Merry Christmas!

:wink:

I believe exceptions_summarized was added to param purely to write the documentation, it’s useful to only print the error message of an instead long and boring exception traceback, exception that would stop the notebook execution. But in your code you should definitely not use it since it will skip exceptions. This context manager would be better off in a separate module dedicated to the docs.

solveForum

  • Search forums
  • Solveforum All topics

ValueError: assignment destination is read-only

  • Thread starter Grzesiu Holui
  • Start date Oct 9, 2022

Grzesiu Holui

  • Oct 9, 2022
SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others. Click to expand...

Recent Threads

Why is it okay for my .bashrc or .zshrc to be writable by my normal user.

  • Zach Huxford
  • Jun 26, 2023

SFTP user login details real-time filtering

  • Amal P Ramesh

get nat port forwarding IP address

Using docker does not give error with sudo but using ctr does on starting a container, what are some of the latest nike soccer shoes that have gained popularity among players and enthusiasts in recent years, can't change tcp/ipv4 settings on windows 10.

exception has occurred valueerror assignment destination is read only

Customer service access 2007 template

  • tintincutes

Latest posts

  • Latest: Ashish Sharma
  • 18 minutes ago
  • Latest: AJ J
  • Latest: Siti Mardiah
  • Latest: A.nechi
  • Latest: Maris

Newest Members

vishvasoilmaker

极客教程 - 以工匠精神打磨精品教程

  • JavaScript 参考手册
  • Spring Boot
  • Spark Streaming
  • scikit-learn

Numpy中赋值目标为只读的错误 – 广播

在本文中,我们将介绍Numpy中的一个常见错误:“assignment destination is read-only”,它通常与广播有关。

阅读更多: Numpy 教程

Numpy中的广播是一种机制,它使得不同形状的数组在执行操作时具有相同的形状。例如,我们可以将一个标量(1维数组)加到一个矩阵(2维数组)中的每个元素,而无需将标量扩展为具有与矩阵相同的形状。将标量添加到矩阵的每个元素通常称为“标量广播”。

下面是标量广播的一个简单示例:

在这个示例中,我们把一个标量(b)加到一个矩阵(a)中。

但是,当我们尝试在广播期间复制值时,会出现“赋值目标是只读的”错误。让我们来看一个示例:

在这个示例中,我们将一个1维数组(b)分配给2维数组(a)中的一列。但是,当我们尝试进行此操作时,会出现“assignment destination is read-only”的错误。

这是因为我们尝试向只读的内存位置复制数据。在这个例子中,a的第一列被广播为与b相同的形状(2行1列,即2维数组),因此它变成只读的。

要解决这个问题,我们可以将代码稍微修改一下,使它在分配前将a复制到一个新的数组中:

在这个示例中,我们将a复制到c中,然后使用c来分配b的值,避免了“赋值目标是只读的”错误。

在Numpy中,广播是一种强大的机制,它使得不同形状的数组能够执行相同的操作。然而,在广播期间,我们需要注意将数据复制到新的数组中,以避免“赋值目标是只读的”错误。 Numpy中广播和标量广播的使用,可以更好的帮助我们编写高效、简洁的代码。

Python 教程

wxPython 教程

SymPy 教程

Matplotlib 教程

Web2py 教程

BeautifulSoup 教程

Java 教程

AngularJS 教程

TypeScript 教程

TypeScript 教程

WordPress 教程

WordPress 教程

Laravel 教程

PhantomJS 教程

Three.js 教程

Three.js 教程

Underscore.JS 教程

Underscore.JS 教程

WebGL 教程

PostgreSQL 教程

SQLite 教程

  • NumPy Ndarray 对象
  • NumPy 数组创建例程
  • NumPy 从现有数据创建数组
  • NumPy 数值范围的数组
  • NumPy 索引和切片
  • NumPy 数组操作 numpy.reshape
  • NumPy 数组操作 numpy.ndarray.flat
  • NumPy 数组操作 numpy.ndarray.flatten
  • NumPy 数组操作 numpy.ravel
  • NumPy 数组操作 numpy.transpose
  • NumPy 数组操作 numpy.ndarray.T
  • NumPy 数组操作 numpy.rollaxis
  • NumPy 数组操作 numpy.swapaxes
  • NumPy 数组操作 numpy.broadcast
  • NumPy 数组操作 numpy.broadcast_to
  • NumPy 数组操作 numpy.expand_dims
  • NumPy 数组操作 numpy.squeeze
  • NumPy 数组操作 numpy.concatenate
  • NumPy 数组操作 numpy.stack
  • NumPy 数组操作 numpy.hstack
  • NumPy 数组操作 numpy.vstack
  • NumPy 数组操作 numpy.split
  • NumPy 数组操作 numpy.hsplit
  • NumPy 数组操作 numpy.vsplit
  • NumPy 数组操作 numpy.resize
  • NumPy 数组操作 numpy.append
  • NumPy 数组操作 numpy.insert
  • NumPy 数组操作 numpy.delete
  • NumPy 数组操作 numpy.unique
  • NumPy 二进制运算符
  • NumPy 二进制位与运算符
  • NumPy 二进制位或运算符
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Error in Joblib Parallelisation Python : assignment destination is read-only

I am getting below error(found this in debug) while doing parallelisation using Joblib in Python.Please share the pointers for root cause and what should I do or tryout to remove this error

  • parallel-processing
  • python-multiprocessing

Sarvendra Singh's user avatar

Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .

Your answer.

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Browse other questions tagged python python-3.x parallel-processing python-multiprocessing joblib or ask your own question .

  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Announcing a change to the data-dump process

Hot Network Questions

  • How can DC charge a capacitor?
  • What are examples of moral principles in religions that secular ethical systems find hard to accept or justify and why?
  • Why are the Founders in Star Trek: Deep Space Nine considered so powerful?
  • IQ test puzzle with diagonal line of clocks
  • User does not have access to sudo on Debian 12 unless the system is rebooted
  • Help using DAC to control DC-DC Buck converter
  • parallelStream with collect method()
  • Why do repeating 8's show up more often in these decimals of square roots?
  • Why have SIGPIPE when EPIPE exists?
  • Why do tip vortices seem to 'bend' inwards at the tip of a plane wing?
  • Is expired sushi rice still good
  • Is "Non-Trivial amount of work" a correct phrase?
  • The 'correct' way to draw a diagram
  • How 'Aristotelian' is Rawls' 'Aristotelian principle'?
  • Glowing eyes facilitate control over other beings
  • How should I acknowledge a reviewer who left a negative review?
  • ORCA 6 slower than ORCA 5?
  • Automata reaching the same state when reading the same word long enough
  • Why is the E in 'collega' long?
  • Political Relations on an Interstellar Scale
  • How can a vulnerable function can be a exploited by a non-logged user if it only called in the WP admin section of a plugin?
  • Was the idea of foxes with many tails invented in anime, or is it a Japanese folk religion thing?
  • Is a hotter heat source always necessary for an object to be heated?
  • Is it realistic that I can fit and maintain 22 trillion people without the need to eat in East Asia?

exception has occurred valueerror assignment destination is read only

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ValueError: assignment destination is read-only #229

@SalvatoreRa

SalvatoreRa commented Apr 12, 2024

Hi,

I am trying just to replicate the tutorial:

and I got this error:

No branches or pull requests

@SalvatoreRa

IMAGES

  1. Valueerror Assignment Destination Is Read Only

    exception has occurred valueerror assignment destination is read only

  2. Valueerror Assignment Destination Is Read Only

    exception has occurred valueerror assignment destination is read only

  3. ValueError: assignment destination is read-only [Solved]

    exception has occurred valueerror assignment destination is read only

  4. ValueError: assignment destination is read-only · Issue #580 · uber

    exception has occurred valueerror assignment destination is read only

  5. Valueerror Assignment Destination Is Read Only

    exception has occurred valueerror assignment destination is read only

  6. Python Numpy.ndarray ValueError:assignment destination is read-only

    exception has occurred valueerror assignment destination is read only

VIDEO

  1. How To Fix Java Exception Has Occurred in 2024

  2. Fix Exception occurred while executing 'put'

  3. Unhandled Exception Has Occurred -Exception From HRESULT 0X800AC472

  4. Mi Flash Tool

  5. Over 100 shots fired near Salem’s riverfront carousel

  6. Learn Python EXCEPTION HANDLING in 5 minutes! 🚦

COMMENTS

  1. ValueError: assignment destination is read-only [Solved]

    The NumPy "ValueError: assignment destination is read-only" occurs when you try to assign a value to a read-only array. To solve the error, create a copy of the read-only array and modify the copy. You can use the flags attribute to check if the array is WRITABLE. main.py. from PIL import Image.

  2. what is the error : "ValueError: assignment destination is read-only"?

    When I am opening a jpg file using cv2.imread() and it fails sometimes which is likely due to BGR format I used. So I switched to PLT to use RGB. import matplotlib.pyplot as plt import numpy as np...

  3. ValueError: Assignment destination is read-only

    In the case of `assignment destination is read-only`, the value that you are trying to assign to the variable is not compatible with the type of the variable. For example, you cannot assign a string value to a variable that has been declared as an integer. This will cause a `ValueError` with the message `assignment destination is read-only`.

  4. [SOLVED] Valueerror assignment destination is read-only

    Solutions for ValueError: assignment destination is read-only. Here are some solutions to solve the ValueError: assignment destination is read-only: Solution 1: Use Mutable Data Structures. Instead of using immutable data structures like tuples or strings, switch to mutable ones such as lists or dictionaries.

  5. ValueError: assignment destination is read-only, when ...

    When I run SparseCoder with n_jobs > 1, there is a chance to raise exception ValueError: assignment destination is read-only. The code is shown as follow: from sklearn.decomposition import SparseCoder import numpy as np data_dims = 4103 ...

  6. ValueError: assignment destination is read-only #14972

    ValueError: assignment destination is read-only """ The above exception was the direct cause of the following exception: ValueErrorTraceback (most recent call last) in 5 6 ... ValueError: assignment destination is read-only. I used the solution on tensorflow/models#6242 but that didn't fix it.

  7. Exception "assignment destination is read-only" when reading from a

    After a quick check, I confirm: a plain array with writeable=False works, but not an array of a subclass that enforces writeable=False.. It's not quite clear to me why in a.take(b), NumPy wants the result to be the type of b rather than the type of a.But then, I guess the subclass rules are rather complex and this may be a surprising side effect.

  8. System error: assignment destination is read-only

    High: It blocks me to complete my task. Hi, I would like to ask about an issue that I encountered when I try to distribute my work on multiple cpu nodes using ray. My input file is a simulation file consisting of multiple time frames, so I would like to distribute the calculation of one frame to one task. It works fine when I just used pool from the multiprocessing python library, where only ...

  9. " ValueError: assignment destination is read-only" when using Pandas

    System information Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Custom code I suppose (see below) OS Platform and Distribution (e.g., Linux Ubuntu...

  10. ValueError: assignment destination is read-only

    I have an app that works the first time but crashes with the included error on second tries. I have isolated it to the hvplot object. I have tried wrapping it ...

  11. Scikit-learn: ValueError: assignment destination is read-only, when

    When I run SparseCoder with n_jobs > 1, there is a chance to raise exception ValueError: assignment destination is read-only.The code is shown as follow: from sklearn.decomposition import SparseCoder import numpy as np data_dims = 4103 init_dict = np.random.rand(500, 64) data = np.random.rand(data_dims, 64) c = SparseCoder(init_dict , transform_algorithm='omp', n_jobs=8).fit_transform(data)

  12. Determine how a param is being set as readonly

    But in your code you should definitely not use it since it will skip exceptions. This context manager would be better off in a separate module dedicated to the docs. I have a class similar to the example below class P (param.Parameterized): a = param.Array () r = param.Array () d = param.DataFrame () def setup (self): axis_names = [f"Axis_ {i+1 ...

  13. ValueError: assignment destination is read-only #6242

    ValueError: assignment destination is read-only #6242. Closed T-chuangxin opened this issue Feb 21, 2019 · 5 comments Closed ... ValueError: assignment destination is read-only ` The text was updated successfully, but these errors were encountered: All reactions.

  14. ValueError: assignment destination is read-only

    Grzesiu Holui Asks: ValueError: assignment destination is read-only My goal is to make aliasing in python but actually i have problem ValueError: assignment destination is read-only. This because of this line numpy_new[:lines * k][:][:] = numpy_last And I don't know how solve this. import...

  15. Trying to replace part of array to another array, get error ValueError

    ValueError: cannot set WRITEABLE flag to True of this array Make a copy of it so you can apply the changes to it: pixel_n = pixels_new.copy() pixels_n[i] = pixels_old[i]

  16. Numpy中赋值目标为只读的错误

    Numpy中赋值目标为只读的错误 - 广播 在本文中,我们将介绍Numpy中的一个常见错误:"assignment destination is read-only",它通常与广播有关。 阅读更多:Numpy 教程 广播 Numpy中的广播是一种机制,它使得不同形状的数组在执行操作时具有相同的形状。例如,我们可以将一个标量(1维数组)加到一个矩阵 ...

  17. Xarray operations produce read-only array #3813

    It seemed very strange to both copy the DataArray (.copy()), convert the dask array to a numpy array (np.asarray), and then still get a read-only array. I can understand how xarray would treat numpy arrays and dask arrays the same when it comes to this, but coming from outside the project it is very surprising that a dask array would be marked ...

  18. Error in Joblib Parallelisation Python : assignment destination is read

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  19. ValueError: assignment destination is read-only #229

    ValueError: assignment destination is read-only #229. Open SalvatoreRa opened this issue Apr 12, 2024 · 0 comments Open ValueError: assignment destination is read-only #229. ... 483 sys.stdout.flush() ValueError: assignment destination is read-only The text was updated successfully, but these errors were encountered: ...