How to convert scalar array to 2d array? The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceConvert bytes to a string?Running sklearn linear regression, getting “arrays with inconsistent numbers of samples” errorHow to find the best degree of polynomials?Regression using PythonRegression with Python (nympy/pandas)SKlearn reshape warning for X and YPredict future values after using polynomial regression in pythonValueError: could not convert string to float:While loading data from sql server to Predict()Expected 2d array but got scalar array insteadTensorflow Polynomial Linear Regression curve fit

Can I visit the Trinity College (Cambridge) library and see some of their rare books

Button changing its text & action. Good or terrible?

Is 'stolen' appropriate word?

University's motivation for having tenure-track positions

How to support a colleague who finds meetings extremely tiring?

Is every episode of "Where are my Pants?" identical?

What was the last x86 CPU that did not have the x87 floating-point unit built in?

Example of compact Riemannian manifold with only one geodesic.

Single author papers against my advisor's will?

What can I do if neighbor is blocking my solar panels intentionally?

Can a flute soloist sit?

Presidential Pardon

Could an empire control the whole planet with today's comunication methods?

US Healthcare consultation for visitors

Does Parliament hold absolute power in the UK?

Why are PDP-7-style microprogrammed instructions out of vogue?

Why not take a picture of a closer black hole?

Mortgage adviser recommends a longer term than necessary combined with overpayments

How to handle characters who are more educated than the author?

What happens to a Warlock's expended Spell Slots when they gain a Level?

Identify 80s or 90s comics with ripped creatures (not dwarves)

For what reasons would an animal species NOT cross a *horizontal* land bridge?

Why don't hard Brexiteers insist on a hard border to prevent illegal immigration after Brexit?

Sub-subscripts in strings cause different spacings than subscripts



How to convert scalar array to 2d array?



The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceConvert bytes to a string?Running sklearn linear regression, getting “arrays with inconsistent numbers of samples” errorHow to find the best degree of polynomials?Regression using PythonRegression with Python (nympy/pandas)SKlearn reshape warning for X and YPredict future values after using polynomial regression in pythonValueError: could not convert string to float:While loading data from sql server to Predict()Expected 2d array but got scalar array insteadTensorflow Polynomial Linear Regression curve fit



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am new to machine learning and facing some issues in converting scalar array to 2d array.
I am trying to implement polynomial regression in spyder. Here is my code, Please help!



# Polynomial Regression

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values

# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)

# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
X_poly = poly_reg.fit_transform(X)
poly_reg.fit(X_poly, y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)

# Predicting a new result with Linear Regression
lin_reg.predict(6.5)

# Predicting a new result with Polynomial Regression
lin_reg_2.predict(poly_reg.fit_transform(6.5))



ValueError: Expected 2D array, got scalar array instead: array=6.5.
Reshape your data either using array.reshape(-1, 1) if your data has a
single feature or array.reshape(1, -1) if it contains a single sample.











share|improve this question
























  • which line you get this error?

    – Jeril
    Mar 8 at 12:32











  • Welcome to SO; please see How to create a Minimal, Complete, and Verifiable example, as well as why a wall of code isn't helpful. Some additional advice 1) remove everything that is not relevant to the issue, e.g. code commented-out and plot commands (done it for you this time) 2) include the full error trace - as is, we don't know which exact command throws the exception...

    – desertnaut
    Mar 8 at 13:02


















0















I am new to machine learning and facing some issues in converting scalar array to 2d array.
I am trying to implement polynomial regression in spyder. Here is my code, Please help!



# Polynomial Regression

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values

# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)

# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
X_poly = poly_reg.fit_transform(X)
poly_reg.fit(X_poly, y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)

# Predicting a new result with Linear Regression
lin_reg.predict(6.5)

# Predicting a new result with Polynomial Regression
lin_reg_2.predict(poly_reg.fit_transform(6.5))



ValueError: Expected 2D array, got scalar array instead: array=6.5.
Reshape your data either using array.reshape(-1, 1) if your data has a
single feature or array.reshape(1, -1) if it contains a single sample.











share|improve this question
























  • which line you get this error?

    – Jeril
    Mar 8 at 12:32











  • Welcome to SO; please see How to create a Minimal, Complete, and Verifiable example, as well as why a wall of code isn't helpful. Some additional advice 1) remove everything that is not relevant to the issue, e.g. code commented-out and plot commands (done it for you this time) 2) include the full error trace - as is, we don't know which exact command throws the exception...

    – desertnaut
    Mar 8 at 13:02














0












0








0








I am new to machine learning and facing some issues in converting scalar array to 2d array.
I am trying to implement polynomial regression in spyder. Here is my code, Please help!



# Polynomial Regression

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values

# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)

# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
X_poly = poly_reg.fit_transform(X)
poly_reg.fit(X_poly, y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)

# Predicting a new result with Linear Regression
lin_reg.predict(6.5)

# Predicting a new result with Polynomial Regression
lin_reg_2.predict(poly_reg.fit_transform(6.5))



ValueError: Expected 2D array, got scalar array instead: array=6.5.
Reshape your data either using array.reshape(-1, 1) if your data has a
single feature or array.reshape(1, -1) if it contains a single sample.











share|improve this question
















I am new to machine learning and facing some issues in converting scalar array to 2d array.
I am trying to implement polynomial regression in spyder. Here is my code, Please help!



# Polynomial Regression

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values

# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)

# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
X_poly = poly_reg.fit_transform(X)
poly_reg.fit(X_poly, y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)

# Predicting a new result with Linear Regression
lin_reg.predict(6.5)

# Predicting a new result with Polynomial Regression
lin_reg_2.predict(poly_reg.fit_transform(6.5))



ValueError: Expected 2D array, got scalar array instead: array=6.5.
Reshape your data either using array.reshape(-1, 1) if your data has a
single feature or array.reshape(1, -1) if it contains a single sample.








python-3.x numpy machine-learning scikit-learn linear-regression






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 13:06









desertnaut

20.8k84479




20.8k84479










asked Mar 8 at 12:23









rahul bachloorahul bachloo

1




1












  • which line you get this error?

    – Jeril
    Mar 8 at 12:32











  • Welcome to SO; please see How to create a Minimal, Complete, and Verifiable example, as well as why a wall of code isn't helpful. Some additional advice 1) remove everything that is not relevant to the issue, e.g. code commented-out and plot commands (done it for you this time) 2) include the full error trace - as is, we don't know which exact command throws the exception...

    – desertnaut
    Mar 8 at 13:02


















  • which line you get this error?

    – Jeril
    Mar 8 at 12:32











  • Welcome to SO; please see How to create a Minimal, Complete, and Verifiable example, as well as why a wall of code isn't helpful. Some additional advice 1) remove everything that is not relevant to the issue, e.g. code commented-out and plot commands (done it for you this time) 2) include the full error trace - as is, we don't know which exact command throws the exception...

    – desertnaut
    Mar 8 at 13:02

















which line you get this error?

– Jeril
Mar 8 at 12:32





which line you get this error?

– Jeril
Mar 8 at 12:32













Welcome to SO; please see How to create a Minimal, Complete, and Verifiable example, as well as why a wall of code isn't helpful. Some additional advice 1) remove everything that is not relevant to the issue, e.g. code commented-out and plot commands (done it for you this time) 2) include the full error trace - as is, we don't know which exact command throws the exception...

– desertnaut
Mar 8 at 13:02






Welcome to SO; please see How to create a Minimal, Complete, and Verifiable example, as well as why a wall of code isn't helpful. Some additional advice 1) remove everything that is not relevant to the issue, e.g. code commented-out and plot commands (done it for you this time) 2) include the full error trace - as is, we don't know which exact command throws the exception...

– desertnaut
Mar 8 at 13:02













3 Answers
3






active

oldest

votes


















0














The issue with your code is linreg.predict(6.5).



If you read the error statement it says that the model requires a 2-d array , however 6.5 is scalar.
Why? If you see your X data is having 2-d so anything that you want to predict with your model should also have two 2d shape.
This can be achieved either by using .reshape(-1,1) which creates a column vector (feature vector) or .reshape(1,-1) If you have single sample.



Things to remember in order to predict I need to prepare my data in the same way as my original training data.



If you need any more info let me know.






