计算r平方但是没有定义y_orig

问题描述 投票:-1回答:2

我正在尝试使用在线教程计算R平方(我是一个非常慢的初学者!)并且遇到一个错误,指出没有定义y_orig。我正在使用提供的代码但链接到电子表格,而教程已经创建了自己的np.array,所以我认为这是问题所在。我想我必须为y_orig和y_line创建一个变量,那里的任何人都愿意帮忙吗?代码如下。

import statistics
from statistics import mean
import numpy as np
Damodaran = pd.read_c("C://Users//Darren//Desktop//CFA//Strathclyde//Big     Data//Assignment//Latest//revised 2.csv")
xs = Damodaran.Growth
ys = Damodaran.Beta
plt.scatter(xs,ys)
plt.show()
def best_fit_slope (xs,ys): 
    m =( ((mean(xs)*mean(ys))-mean(xs*ys))/
    ((mean(xs)*mean(xs))-mean(xs*xs)) )
return m
m = best_fit_slope(xs,ys)
print(m)

from matplotlib import style
style.use('fivethirtyeight')
def best_fit_slope_and_intercept (xs,ys): 
    m =( ((mean(xs)*mean(ys))-mean(xs*ys))/
    ((mean(xs)*mean(xs))-mean(xs*xs)) )
    b = mean(ys) - m*mean(xs)
return m, b

def squared_error (ys_orig, ys_line):
    return sum((ys_line - ys_orig)**2)

def coeffiecient_of_determination (ys_orig, ys_line):
    y_mean_line= [mean(ys_orig) for ys in y_orig]
    squared_error_regr = squared_error (ys_orig, ys_line)
    squared_error_y_mean = squared_error(ys_orig, y_mean_line)
    return 1 - (squared_error_regr / squared_error_y_mean)

m,b = best_fit_slope_and_intercept(xs,ys)

谢谢Coeur,为什么几个月后改变....?

python linear-regression
2个回答
0
投票

错误说,因为虽然定义了ys_orig,但y_orig不是。


0
投票

我无法在评论中格式化代码,因此请将其放在此处。下面是一个示例Python图形多项式拟合器,它还可以计算RMSE和R平方拟合统计量。

import numpy, matplotlib
import matplotlib.pyplot as plt

xData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.0, 6.6, 7.7, 0.0])
yData = numpy.array([1.1, 20.2, 30.3, 40.4, 50.0, 60.6, 70.7, 0.1])

polynomialOrder = 2 # example quadratic

# curve fit the test data
fittedParameters = numpy.polyfit(xData, yData, polynomialOrder)
print('Fitted Parameters:', fittedParameters)

modelPredictions = numpy.polyval(fittedParameters, xData)
absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()


##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = numpy.polyval(fittedParameters, xModel)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)
© www.soinside.com 2019 - 2024. All rights reserved.