From 49603422a6cedb2cd4eeace9c538ef182550246f Mon Sep 17 00:00:00 2001 From: lennlouis Date: Sun, 9 Jun 2024 22:27:55 +0800 Subject: [PATCH] linear regression finished --- .DS_Store | Bin 6148 -> 8196 bytes MainWindows.py | 45 ++++++++++++++++++++++++++++++++++++------- PlotWindows.py | 42 ++++++++++++++++++++++++++++++++++++++++ Test/data_show.ipynb | 21 ++++++++++++++++++++ qss/stypesheet.css | 2 ++ stylesheet.qrc | 5 +++++ 6 files changed, 108 insertions(+), 7 deletions(-) create mode 100644 PlotWindows.py create mode 100644 qss/stypesheet.css create mode 100644 stylesheet.qrc diff --git a/.DS_Store b/.DS_Store index cc0b6ea1fc017e6662ae5f6f9fe48e24f966da03..5652f8c9f8ff41da7f93f8c2fa8deac8867ddb8b 100644 GIT binary patch delta 306 zcmZoMXmOBWU|?W$DortDU;r^WfEYvza8FDWo2aMAD6%nNH}hr%jz7$c**Q2S7O*gi zZ02E!WE3o9C}t>5DlaZb%E?ax>exQnpQVsXyt>-bSVzIw)O_-37HP)L$$V_`^<6+| zW(Kf^l;Y%^r2PCGMubpKx?yl~er^F!1O}jrbMswXpr&&yTXbXXajs*IKqYY56g;v8 z8E{j1QHW#HUIzs delta 105 zcmZp1XfcprU|?W$DortDU=RQ@Ie-{Mvv5sJ6q~50$jG}fU^g=(?`9r>NXE^lg%&X_ rX6N7#WCkh$0s(Fy;R;f{G4VU|WPTY>kX{BRh&dpm88*lB%wYxqkcAL( diff --git a/MainWindows.py b/MainWindows.py index 59e0724..40a6333 100644 --- a/MainWindows.py +++ b/MainWindows.py @@ -1,5 +1,5 @@ import Ui_MainWindow -from PyQt5.QtCore import QFile, QFileInfo, pyqtSlot, pyqtSignal +from PyQt5.QtCore import QFile, QFileInfo, pyqtSlot, pyqtSignal, QIODevice from PyQt5 import QtGui, QtWidgets, QtCore from PyQt5.QtWidgets import QPushButton, QTableWidgetItem, QInputDialog, QLabel from PyQt5.QtGui import QIcon, QPixmap @@ -7,6 +7,7 @@ from data_set_read import Data_Read import pandas as pd import openpyxl as pyx from libdataanalysis.LinearRegression.linear_regression import LinearRegression +from PlotWindows import PlotWidget class MainWindows: def __init__(self) -> None: @@ -23,6 +24,10 @@ class MainWindows: self.ui.progressBar_linear_regression.setValue(0) self.statusLable = QLabel("准备完成!") self.ui.statusbar.addWidget(self.statusLable, 1) + qss_file = QFile(":/qss/stypesheet.css") + if qss_file.open(QIODevice.OpenModeFlag.ReadOnly): + self.MainWindow.setStyleSheet(qss_file.readAll()) + qss_file.close() def file_object_init(self): self.ui.pushButton_filepath.clicked.connect(self.pushButton_filepath_clicked) @@ -31,6 +36,8 @@ class MainWindows: self.ui.pushButton_Kmeans.clicked.connect(lambda checked: self.ui.stackedWidget.setCurrentIndex(1)) self.ui.actionNumber_Head.triggered.connect(self.action_Number_Head_triggered) self.ui.pushButton_linear_regression_begin.clicked.connect(self.pushButton_linear_regression_begin_clicked) + self.ui.pushButton_linear_regression_show.clicked.connect(self.pushButton_linear_regression_show_clicked) + self.ui.pushButton_linear_regression_save.clicked.connect(self.pushButton_linear_regression_save_clicked) def pushButton_filepath_clicked(self): file_path = QtWidgets.QFileDialog.getOpenFileName(self.MainWindow, "Open File", ".", "All Files(*);;csv Files(*.csv);;Old Excel Files(*.xls);;New Excel Files(*.xlsx)") @@ -56,7 +63,9 @@ class MainWindows: if suffix == "csv": self.set_csv_headers(data_file.absoluteFilePath()) elif suffix == "xlsx" or suffix == "xls": - self.set_excel_headers(data_file.absoluteFilePath()) + self.set_excel_headers(data_file.absoluteFilePath()) + + def set_excel_headers(self, file_path): wb = pyx.load_workbook(file_path) @@ -115,9 +124,10 @@ class MainWindows: data = pd.read_csv(self.file_path) elif suffix == "xls" or suffix == "xlsx": data = pd.read_excel(self.file_path) - - x = data[self.ui.lineEdit_linear_regression_original.text().split(",")].values - y = data[self.ui.lineEdit_linear_regression_target.text()].values + train_data = data.sample(frac=self.ui.doubleSpinBox_linear_regression_train_percent.value()) + self.test_data = train_data.drop(train_data.index) + x = train_data[self.ui.lineEdit_linear_regression_original.text().split(",")].values + y = train_data[self.ui.lineEdit_linear_regression_target.text()].values num_iterations = self.ui.spinBox_linear_regression_iter.value() learning_rate = self.ui.doubleSpinBox_linear_regression_rate.value() @@ -130,6 +140,27 @@ class MainWindows: learning_rate, num_iterations ) - msg = "开始损失: {:.2f},结束损失: {:.2f}".format(cost_history[0], cost_history[-1]) + msg = "开始损失: {:.20f},结束损失: {:.20f}".format(cost_history[0], cost_history[-1]) + self.statusLable.setText(msg) + self.draw_linear_regression_result(num_iterations, cost_history, "num_iterations", "cost_history") - self.statusLable.setText(msg) \ No newline at end of file + def draw_linear_regression_result(self, num_iterations : int, cost_history : list, xlabel, ylabel): + num_iter_list = [i for i in range(num_iterations)] + self.plotwidget = PlotWidget(num_iter_list, cost_history, xlabel, ylabel) + self.plotwidget.show() + + def pushButton_linear_regression_show_clicked(self): + if self.plotwidget is not None: + self.plotwidget.show() + + def pushButton_linear_regression_save_clicked(self): + if self.plotwidget is not None: + dir_path = QtWidgets.QFileDialog.getExistingDirectory(self.MainWindow, "Chose Directory", ".") + if dir_path is not None: + self.plotwidget.save(dir_path) + + def statusLabel_black(self): + self.statusLable.setStyleSheet("color:black") + + def statusLabel_red(self): + self.statusLable.setStyleSheet("color:red") \ No newline at end of file diff --git a/PlotWindows.py b/PlotWindows.py new file mode 100644 index 0000000..6d5b964 --- /dev/null +++ b/PlotWindows.py @@ -0,0 +1,42 @@ +from PyQt5.QtCore import Qt +from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget, QMainWindow +from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas +from matplotlib.figure import Figure +import matplotlib.pyplot as plt +import sys +from datetime import datetime + +class PlotWidget(QWidget): + # def __init__(self, parent: QWidget | None = ..., flags: Qt.WindowFlags | Qt.WindowType = ...) -> None: + # super().__init__(parent, flags) + def __init__(self, scalex, scaley, xlabel, ylabel): + super().__init__() + self.scalex = scalex + self.scaley = scaley + self.xlabel = xlabel + self.ylabel = xlabel + self.fig = Figure() + self.ax = self.fig.add_subplot(111) + + # self.ax.plot(scalex=scalex, scaley=scaley) + self.ax.plot(scalex, scaley) + self.ax.set_xlabel(xlabel=xlabel) + self.ax.set_ylabel(ylabel=ylabel) + + self.canvas = FigureCanvas(self.fig) + + layout = QVBoxLayout() + layout.addWidget(self.canvas) + self.setLayout(layout) + + self.canvas.draw() + + def save(self, dir_path): + plt.figure() + plt.plot(self.scalex, self.scaley) + plt.xlabel(self.xlabel) + plt.ylabel(self.ylabel) + current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + plt.savefig(f"{dir_path}/{current_time}.png") + + \ No newline at end of file diff --git a/Test/data_show.ipynb b/Test/data_show.ipynb index 77c75a5..b13615e 100644 --- a/Test/data_show.ipynb +++ b/Test/data_show.ipynb @@ -339,6 +339,27 @@ "str = \"1111\"\n", "print(str.split(\",\"))" ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "8b12bd42", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "range(0, 100)" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "range(100)" + ] } ], "metadata": { diff --git a/qss/stypesheet.css b/qss/stypesheet.css new file mode 100644 index 0000000..a973cd9 --- /dev/null +++ b/qss/stypesheet.css @@ -0,0 +1,2 @@ +/* stylesheet.css */ + diff --git a/stylesheet.qrc b/stylesheet.qrc new file mode 100644 index 0000000..44952b0 --- /dev/null +++ b/stylesheet.qrc @@ -0,0 +1,5 @@ + + + qss/stypesheet.css + +