share|improve this answer






























    0














    You have to give the input as 2D array, Hence try this!



    lin_reg.predict([6.5])
    lin_reg_2.predict(poly_reg.fit_transform([6.5]))





    share|improve this answer






























      0














      You get this issue in Jupyter only.
      To resolve in jupyter make the value into np array using below code.



      lin_reg.predict(np.array(6.5).reshape(1,-1))
      lin_reg_2.predict(poly_reg.fit_transform(np.array(6.5).reshape(1,-1)))


      For spyder it work same as you expected:



      lin_reg.predict(6.5)
      lin_reg_2.predict(poly_reg.fit_transform(6.5))





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55063175%2fhow-to-convert-scalar-array-to-2d-array%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        The issue with your code is linreg.predict(6.5).



        If you read the error statement it says that the model requires a 2-d array , however 6.5 is scalar.
        Why? If you see your X data is having 2-d so anything that you want to predict with your model should also have two 2d shape.
        This can be achieved either by using .reshape(-1,1) which creates a column vector (feature vector) or .reshape(1,-1) If you have single sample.



        Things to remember in order to predict I need to prepare my data in the same way as my original training data.



        If you need any more info let me know.






        share|improve this answer



























          0














          The issue with your code is linreg.predict(6.5).



          If you read the error statement it says that the model requires a 2-d array , however 6.5 is scalar.
          Why? If you see your X data is having 2-d so anything that you want to predict with your model should also have two 2d shape.
          This can be achieved either by using .reshape(-1,1) which creates a column vector (feature vector) or .reshape(1,-1) If you have single sample.



          Things to remember in order to predict I need to prepare my data in the same way as my original training data.



          If you need any more info let me know.






          share|improve this answer

























            0












            0








            0







            The issue with your code is linreg.predict(6.5).



            If you read the error statement it says that the model requires a 2-d array , however 6.5 is scalar.
            Why? If you see your X data is having 2-d so anything that you want to predict with your model should also have two 2d shape.
            This can be achieved either by using .reshape(-1,1) which creates a column vector (feature vector) or .reshape(1,-1) If you have single sample.



            Things to remember in order to predict I need to prepare my data in the same way as my original training data.



            If you need any more info let me know.






            share|improve this answer













            The issue with your code is linreg.predict(6.5).



            If you read the error statement it says that the model requires a 2-d array , however 6.5 is scalar.
            Why? If you see your X data is having 2-d so anything that you want to predict with your model should also have two 2d shape.
            This can be achieved either by using .reshape(-1,1) which creates a column vector (feature vector) or .reshape(1,-1) If you have single sample.



            Things to remember in order to predict I need to prepare my data in the same way as my original training data.



            If you need any more info let me know.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 9 at 0:56









            Anirban GhoshAnirban Ghosh

            11




            11























                0














                You have to give the input as 2D array, Hence try this!



                lin_reg.predict([6.5])
                lin_reg_2.predict(poly_reg.fit_transform([6.5]))





                share|improve this answer



























                  0














                  You have to give the input as 2D array, Hence try this!



                  lin_reg.predict([6.5])
                  lin_reg_2.predict(poly_reg.fit_transform([6.5]))





                  share|improve this answer

























                    0












                    0








                    0







                    You have to give the input as 2D array, Hence try this!



                    lin_reg.predict([6.5])
                    lin_reg_2.predict(poly_reg.fit_transform([6.5]))





                    share|improve this answer













                    You have to give the input as 2D array, Hence try this!



                    lin_reg.predict([6.5])
                    lin_reg_2.predict(poly_reg.fit_transform([6.5]))






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 9 at 11:02









                    ai_learningai_learning

                    4,65521136




                    4,65521136





















                        0














                        You get this issue in Jupyter only.
                        To resolve in jupyter make the value into np array using below code.



                        lin_reg.predict(np.array(6.5).reshape(1,-1))
                        lin_reg_2.predict(poly_reg.fit_transform(np.array(6.5).reshape(1,-1)))


                        For spyder it work same as you expected:



                        lin_reg.predict(6.5)
                        lin_reg_2.predict(poly_reg.fit_transform(6.5))





                        share|improve this answer



























                          0














                          You get this issue in Jupyter only.
                          To resolve in jupyter make the value into np array using below code.



                          lin_reg.predict(np.array(6.5).reshape(1,-1))
                          lin_reg_2.predict(poly_reg.fit_transform(np.array(6.5).reshape(1,-1)))


                          For spyder it work same as you expected:



                          lin_reg.predict(6.5)
                          lin_reg_2.predict(poly_reg.fit_transform(6.5))





                          share|improve this answer

























                            0












                            0








                            0







                            You get this issue in Jupyter only.
                            To resolve in jupyter make the value into np array using below code.



                            lin_reg.predict(np.array(6.5).reshape(1,-1))
                            lin_reg_2.predict(poly_reg.fit_transform(np.array(6.5).reshape(1,-1)))


                            For spyder it work same as you expected:



                            lin_reg.predict(6.5)
                            lin_reg_2.predict(poly_reg.fit_transform(6.5))





                            share|improve this answer













                            You get this issue in Jupyter only.
                            To resolve in jupyter make the value into np array using below code.



                            lin_reg.predict(np.array(6.5).reshape(1,-1))
                            lin_reg_2.predict(poly_reg.fit_transform(np.array(6.5).reshape(1,-1)))


                            For spyder it work same as you expected:



                            lin_reg.predict(6.5)
                            lin_reg_2.predict(poly_reg.fit_transform(6.5))






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 16 at 13:36









                            rahul kumeriyarahul kumeriya

                            15




                            15



























                                draft saved

                                draft discarded
















































                                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.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55063175%2fhow-to-convert-scalar-array-to-2d-array%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved