最小二乘法,可视化UI界面

python 复制代码
import tkinter as tk
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['FangSong']  # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题


# 函数用于执行最小二乘法线性拟合
def linear_regression():
    x_values = [float(x) for x in x_entry.get().split()]
    y_values = [float(y) for y in y_entry.get().split()]

    A = np.vstack([x_values, np.ones(len(x_values))]).T
    m, c = np.linalg.lstsq(A, y_values, rcond=None)[0]

    # 清空画布
    ax[0].clear()
    ax[1].clear()

    # 绘制数据点
    ax[0].scatter(x_values, y_values, label='数据点')

    # 绘制最小二乘法拟合线
    ax[0].plot(x_values, m * np.array(x_values) + c, 'r', label='自己计算的')

    ax[0].set_title(f'自己计算的: Y = {m:.5f} * X + {c:.5f}')

    # 从斜率和截距输入框获取备选直线的参数
    lines_m = [float(m) for m in m_entry.get().split()]
    lines_c = [float(c) for c in c_entry.get().split()]

    # 绘制备选直线
    for i in range(len(lines_m)):
        ax[0].plot(x_values, lines_m[i] * np.array(x_values) + lines_c[i], label=f'直线 {i + 1}')

    # 计算备选直线中最好的拟合直线,得到是哪一条直线最好
    best_line_index = np.argmin([np.sum(np.square(y_values - (m * np.array(x_values) + c))) for m, c in
                                 zip(lines_m, lines_c)])

    ax[0].set_xlabel('X')
    ax[0].set_ylabel('Y')
    ax[0].legend()

    # 在ax[1]绘制最好的直线
    ax[1].scatter(x_values, y_values, label='数据点')
    ax[1].plot(x_values, lines_m[best_line_index] * np.array(x_values) + lines_c[best_line_index], 'r',
               label=f'直线 {best_line_index + 1}')
    ax[1].set_title(
        f'最佳备选线: Y = {lines_m[best_line_index]} * X + {lines_c[best_line_index]},Index: {best_line_index + 1}')
    ax[1].set_xlabel('X')
    ax[1].set_ylabel('Y')
    ax[1].legend()

    canvas.draw()


# 创建Tkinter窗口
root = tk.Tk()
root.title('最小二乘法线性拟合')

frame = tk.Frame(root)
frame.pack(padx=10, pady=10)

# 创建输入框和标签
x_label = tk.Label(frame, text='输入x值(用空格分隔):')
x_label.pack()
x_entry = tk.Entry(frame)
x_entry.insert(0, '2 4 6 8 10')  # 设置默认值
x_entry.pack()

y_label = tk.Label(frame, text='输入y值(用空格分隔):')
y_label.pack()
y_entry = tk.Entry(frame)
y_entry.insert(0, '10.046 20.090 30.155 40.125 50.074')  # 设置默认值
y_entry.pack()

m_label = tk.Label(frame, text='输入备选直线的斜率(用空格分隔):')
m_label.pack()
m_entry = tk.Entry(frame)
m_entry.insert(0, '5.0 5.01 4.97 4.95 5.08')  # 设置默认值
m_entry.pack()

c_label = tk.Label(frame, text='输入备选直线的截距(用空格分隔):')
c_label.pack()
c_entry = tk.Entry(frame)
c_entry.insert(0, '0.08 0.07 0.12 0.15 0.06')  # 设置默认值
c_entry.pack()

# 创建确认按钮
calculate_button = tk.Button(frame, text='确认', command=linear_regression)
calculate_button.pack()

# 创建大画布
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
canvas = FigureCanvasTkAgg(fig, master=frame)
canvas.get_tk_widget().pack()
canvas.draw()

# 运行Tkinter主循环
root.mainloop()
相关推荐
hanlin037 小时前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode
All for pursuit.7 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
youngfengying8 小时前
集成学习及置信度
人工智能·机器学习
碧海银沙音频科技研究院10 小时前
基于炬芯ATS3089X自研AEC声学回声消除算法
算法
通问AI10 小时前
在两台 Mac Studio 上跑 800B 模型:MLX + RDMA over Thunderbolt 实测与四道门选型法
算法
ZywOo62310 小时前
《算法竞赛进阶指南》0x03 前缀和与差分
算法
Scintilla_y10 小时前
DAY2 滑动窗口
算法·leetcode·散列表
lvwangshu10 小时前
笛卡尔树
算法·图论
026d2311 小时前
状态信号只知“其然”不知“其所以然”:变工况机械故障诊断的物理盲区
算法
姜鱼问生11 小时前
备份和服务器在同一台机器上,等于没备份
算法·架构