Меню

Ошибка valueerror shape mismatch objects cannot be broadcast to a single shape

Why is valueerror shape mismatch objects cannot be broadcastValueerror: shape mismatch: objects cannot be broadcast to a single shape error might occur when you perform an arithmetic operation on differently shaped variables. Moreover, another reason can be an attempt to plot the vectors having different lengths. Don’t worry if the causes have confused you even more because this article will explain to you the same in detail. Read more to dive into the details of the causes and get the best solution to eliminate the stated error.

Contents

  • Why Is ValueError: Shape Mismatch: Objects Cannot Be Broadcast To a Single Shape Occurring?
    • – Performing Arithmetic Operation on Differently Shaped Variables
    • – Plotting Vectors of Different Lengths
  • How To Fix the Above Error?
    • – Adjust the Shapes of Variables To Remove ValueError: Shape Mismatch: Objects Cannot Be Broadcast To a Single Shape
    • – Align the Lengths of the Vectors To Be Plotted
  • Solving Your Query
    • – Why Does the Error Targeting Mismatched Shapes Pops Up While Using str.len()?
  • Conclusion

The above error is occurring because you are trying to compute differently shaped variables. Also, the given value error might appear when you plot the vectors that don’t have similar lengths. Please read the cause descriptions for more clarity.

– Performing Arithmetic Operation on Differently Shaped Variables

The line of code that attempts to calculate differently shaped variables will throw the error mentioned above. It is because the given variables won’t be compatible with each other. Consequently, they won’t be able to produce an output irrespective of the type of arithmetic operator being used.

The issue was once noticed while using SciPy’s pearsonr(x,y) method. The erroneous code inside the said method looked like this: res = n*(np.add.reduce(xm*ym)).

So, here the issue seemed to be related to the x and y variables. The different shapes of x and y don’t allow the multiplication of both the variables resulting in the above error.

– Plotting Vectors of Different Lengths

Are you getting the above error while working with matplotlib and numpy libraries? Well, then a possible reason can be the different lengths of the vectors to be plotted. It is because the matplotlib doesn’t know about the procedure of plotting such vectors.

The example erroneous code can be seen here:

import matplotlib.pyplot as plt
import numpy as np
vector1 = np.arange(9)
vector2 = np.arange(8)
plt.bar(vector1, vector2)

How To Fix the Above Error?

You can fix the value error stated in the title by adjusting the shapes of the variables and the lengths of the vectors accordingly. So, once you’ve figured out the erroneous code in your program, opt for any of the given solutions to resolve the error:

– Adjust the Shapes of Variables To Remove ValueError: Shape Mismatch: Objects Cannot Be Broadcast To a Single Shape

You should adjust the shapes of the variables before performing any arithmetic operation on the same. Indeed, it is important to ensure that the variables are compatible with each other. Well, the error might go away even if you manipulate the variables on the same line that performs an arithmetic operation on the same. Here, you only need to ensure that the manipulation is carried out before the calculation.

– Align the Lengths of the Vectors To Be Plotted

Did your coding mistake resemble the second cause shared above? If yes, then the solution is super-easy and simplest. You only have to adjust the lengths of the vectors to make them the same, not even one number up or down. Consequently, you’ll see the error go away and the vectors will be plotted perfectly.

Solving Your Query

Here is a common question that relates to the above error:

– Why Does the Error Targeting Mismatched Shapes Pops Up While Using str.len()?

The stated error might occur when you improperly specify a condition that compares the lengths of two or more variables by using str.len(). Here, you should look for any extra parenthesis and remove them. Also, wrapping each sub-condition inside individual parenthesis can make the code work for you and eliminate the error.

Here is an example code that works:

(str1.str.len() != str2.str.len())
((str1.str.len() != 7) & (str2.str.len() == 10))

Conclusion

You have now understood enough about the value error that targetted the shapes of the variables and indirectly, the lengths of the vectors as well. Please see the below list to have a quick revision of the solutions discussed above:

  • The error is occurring because you are trying to compute differently shaped variables.
  • Adjusting the shapes of the variables before using them in a mathematical expression can help you in resolving the error.
  • You should ensure that the lengths of the vectors are the same before plotting them to solve the above error.

Valueerror shape mismatchInterestingly, even the error statement will seem clear to you after reading this article. So, get back to your program, look for the incompatible variables or vectors, and correct them to proceed further.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

Table of Contents
Hide
  1. Code Example

    1. Solution
  2. Live Demo

    1. Related Posts

In this article we will see Python code to resolve valueerror: shape mismatch: objects cannot be broadcast to a single shape. This error occurs when one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar).

When you do arithmetic operations like addition, multiplication over variables of different shape then this error occurs.

Error Code – Let’s first replicate the error –

import matplotlib.pyplot as plt
import numpy as np
 
x = np.arange(10)
y = np.arange(11)
plt.bar(x, y)

This code will generate valueerror: shape mismatch: objects cannot be broadcast to a single shape. Because (x,y) co-ordinates are always in pairs and if there are more y than x, then how will you plot them? Same issue happens with different libraries and they throw error.

The error could also occur in SciPy Pearson correlation coefficient function pearsonr(x,y). Both x and y needs to have same shape. The below code will throw error –

from scipy import stats
res = stats.pearsonr([1, 2, 3, 4], [10, 9, 2.5, 6, 4])
print(res)

Error –

Traceback (most recent call last):
  File "pearsonr.py", line 2, in <module>
    res = stats.pearsonr([1, 2, 3, 4], [10, 9, 2.5, 6, 4])
  File "/usr/lib/python3.6/site-packages/scipy/stats/stats.py", line 3001, in pearsonr
    r_num = np.add.reduce(xm * ym)
ValueError: operands could not be broadcast together with shapes (4,) (5,)

Solution

Keep the shape of variables similar.

import matplotlib.pyplot as plt
import numpy as np
 
x = np.arange(11)
y = np.arange(11)
plt.bar(x, y)

Now we set both (x,y) co-ordinates of same shape. So, it will work fine.

from scipy import stats
res = stats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4])
print(res)

Here we set both arrays of same shape in pearsonr method. Output will be –

(-0.7426106572325057, 0.15055580885344547)

Live Demo

Open Live Demo

This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.

Related Tags
  • Error,
  • python error,
  • python-short

One situation this could happen is when you try to plot with two vectors of different sizes. Say you have an x vector of size 10 and a y vector of size 11, and you try plot them with plt.bar(x, y) as follows:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
y = np.arange(11)
plt.bar(x, y)

ValueError: shape mismatch: objects cannot be broadcast to a single shape

The reason being that when plotting you always expect to have the x coordinate and y coordinate to come in pairs. If they don’t have the same length, matplotlib can’t figure out how to plot it.

So when you get this error, double check your input to the plot functions and make sure they are what you meant them to be.


PS: Ever struggling extracting html table or other similar web data to an excel sheet or a csv file ? Check out the isheet chrome extension here: https://chrome.google.com/webstore/detail/isheet/mglgkilcpipfamlcfpghglopplaicobn

#python #pandas #dataframe #matplotlib #scikit-learn

Вопрос:

У меня есть фрейм данных, который выглядит так (очевидно, он намного больше):

 id     points isAvailable frequency   Score
abc1   325    0           93          0.01
def2   467    1           80          0.59
ghi3   122    1           90          1 
jkl4   546    1           84          0
mno5   355    0           93          0.99
 

Я хочу посмотреть , насколько велики возможности points isAvailable и frequency влияние Score . Я хочу использовать случайные леса, как в этом примере:

 import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
#from sklearn.inspection import permutation_importance
#import shap
from matplotlib import pyplot as plt

plt.rcParams.update({'figure.figsize': (12.0, 8.0)})
plt.rcParams.update({'font.size': 14})

list_of_columns = ['points','isAvailable', 'frequency']
X = df[list_of_columns]
target_column = 'Score'
y = df[target_column]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=12)

rf = RandomForestRegressor(n_estimators=100)
rf.fit(X_train, y_train)
rf.feature_importances_ #the array below is the output 
>>> array([0.44326132, 0.01666047, 0.        , 0.5400782 ])

plt.barh(df.columns, rf.feature_importances_)
 

В последней строке я получаю следующую ошибку: ValueError: shape mismatch: objects cannot be broadcast to a single shape . Должен ли я был создавать эти столбцы в самом начале? Есть ли проблема в (больших) данных?

Ответ №1:

rf Модель обучается X , которая является только подмножеством df , поэтому значения функций должны быть нанесены на X.columns (или list_of_columns ) вместо df.columns :

 plt.barh(X.columns, rf.feature_importances_)
 

гистограмма важности функции

I am working in python3 and I want to obtain a stacked barchart plot, showing three different variables on 5 different columns.
My code works fine if I do not add the ‘bottom parameter’ in plt.bar (but I need to, in order for the stacks to appear in the correct order):

import numpy as np
import matplotlib as plt

columns=['a','b','c','d','e']
pos = np.arange(5)
var_one=[40348,53544,144895,34778,14322,53546,33623,76290,53546]
var_two=[15790,20409,87224,22085,6940,27099,17575,41862,27099]
var_three=[692,3254,6645,1237,469,872,569,3172,872]

plt.bar(pos,var_one,color='green',edgecolor='green')
plt.bar(pos,var_two,color='purple',edgecolor='purple')
plt.bar(pos,var_three,color='yellow',edgecolor='yellow')
plt.xticks(pos, columns)
plt.show()

However, once I add the bottom parameter in bar.plot (as shown below):

import numpy as np
import matplotlib as plt

columns=['a','b','c','d','e']
pos = np.arange(5)
var_one=[40348,53544,144895,34778,14322,53546,33623,76290,53546]
var_two=[15790,20409,87224,22085,6940,27099,17575,41862,27099]
var_three=[692,3254,6645,1237,469,872,569,3172,872]

plt.bar(pos,var_one,color='green',edgecolor='green')
plt.bar(pos,var_two,color='purple',edgecolor='purple',bottom=var_one)
plt.bar(pos,var_three,color='yellow',edgecolor='yellow',bottom=var_one+var_two)
plt.xticks(pos, columns)
plt.show()

the code triggers the error

ValueError: shape mismatch: objects cannot be broadcast to a single shape

How could I fix it?

python - ValueError: shape mismatch: objects cannot be broadcast to a single shape

python – ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, its not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

python – ValueError: shape mismatch: objects cannot be broadcast to a single shape

Related posts on python :

  • python – ValueError: unconverted data remains: 02:05
  • python – Pyspark: show histogram of a data frame column
  • python – Save Numpy Array using Pickle
  • python 3.x – Virtualenv – workon command not found
  • python NameError: global name __file__ is not defined
  • python – s3 urls – get bucket name and path
  • How can I tail a log file in Python?
  • python – Create dynamic URLs in Flask with url_for()
  • python – Usage of sys.stdout.flush() method

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка valueerror math domain error
  • Ошибка valueerror invalid literal for int with base 10