我在pyhton中遇到此错误:ValueError:x和y的大小必须相同

时间:2019-04-25 18:08:34

标签: python regression spyder linear

我正在尝试导入一个csv文件,找到线性回归后,我想为其绘制一个图形。但是,当我在输出中输入值后,它向我显示了此错误。 概率是正确的,我已经检查过,只有此绘图功能不起作用。 谁能告诉我这是什么问题。

这是我的代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def plot_regression(x, y, b): 
    # plotting the actual points as scatter plot 
    plt.scatter(x, y, color = "g", marker = "o", s = 30) 

    # predicted response vector 
    y_pred = b[0] + b[1]*x 

    # plotting the regression line 
    plt.plot(x, y_pred, color = "r") 

    # putting labels 
    plt.xlabel('x') 
    plt.ylabel('y') 

    # function to show plot 
    plt.show() 

def estimate(x,y):
    n=np.size(x)
    mx=np.mean(x)
    my=np.mean(y)

    xy=np.sum(y*x) -n*my*mx
    xx=np.sum(x*x) -n*mx*mx

    b1=xy/xx
    b0=my-b1*mx
    return(b0,b1)


data=pd.read_csv("linearwala.csv")
x=data['temp'].values
y=data['passengers'].values

b=estimate(x,y)


year=int(input("enter the value: "))

y=b[0]+b[1]*year
print("probabs are:")
print("b[0] :",b[0],"\n b[1] :",b[1])
print("final probabs are:",y)

b0=b[0]
b1=b[1]

bb=[b0,b1]
plot_regression(x,y,bb)

这是我的输出:  enter image description here

Here是我的csv文件。

1 个答案:

答案 0 :(得分:1)

您正在用新值覆盖y,因此无法绘制它。您需要使用其他变量名称-也许是prob

#...

probs=b[0]+b[1]*year
print("probabs are:")
print("b[0] :",b[0],"\n b[1] :",b[1])
print("final probabs are:",probs)

#...