最小二乘法,可视化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()
相关推荐
vibecoding日记4 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21386 小时前
Verilog参数化游程编码RLE模块
算法
望易7 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络10 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法