用python写一个基于PySimpleGUI的处理线性回归问题并绘制拟合直线的ui程序
时间: 2023-07-16 07:14:19 浏览: 48
好的,下面是一个基于PySimpleGUI的处理线性回归问题并绘制拟合直线的UI程序的示例代码。在这个程序中,用户可以输入一组数据点,然后程序将使用线性回归算法拟合这些数据点并绘制拟合直线。
```python
import PySimpleGUI as sg
import matplotlib.pyplot as plt
import numpy as np
sg.theme('DefaultNoMoreNagging')
layout = [
[sg.Text('Linear Regression', font=('Helvetica', 20))],
[sg.Text('Enter x values: '), sg.InputText(key='x_values')],
[sg.Text('Enter y values: '), sg.InputText(key='y_values')],
[sg.Button('Fit Line'), sg.Button('Exit')],
[sg.Canvas(key='-CANVAS-')],
]
window = sg.Window('Linear Regression', layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event == 'Fit Line':
try:
x_values = np.array([float(x) for x in values['x_values'].split(',')])
y_values = np.array([float(y) for y in values['y_values'].split(',')])
assert len(x_values) == len(y_values)
except:
sg.popup('Invalid input!')
continue
# fit the line
A = np.vstack([x_values, np.ones(len(x_values))]).T
m, c = np.linalg.lstsq(A, y_values, rcond=None)[0]
# plot the points and the line
fig, ax = plt.subplots()
ax.plot(x_values, y_values, 'o', label='Data')
ax.plot(x_values, m*x_values + c, label='Fitted line')
ax.legend()
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Linear regression')
plt.close(fig)
# display the plot in the window
canvas = window['-CANVAS-'].TKCanvas
canvas.delete('all')
graph = FigureCanvasTkAgg(fig, master=canvas)
graph.draw()
graph.get_tk_widget().pack(side='top', fill='both', expand=1)
window.close()
```
运行这个程序后,用户可以在GUI界面中输入x和y值,点击“Fit Line”按钮进行计算和绘图。程序会检查并解析输入的数据,然后使用numpy中的线性回归函数求解回归系数,最后使用matplotlib绘制拟合直线并将图像显示在GUI界面中。