Python线性回归方程计算器
本文最后更新于 408 天前,其中的信息可能已经有所发展或是发生改变。
回归

大家不觉得线性回归方程运算量挺大的········
有兴趣的可以看看:这个西格玛写的我心惊胆战
有一些功能没有做,以后再填坑
直接上代码:

"""
The MIT License (MIT)

Copyright (c) <year> <copyright holders>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED T THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from tkinter import *
import re
import tkinter.messagebox as messagebox
def del_coor():
    global __coordinate__
    __coordinate__ = []
    global y_pad
    root.geometry('360x'+str(200+(y_pad-150))+'+200+20')
    for times_del in Button_check:
        Button_check[times_del].deselect()
        Button_check[times_del].configure(state=DISABLED)
        Button_check[times_del].update()
    try:
        global show_con
        show_con.destroy()
        global show_equ
        show_equ.destroy()
    except:
        pass
    Button_cal.configure(state=DISABLED)
    Button_mat.configure(state=DISABLED)
    Button_cls.configure(state=DISABLED)
    root.update()
def do_matplotlib():
    pass
def do_calculate():
    if (__coordinate__.count(__coordinate__[0])==len(__coordinate__)):
        messagebox.showerror("数据错误","所有运算数据不能均相等!")
        return 0
    x_add,y_add,accumulate_xy,accumulate_x,accumulate_y=0,0,0,0,0
    for coor in __coordinate__:
        coor = coor.rstrip(")").lstrip("(")
        x = float(coor.split(",")[0])
        y = float(coor.split(",")[1])
        accumulate_xy += x*y
        x_add += x
        y_add += y
        accumulate_x += x**2
        accumulate_y += y**2
    x_averange,y_averange = x_add/len(__coordinate__),y_add/len(__coordinate__)
    Upper = accumulate_xy-len(__coordinate__)*x_averange*y_averange
    Downer = ((accumulate_x-len(__coordinate__)*(x_averange**2))**0.5)*((accumulate_y-len(__coordinate__)*(y_averange**2))**0.5)
    coefficient_num = Upper/Downer
    eqation_upper = accumulate_xy-(x_add*y_add/len(__coordinate__))
    eqation_downer = accumulate_x-(x_add*x_add/len(__coordinate__))
    b = eqation_upper/eqation_downer
    a = y_add/(len(__coordinate__))-b*(x_add/(len(__coordinate__)))
    equation_co = ("线性回归方程:y = "+str(round(a,3))+" + "+str(round(b,3))+"X")
    root.geometry('360x'+str(200+(y_pad-150)+50))
    global coefficient
    coefficient = ("线性相关系数:"+str(round(coefficient_num,4))+" | 相关性:")
    if (coefficient_num == 0):
        coefficient += "不相关"
    elif (coefficient_num > 0):
        coefficient += "正相关"
    else:
        coefficient += "负相关"
    global show_con
    global show_equ
    show_equ = Label(text=equation_co,fg="red")
    show_equ.place(rely="0.77",relx="0.2")
    show_con = Label(text=coefficient,fg="red")
    show_con.place(rely="0.85",relx="0.2")
def add_coor():
    new_list_coor = []
    coor = (str(Entry_coor.get())).strip(' ')
    coor_re = r'^\(-{0,1}\d*\.{0,1}\d*,-{0,1}\d*\.{0,1}\d*\)

    coor_list = coor.split(' ')
    has_add_coor = 0
    for coor in coor_list:
        if (not coor.startswith('(')):
            coor = '(' + coor
        if (not coor.endswith(')')):
            coor = coor + ')'
        if (re.match(coor_re,str(coor))) != None:
            new_list_coor.append(coor)
            __coordinate__.append(coor)
            has_add_coor += 1
            global dan_coor
            dan_coor += 1
        else:
            messagebox.showerror('数据错误','请输入按照 x,y 数据(有无括号均可)格式的有效值!\n已经添加前了%i个坐标'%has_add_coor)
            break
    if has_add_coor == len(coor_list):
        Entry_coor.delete(0,END)
    if len(__coordinate__) != 0:
        Button_mat.configure(state=ACTIVE)
        Button_cls.configure(state=ACTIVE)
        Button_cls.update()
        Button_mat.update()
    if has_add_coor != 0:
        Label(root,text="已经添加的数据有:").place(x="15",y="110")
    global y_pad,x_pad
    times = 0
    for coor_items in new_list_coor:
        global Button_check
        Button_check['a'+str(times+1)] = Checkbutton(root,text=coor_items)
        Button_check['a'+str(times+1)].place(y=y_pad,x=x_pad)
        Button_check['a'+str(times+1)].select()
        x_pad += 100
        times += 1
        if (x_pad>=160):
            x_pad = 15
            y_pad += 34
        if (y_pad>=170):
            root.geometry('360x'+str(205+(y_pad-150)))
    del times
    if len(__coordinate__) >= 2:
        Button_cal.configure(state=ACTIVE)
        Button_cal.update()
root = Tk()
Button_check = {}
__coordinate__ = []
x_pad = 15
y_pad = 130
dan_coor = 0
root.title('线性回归方程计算')
root.resizable(False,True)
root.geometry("370x220+200+20")
check = IntVar()
show = StringVar()
Label(text="在此输入您想要运算的坐标,输入后按添加:").pack(side="top",anchor="w",padx="10",pady="5")
Label(text="小提示:您可以在两个坐标之间加入空格来一次输入多个坐标").pack(anchor="sw",padx="10")
Label(text="作者:[email protected]",fg="blue").pack(side="bottom",pady="5")
Button_add = Button(command=add_coor,text="添加")
Entry_coor = Entry(root,textvariable = show,width="25",font=('Microsoft Yahei','10','bold'),relief="groove")
Button_cal = Button(command=do_calculate,text="计算",state=DISABLED)
Button_mat = Button(command=do_matplotlib,text="绘图",state=DISABLED)
Button_cls = Button(command=del_coor,text="清空",state=DISABLED)
Entry_coor.pack(side="left",anchor="nw",padx="35",ipady="5",pady="10")
Button_add.pack(anchor="nw",pady="10")
Button_cal.place(rely="0.55",relx=0.8)
Button_mat.place(rely="0.7",relx=0.8)
Button_cls.place(rely="0.55",relx=0.7)
def popupmenu(event):
    menu.post(event.x_root,event.y_root)
class section:
    def onPaste(self):
        try:
            self.text = root.clipboard_get()
        except TclError:
            pass
        else:
            show.set(str(self.text))
    def onCopy(self):
        self.text = Entry_coor.get()
        root.clipboard_append(self.text)
    def onCut(self):
        self.onCopy()
        try:
            Entry_coor.delete('sel.first','sel.last')
        except TclError:
            pass
section = section()
menu = Menu(root,tearoff=0)
menu.add_command(label="复制",command=section.onCopy)
menu.add_separator()
menu.add_command(label="粘贴",command=section.onPaste)
menu.add_separator()
menu.add_command(label="剪切",command=section.onCut)
Entry_coor.bind("<Button -3>",popupmenu)
if __name__ == "__main__":
    root.mainloop()
暂无评论

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