Как я могу найти и выбрать определенный текстовый файл для чтения в GUI нейронных сетях для обучения нейронной сети? - PullRequest
0 голосов
/ 03 февраля 2020

Я создаю GUI код нейронной сети python для CSTR, используя модуль sklearn, который имеет два входа и один выход. Входами являются температура охлаждения T c и расход на входе qin. Выход - это просто температура. Я уже сохранил входные и выходные данные в текстовые файлы и успешно запустил код GUI NN Python. Однако я хочу улучшить свой код GUI NN и хочу, чтобы пользователь сам выбирал текстовый файл для чтения; У меня уже есть текстовые файлы T c, qin и T. У меня есть 3 кнопки в верхней части моего приложения GUI: ввод T c, ввод Qin, вывод T. Например, когда я нажимаю кнопку Input T c, я хочу GUI, чтобы открыть новое окно. где пользователь может выбрать и выбрать нужный текстовый файл.

Чтобы сделать вещи более понятными, это близко к тому, когда человек хочет вложить файл в электронное письмо, как только он / она нажимает кнопку присоединить, пользователь имеет возможность выбрать любой файл, который он / она хочет .

Как это можно сделать в GUI на Python?

Ниже приведен мой существующий код Python для редактирования. Вместо того, чтобы указывать текстовые файлы непосредственно в коде, я хочу, чтобы у пользователя была возможность выбирать текстовые файлы.

import tkinter as tk #to use Tkinter
from sklearn.neural_network import MLPRegressor #to solve the NN
import pandas
#from sknn.mlp import Classifier
import numpy as np
from tkinter import *
import tkinter.messagebox #import a message box that will be displayed
import csv #needed to open and read text files

# Create the main window
root = tk.Tk()

#this example represents a two input &one output NN application

#x1 represent the cooling T (Manipulated Variable of CSTR)
#x2 represents the inlet flowrate

ReadInput1= False # used for test Tc input button ; turns to true if the button is pressed

ReadInput2= False # used for test qin input button ; turns to true if the button is pressed

ReadOutput= False # used for test output button ; turns to true if the button is pressed

def readinput1():

    global ReadInput1
    x1=np.empty(401)#initialize to empty ;to be filled

    #read data from Tc_Training txt file

    with open("Tc data.txt","r") as csv_file:

        count=0

        csv_reader=csv.reader(csv_file)
        for row in csv_reader:
            i=float(row[0])#change from string to float type
            x1[count]=i #updates x array
            count +=1 # increment of 1 to get the number of total values

        x1=x1.reshape(401,1) #change all to 1 row and 401 columns (this is the format needed)

    ReadInput1=True #becomes true if the button test input is pressed

    if ReadInput1==True:# if the button read output is pressed

        print("The Tc input data for training is now read")

    return x1

def readinput2():

    global ReadInput2

    x2=np.empty(401)#initialize to empty ;to be filled

    #read data from Tc_Training txt file

    with open("q data.txt","r") as csv_file:

        count=0

        csv_reader=csv.reader(csv_file)
        for row in csv_reader:
            i=float(row[0])#change from string to float type
            x2[count]=i #updates x array
            count +=1 # increment of 1 to get the number of total values

        x2=x2.reshape(401,1) #change all to 1 row and 401 columns (this is the format needed)

    ReadInput2=True #becomes true if the button test input is pressed

    if ReadInput2==True:# if the button read output is pressed

        print("The qin input data for training is now read")

    return x2

#y represents the Temperature of CSTR

def readoutput():

    global ReadOutput
    y=np.empty(401) #initialize to empty ;to be filled

        #read data from T_training txt file
    with open("T data.txt","r") as csv_file:

        count=0

        csv_reader=csv.reader(csv_file)
        for row in csv_reader:
            i=float(row[0])#change from string to float type
            y[count]=i #update y array
            count +=1 # increment of 1 to get the number of total values

    y=np.array(y).ravel() #ravel is to convert to a single column

    ReadOutput=True #becomes true if the button test input is pressed

    if ReadOutput==True:# if the button read output is pressed

        print("The output data for training is now read")

    return y

flag=False #this value should be false if the test button is not pressed and true if pressed

def test(): #to do the testing for the neural network

    if ReadOutput==True and ReadInput1==True and ReadInput2==True: # if the buttons read input and read output are pressed

        global flag #should put it as a global so that its value can be saved when the function is called (the button is pressed);
        #if the button is not pressed the variable should be remained as false

        x1=readinput1()
        x2=readinput2()
        y=readoutput()

        x=np.hstack((x1,x2))# combines the x1 and x2 arrays into 1 so that we can have 1 combined input

        numb = entry_3.get() #for the number of max iterations

        numb=int(numb)#converts the text given to a number

        numc = entry_4.get()#for the number of neurons in hidden layer #1

        numc=int(numc)#converts the text given to a number

        numd = entry_5.get() #for the number of neurons in hidden layer #2

        numd=int(numd)#converts the text given to a number

        nume = entry_6.get()#for the number of neurons in hidden layer #3

        nume=int(nume)#converts the text given to a number

        numf = entry_7.get() #for the number of neurons in hidden layer #4

        numf=int(numf)#converts the text given to a number


        if flag==False: #i want to print the following only once and avoid printing them twice (when testing and when training) ; thus
        #the flag value is used; before testing is done; the value is false and they are printed, when testing is done the value become true
        #and thus they are not printed again. This achieves our objective.

            print('the max number of iterations is:',numb)
            print('the number of neurons in the 1st hidden layer is:',numc)
            print('the number of neurons in the 2nd hidden layer is:',numd)
            print('the number of neurons in the 3rd hidden layer is:',nume)
            print('the number of neurons in the 4th hidden layer is:',numf)


        nn = MLPRegressor(
            hidden_layer_sizes=(5,5,5,5),  activation='relu', solver='adam',random_state=1,max_iter=10000)

        n = nn.fit(x, y)

        flag=True #becomes true if testing is done (if the test button is pressed)

        return nn #return the nn function fitting used later for testing

    else:
        print("The input and the output for testing are not read")

def train():

    if flag==True: #if the test button is pressed

        nn=test() #take the Neural Network fitting function if the testing is done

        numa = entry_1.get() #for the Tc training input

        numa=int(numa) #converts the text given to a number

        num = entry_2.get() #for the Qin training input

        num=int(num)#converts the text given to a number

        print('the Cooling Temperature testing input is:',numa,' K')

        print('the inlet flowrate testing input is:',num,' m^3/s')

        y=np.hstack((numa,num))# combines the Tc and qin into one array 

        test_y=nn.predict([y])#predicts the output of T for the given Tc and qin


        print('the value of the predicted Temperature is:',test_y,' K')

        #to show the results on GUI

        output= "The result is:"
        output+=" T= %d K"%(test_y)#takes the output of test_y
        output+= " for the testing inputs "
        tkinter.messagebox.showinfo("Results",output)#display output in a box when the problem is executed
        #and data are filled by the user

    if flag==False: #if testing is not done

        print("No testing is performed")

# Create the widgets
btn_1 = tk.Button(root, text = "Input Tc data", command = readinput1)#when pressed, the input of Tc for testing is done
btn_2 = tk.Button(root, text = "Input Qin data", command = readinput2)#when pressed, the input of qin for testing is done
btn_3 = tk.Button(root, text = "OutputData", command = readoutput)#when pressed, the output for testing is done


entry_3=tk.Entry(root)#specify that entry_3 should be filled by the user
entry_4=tk.Entry(root)
entry_5=tk.Entry(root)
entry_6=tk.Entry(root)
entry_7=tk.Entry(root)

btn_4 = tk.Button(root, text = "Perform Testing", command = test)#when pressed, testing is done

entry_1 = tk.Entry(root)
entry_2 = tk.Entry(root)

btn_5 = tk.Button(root, text = "Predict Output", command = train)#when pressed, training is done

var1 = StringVar()#indicates that the variable is of string type
label_1 = Label( root, textvariable=var1 )#Label Widget
var1.set("The number of maximum iterations (e.g. 500) ")#indicates the string variable

var2 = StringVar()#indicates that the variable is of string type
label_2 = Label( root, textvariable=var2 )#Label Widget


var2.set("The number of neurons in the first hidden layer (e.g. 3)")#indicates the string variable

var3 = StringVar()#indicates that the variable is of string type
label_3 = Label( root, textvariable=var3 )#Label Widget
var3.set("The number of neurons in the second hidden layer(e.g. 3)")#indicates the string variable

var4 = StringVar()#indicates that the variable is of string type
label_4 = Label( root, textvariable=var4 )#Label Widget
var4.set("The number of neurons in the third hidden layer (e.g. 3)")#indicates the string variable

var5 = StringVar()#indicates that the variable is of string type
label_5 = Label( root, textvariable=var5 )#Label Widget
var5.set("The number of neurons in the fourth hidden layer(e.g. 3)")#indicates the string variable

var6 = StringVar()#indicates that the variable is of string type
label_6 = Label( root, textvariable=var6 )#Label Widget
var6.set("The testing input Tc")#indicates the string variable

var7 = StringVar()#indicates that the variable is of string type
label_7 = Label( root, textvariable=var7 )#Label Widget
var7.set("The testing input Qin")#indicates the string variable

#if training is attempted before doing testing( before pressing the test button); the code should tell us that
#we did not do testing.

# Grid is used to add the widgets to root
#locate labels,buttons and user-input numbers

btn_1.grid(row=0,column=0)
btn_2.grid(row=0,column=1)
btn_3.grid(row=0,column=2)

label_1.grid(row = 1, column = 0) #puts the 1st label the no of max iterations in the first row and and 1st column 
label_2.grid(row = 2, column = 0)
label_3.grid(row = 3, column = 0)
label_4.grid(row = 4, column = 0)
label_5.grid(row = 5, column = 0)

btn_4.grid(row=6,column=1)

label_6.grid(row = 7, column = 0)
label_7.grid(row = 8, column = 0)

entry_3.grid(row = 1, column = 1) #puts the no of max iterations in the first row and and 2nd column near its label
entry_4.grid(row = 2, column = 1)
entry_5.grid(row = 3, column = 1)
entry_6.grid(row = 4, column = 1)
entry_7.grid(row = 5, column = 1)
entry_1.grid(row = 7, column = 1)
entry_2.grid(row = 8, column = 1)

btn_5.grid(row = 9, column = 1)#put the button solve for the data given in the last row 

root.mainloop() #open the main window

Спасибо!

...