python - 为什么没有打印任何行并且估计系数为 NaN?

标签 python numpy matplotlib

代码使用numpy.genfromtxt将数据集导入到代码中,然后尝试通过散点图绘制回归线。但是,散点图会打印,而线条不会打印。估计系数也输出 NaN。问题出在哪里?

import numpy as np 
import matplotlib.pyplot as plt 
from numpy import genfromtxt

def estimate_coef(x, y): 
    # number of observations/points 
    n = np.size(x) 

    # mean of x and y vector 
    m_x, m_y = np.mean(x), np.mean(y) 

    # calculating cross-deviation and deviation about x 
    SS_xy = np.sum(y*x) - n*m_y*m_x 
    SS_xx = np.sum(x*x) - n*m_x*m_x 

    # calculating regression coefficients 
    b_1 = SS_xy / SS_xx 
    b_0 = m_y - b_1*m_x 

    return(b_0, b_1) 

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

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

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

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

    # function to show plot 
    plt.show() 

def main(): 
    # observations 
    x = genfromtxt('/Users/divyanshuvarma/Downloads/graduate-admissions/Admission_Predict.csv', delimiter=',',usecols=(1))
    y = genfromtxt('/Users/divyanshuvarma/Downloads/graduate-admissions/Admission_Predict.csv', delimiter=',',usecols=(8))


    # estimating coefficients 
    b = estimate_coef(x, y) 
    print("Estimated coefficients:\nb_0 = {}  \
          \nb_1 = {}".format(b[0], b[1])) 

    # plotting regression line 
    plot_regression_line(x, y, b) 

if __name__ == "__main__": 
    main() 

最佳答案

函数estimate_coef中有一个除法b_1 = SS_xy/SS_xx。您是否打印出值SS_xx,也许它为零?希望有帮助。

关于python - 为什么没有打印任何行并且估计系数为 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55413674/

相关文章:

python - 有人知道 Django 中的 RTF 报告生成器吗?

python - Numpy:合并多个切片的有效方法

python - Python 中的 3D 绘图 - 向散点图添加图例

python - 用 Bokeh 中的颜色简化绘图

python - 将颜色图与 matplotlib 循环器一起使用

python - 在 Django 中,我如何返回与模型相关的项目总数?

python - 有条件写入文件的最有效方法?

python - 如何将嵌套列表作为新列添加到现有的 Pandas 数据框中

使用 pylab 绘制 python 绘图

python - 如何在Python中追加某个索引的列表?