此代码将得到有关NameError的错误:未定义名称'ui'。 我无法将Ui_Mainwindow数据(样本和结果)用于线性模型(LR_Model), 我怎么能互相联系。非常感谢。
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import pandas as pd
import numpy as np
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as
FigureCanvas
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.externals import joblib
import os
from sklearn.model_selection import train_test_split
import random
主界面
class Ui_MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(Ui_MainWindow,self).__init__()
self.setupUi(self)
self.retranslateUi(self)
self.path_openfile_name=[]
self.sample_table=[]
self.result_table=[]
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1034, 605)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.loaddataButton = QtWidgets.QPushButton(self.centralwidget)
self.loaddataButton.setGeometry(QtCore.QRect(180, 60, 101, 31))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(10)
self.loaddataButton.setFont(font)
self.loaddataButton.setObjectName("loaddataButton")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(40, 444, 91, 51))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(10)
self.label.setFont(font)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(170, 444, 91, 51))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(10)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.testdata = QtWidgets.QLineEdit(self.centralwidget)
self.testdata.setGeometry(QtCore.QRect(170, 493, 113, 31))
font = QtGui.QFont()
font.setFamily("Agency FB")
font.setPointSize(10)
self.testdata.setFont(font)
self.testdata.setObjectName("testdata")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(40, 401, 91, 51))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(12)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(30, 20, 211, 41))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(12)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_3.setGeometry(QtCore.QRect(30, 100, 251, 31))
self.lineEdit_3.setObjectName("lineEdit_3")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(30, 50, 91, 51))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(10)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(300, 50, 91, 51))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(10)
self.label_6.setFont(font)
self.label_6.setObjectName("label_6")
self.lineEdit_4 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_4.setGeometry(QtCore.QRect(300, 100, 251, 31))
self.lineEdit_4.setObjectName("lineEdit_4")
self.line = QtWidgets.QFrame(self.centralwidget)
self.line.setGeometry(QtCore.QRect(30, 380, 531, 20))
self.line.setFrameShape(QtWidgets.QFrame.HLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.runmodelbotton = QtWidgets.QPushButton(self.centralwidget)
self.runmodelbotton.setGeometry(QtCore.QRect(300, 493, 101, 31))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(10)
self.runmodelbotton.setFont(font)
self.runmodelbotton.setObjectName("runmodelbotton")
self.traindata = QtWidgets.QLineEdit(self.centralwidget)
self.traindata.setGeometry(QtCore.QRect(40, 493, 113, 31))
font = QtGui.QFont()
font.setFamily("Agency FB")
font.setPointSize(10)
self.traindata.setFont(font)
self.traindata.setObjectName("traindata")
self.line_2 = QtWidgets.QFrame(self.centralwidget)
self.line_2.setGeometry(QtCore.QRect(570, 50, 20, 481))
self.line_2.setFrameShape(QtWidgets.QFrame.VLine)
self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.label_7 = QtWidgets.QLabel(self.centralwidget)
self.label_7.setGeometry(QtCore.QRect(600, 40, 121, 51))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(10)
self.label_7.setFont(font)
self.label_7.setObjectName("label_7")
self.label_8 = QtWidgets.QLabel(self.centralwidget)
self.label_8.setGeometry(QtCore.QRect(600, 280, 121, 51))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(10)
self.label_8.setFont(font)
self.label_8.setObjectName("label_8")
self.rsquare = QtWidgets.QGraphicsView(self.centralwidget)
self.rsquare.setGeometry(QtCore.QRect(600, 80, 401, 201))
self.rsquare.setObjectName("rsquare")
self.lossfunction = QtWidgets.QGraphicsView(self.centralwidget)
self.lossfunction.setGeometry(QtCore.QRect(600, 330, 401, 201))
self.lossfunction.setObjectName("lossfunction")
self.loaddataButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.loaddataButton_2.setGeometry(QtCore.QRect(450, 60, 101, 31))
font = QtGui.QFont()
font.setFamily("微軟正黑體")
font.setPointSize(10)
self.loaddataButton_2.setFont(font)
self.loaddataButton_2.setObjectName("loaddataButton_2")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(30, 140, 251, 192))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.tableWidget_2 = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget_2.setGeometry(QtCore.QRect(300, 140, 251, 192))
self.tableWidget_2.setObjectName("tableWidget_2")
self.tableWidget_2.setColumnCount(0)
self.tableWidget_2.setRowCount(0)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1034, 25))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.loaddataButton.clicked.connect(self.openfile)
self.loaddataButton_2.clicked.connect(self.openfile)
self.loaddataButton.clicked.connect(self.creat_table_show)
self.loaddataButton_2.clicked.connect(self.creat_table_show2)
self.runmodelbotton.clicked.connect(LR_Model())
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.loaddataButton.setText(_translate("MainWindow", "讀取資料"))
self.label.setText(_translate("MainWindow", "訓練資料"))
self.label_2.setText(_translate("MainWindow", "測試資料"))
self.label_3.setText(_translate("MainWindow", "模型設定"))
self.label_4.setText(_translate("MainWindow", "配對預測模型"))
self.label_5.setText(_translate("MainWindow", "量測數據"))
self.label_6.setText(_translate("MainWindow", "模擬數據"))
self.runmodelbotton.setText(_translate("MainWindow", "預測"))
self.label_7.setText(_translate("MainWindow", "Accurancy Rate"))
self.label_8.setText(_translate("MainWindow", "Loss Function"))
self.loaddataButton_2.setText(_translate("MainWindow", "讀取資料"))
开放数据功能
def openfile(self):
openfile_name = QFileDialog.getOpenFileName(self,'選擇文件','','Excel files(*.csv , *.csv)')
#print(openfile_name)
global path_openfile_name
###获取路径
path_openfile_name = openfile_name[0]
存在样本数据
def creat_table_show(self):
if len(path_openfile_name) > 0:
self.sample_table = pd.read_csv(path_openfile_name)
#print(input_table)
input_table_rows = self.sample_table.shape[0]
input_table_colunms = self.sample_table.shape[1]
#print(input_table_rows)
#print(input_table_colunms)
input_table_header =self.sample_table.columns.values.tolist()
self.tableWidget.setColumnCount(input_table_colunms)
self.tableWidget.setRowCount(input_table_rows)
self.tableWidget.setHorizontalHeaderLabels(input_table_header)
for i in range(input_table_rows):
input_table_rows_values = self.sample_table.iloc[[i]]
#print(input_table_rows_values)
input_table_rows_values_array = np.array(input_table_rows_values)
input_table_rows_values_list = input_table_rows_values_array.tolist()[0]
#print(input_table_rows_values_list)
for j in range(input_table_colunms):
input_table_items_list = input_table_rows_values_list[j]
#print(input_table_items_list)
# print(type(input_table_items_list))
input_table_items = str(input_table_items_list)
newItem = QTableWidgetItem(input_table_items)
newItem.setTextAlignment(Qt.AlignHCenter|Qt.AlignVCenter)
self.tableWidget.setItem(i, j, newItem)
else:
self.centralWidget.show()
存在结果数据
def creat_table_show2(self):
if len(path_openfile_name) > 0:
self.result_table = pd.read_csv(path_openfile_name)
#print(input_table)
input_table_rows = self.result_table.shape[0]
input_table_colunms = self.result_table.shape[1]
input_table_header = self.result_table.columns.values.tolist()
self.tableWidget_2.setColumnCount(input_table_colunms)
self.tableWidget_2.setRowCount(input_table_rows)
self.tableWidget_2.setHorizontalHeaderLabels(input_table_header)
for i in range(input_table_rows):
input_table_rows_values = self.result_table.iloc[[i]]
#print(input_table_rows_values)
input_table_rows_values_array = np.array(input_table_rows_values)
input_table_rows_values_list = input_table_rows_values_array.tolist()[0]
#print(input_table_rows_values_list)
for j in range(input_table_colunms):
input_table_items_list = input_table_rows_values_list[j]
input_table_items = str(input_table_items_list)
newItem = QTableWidgetItem(input_table_items)
newItem.setTextAlignment(Qt.AlignHCenter|Qt.AlignVCenter)
self.tableWidget_2.setItem(i, j, newItem)
else:
self.centralWidget.show()
线性模型
class LR_Model():
def __init__(self):
self.Y_num=0
self.X_test=[]
self.Y_test=[]
self.model_list=[]
self.result_all=[]
self.mse_all=[]
self.r_squared_all=[]
self.X_variable = ['A','B','C']
self.Y_variable = ['X','Y','Z']
self.LRModel()
self.PredictModel()
模型准备
def LRModel(self):
# #模型建立及儲存
csvSample=ui.sample_table
csvResult=ui.result_table
csvSample = pd.DataFrame(csvSample, columns=self.X_variable)
csvResult = pd.DataFrame(csvResult, columns=self.Y_variable)
random.seed(123)
X_train,self.X_test,Y_train,self.Y_test = train_test_split(csvSample,csvResult,test_size=0.2)
self.Y_num=len(csvResult.columns)
for i in range(self.Y_num):
lm= LinearRegression()#建模
lm.fit(X_train,Y_train.iloc[:,i])
joblib_file=os.path.abspath('..')+'\Vicky\LR_UI\lm'+format(i)+'.pkl'
joblib.dump(lm,joblib_file)
self.model_list.append(joblib_file)
预测模型和绘图
def PredictModel(self):
for i in range(self.Y_num):
lm=joblib.load(self.model_list[i])
result=lm.predict(self.X_test)
mse = np.mean((result - self.Y_test.iloc[:,i]) ** 2)
self.result_all.append(result)
self.mse_all.append(mse)
r_squared = lm.score(self.X_test, self.Y_test.iloc[:,i])
self.r_squared_all.append(r_squared)
plt.plot(self.Y_variable,self.r_squared,'--o') #定義x,y和圖的樣式
plt.xticks(self.Y_variable,rotation=90)
fig = plt.figure()
ui.rsquare.setScene(fig)
if __name__ == "__main__":`enter code here`
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())