Python 学者 - 如何从点击和图形上显示的图形把回归线平衡?

2024-09-30 20:22:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读johnzelle编写的Python编程,我被困在下面图片所示的一个练习上。在

你可以在下面查看我的代码。我知道代码很难看。(如有任何提示,不胜感激)

Picture of Regression Exercise

以下是我目前为止的代码:

from graphics import *

def regression():

# creating the window for the regression line
        win = GraphWin("Regression Line - Start Clicking!", 500, 500)
        win.setCoords(0.0, 0.0, 10.0, 10.0)

        rect = Rectangle(Point(0.5, 0.1), Point(2.5, 2.1))
        rect.setFill("red")
        rect.draw(win)
        Text(rect.getCenter(), "Done").draw(win)

        message = Text(Point(5, 0.5), "Click in this screen")
        message.draw(win)

        points = [] # list of points
        n = 0 # count variable
        sumX = 0
        sumY = 0

        while True:
                p = win.getMouse()
                p.draw(win)

# if user clicks in a red square it exits the loop and calculates the regression line
                if (p.getX() >= 0.5 and p.getX() <= 2.5) and (p.getY() >= 0.1 and p.getY() <= 2.1):
                        break

                n += 1 # count of the points

# get the sum of the X and Y points
                sumX = sumX + p.getX()
                sumY = sumY + p.getY()

# tuple of the X and Y points
                dot = (p.getX(), p.getY())
                points.append(dot)

        avgX = sumX / n
        avgY = sumY / n

        top = 0
        bottom = 0

# my ugly attempt at the regression equation shown in the book

        for i in points:
                gp = 0
                numer = points[gp][0] * points[gp][1]
                top = top + numer

                denom = points[gp][0] ** 2
                bottom = bottom + denom
                gp += 1

        m = (top - sumX * sumY) / (bottom - sumX ** 2)

        y1 = avgY + m * (0.0 - avgX)
        y2 = avgY + m * (10.0 - avgX)

        regressionline = Line(Point(0, y1), Point(10.0, y2))
        regressionline.draw(win)

        raw_input("Press <Enter> to quit.")
        win.close()

regression()

当我运行这个程序时,回归线似乎永远不会是真正的最佳拟合线。我相信我在代码中错误地解释了回归方程。为了得到正确的回归线,需要改变什么?在


Tags: andofthe代码inrectwinpoints
2条回答

问题:

  • from my_library import *应该避免;最好确切地指定您想要从中得到什么。这有助于保持命名空间的整洁。

  • 你有一个巨大的代码块,最好把它分成单独的函数。这使得思考和调试更加容易,并且可能有助于以后重用代码。当然,这是一个玩具问题,你不会再使用它——但是做练习的全部目的是培养好习惯,这样分解代码绝对是一个好习惯!一般的经验法则是,如果一个函数包含超过十几行代码,您应该考虑进一步拆分它。

  • 这个练习要求您在获取输入点的同时,跟踪x、y、xx和xy的运行和。我认为这是一个坏主意,或者至少比Python更具C语言风格,因为它迫使你同时完成两个不同的任务(获取点数并对它们进行数学运算)。我的建议是:如果你得到了分数,就得分数;如果你在做数学,就做数学;不要尝试同时做这两个。

  • 类似地,我不喜欢你用回归计算来担心窗口的边在哪里。它为什么要知道或关心windows?希望您喜欢我的解决方案;-)

以下是我对您代码的重构版本:

from graphics import GraphWin, Point, Line, Rectangle, Text

def draw_window()
    # create canvas
    win = GraphWin("Regression Line - Start Clicking!", 500, 500)
    win.setCoords(0., 0., 10., 10.)
    # exit button
    rect = Rectangle(Point(0.5, 0.1), Point(2.5, 2.1))
    rect.setFill("red")
    rect.draw(win)
    Text(rect.getCenter(), "Done").draw(win)
    # instructions
    Text(Point(5., 0.5), "Click in this screen").draw(win)
    return win

def get_points(win):
    points = []
    while True:
        p = win.getMouse()
        p.draw(win)
        # clicked the exit button?
        px, py = p.getX(), p.getY()
        if 0.5 <= px <= 2.5 and 0.1 <= py <= 2.1:
            break
        else:
            points.append((px,py))
    return points

def do_regression(points):
    num = len(points)
    x_sum, y_sum, xx_sum, xy_sum = 0., 0., 0., 0.
    for x,y in points:
        x_sum += x
        y_sum += y
        xx_sum += x*x
        xy_sum += x*y
    x_mean, y_mean = x_sum/num, y_sum/num
    m = (xy_sum - num*x_mean*y_mean) / (xx_sum - num*x_mean*x_mean)
    def lineFn(xval):
        return y_mean + m*(xval - x_mean)
    return lineFn

def main():
    # set up
    win = draw_window()
    points = get_points(win)
    # show regression line
    lineFn = do_regression(points)
    Line(
        Point(0.,  lineFn(0. )),
        Point(10., lineFn(10.))
    ).draw(win)
    # wait to close
    Text(Point(5., 5.), "Click to exit").draw(win)
    win.getMouse()
    win.close()

if __name__=="__main__":
    main()

for循环全乱了!您有一个在循环中更改的i,但是使用的gp总是0。在

你想要更像:

for (X, Y) in points:
    numer += X * Y
    denom += X * X

…或将gp = 0移到for循环之前。在

…或者完全删除该部分,并将sumXYsumXX添加到sumXsumY。在

不管怎样,一旦你修复了它应该是好的(好吧,或者可能是其他一些bug……)。在

相关问题 更多 >