从“主程序”获取所有预定义变量的子程序 [英] Subprogram which takes all the predefined variables from a "main program"

查看:164
本文介绍了从“主程序”获取所有预定义变量的子程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的困难:
因为我正在用pyqt编写图形用户界面,所以我想构建我的工作:

GUI应该从我的scikitlearn计算中调用不同的子程序。

我有一个按钮PRED用于预测,另一个用于一些称为PLOT p>

当点击这些按钮时,会调用一个python计算程序,并使用

  class MyDia(QtGui.QDialog,Dlg):
def __init __(self):
QtGui.QDialog .__ init __(self)
self.setupUi(self)

self.connect(self.buttonOPLOT,
QtCore.SIGNAL(clicked()),self.onPLOT)
self.connect(self.buttonPRED,
QtCore.SIGNAL(clicked ()),self.onPRED)
def onPRED
if self.button_1.checkState():
a = 1
if self.button_2.checkState():
a = 2
query = np.zeros((1,18 ))
在范围内(0,18,1):
try:
query [0,i] = float(self.tableWidget.item(0,i).text( ))

###当用户做出选择时,数据会从sk_calc导入main,pred
main()#after main,pred执行此操作
(a)#a是回归的某个参数(我尽量保持简单)

目前我在不同的文件中使用不同的计算程序sk_plot和sk_pred - 目标是只更改一个...其中 main在指定作业(PRED或PLOT ...)之前运行。

UNIQUE计算程序应该看起来/结构类似于此:

  def main():
import numpy as np
从scikitlearn导入#all模块

DATA = np.genfromtxt(direc +\some.csv,delimiter =;,dtype = float,skip_header = 2,usecols =范围(0,22))#使用我的数据读取csv文件

特征= DATA [:,4:22]#我的DATA
targets = DATA [ :,1]#我的DATA

的Ysvr_rbf = SVR(kernel ='rbf',C = 2e4,gamma = a)#使用DATA #a的回归来自用户点击
svr_rbf.fit(features,targets).predict(features)#scikit-learn的方法

def pred():
Prediction = svr_rbf.predict(query)
#query由用户在gui中定义,键入一​​些值
print(Pred_ic)

def plot():
#...使用pylab但不同的东西DATA功能和目标

你看到我希望某些代码(main)运行时无需点击按钮就可以点击
,之后应该执行一部分计算程序,它具有main()中定义的变量和DATA。

我是否使用类?如果是的话,我必须记住什么?什么是这个步骤......

解决方案

你是正确的,类是一个很好的方式来构建你的代码。 p>

一个类可以保持自己的状态,并且具有预定义的行为,可以通过方法和属性来操纵。



但是,我不会给出关于使用类的一般建议,因为这是关于特定编程问题的stackoverflow的主题。如果你想知道更多,只需做一个关于这个主题的python书籍/教程的网络搜索 - 那里有几十个好的。



相反,我会尽我所能重新构建您的问题中的代码来使用一个类。下面的代码仅用于说明目的。不是意味着一个完整的,可运行的例子。希望有足够的提示让您知道如何进行:

gui.py

  import numpy as np 
import sk_calc
$ b $ class MyDia(QtGui.QDialog,Dlg):
def __init__ (self):
QtGui.QDialog .__ init __(self)
self.setupUi(self)
self.buttonOPLOT.clicked.connect(self.onPLOT)
self.buttonPRED。 clicked.connect(self.onPRED)

def onPRED(self):
if self.button_1.isChecked():
a = 1
elif self.button_2。 isChecked():
a = 2
else:
a = 0
query = np.zeros((1,18))
#... etc

#当用户做出选择时,数据将执行

#创建Calc类的一个实例,从gui
中传入
#参数calc = sk_calc.Calc(a)

#调用实例的方法,传递i n参数
#从gui中接收返回值
prediction = calc.pred(查询)

#calc.plot()...等

sk_calc.py

  import numpy as np $ b $ from sklearn.svm import SVR 
#从scikitlearn导入其他内容

DEFAULT_CSVPATH ='path / to / some / file.csv'

class Calc(object):
def __init __(self,a,csvpath = None):
如果csvpath是None:
csvpath = DEFAULT_CSVPATH
#用我的数据在csv文件中读取
self.data = np.genfromtxt(
csvpath,delimiter =';',dtype = float,
skip_header = 2,usecols =范围(0,22))

self.features = data [:,4:22]#我的DATA
的Xself.targets = data [:,1] #我的DATA的Y

#使用DATA进行回归,a来自用户单击
self.svr_rbf = SVR(kernel ='r bf',C = 2e4,gamma = a)

#scikit-learn方法
self.svr_rbf.fit(特征,目标).predict(特征)

def pred(self,query):
#query由用户在gui中定义的一些值中输入
prediction = self.svr_rbf.predict(查询)
返回预测

def plot(self):
#...使用带有DATA功能和目标的pylab
#self.data ...
#self.features ...


i have a hard time with this: As i am programming GUIs with pyqt i want to structure my work:

I have several buttons on my GUI that should call "different subprograms" from my calculations with scikitlearn.

i have a button "PRED" for Prediction, another one for some plots called "PLOT"

when these buttons are clicked a python "calculation program" is called with

class MyDia(QtGui.QDialog, Dlg): 
    def __init__(self): 
        QtGui.QDialog.__init__(self) 
        self.setupUi(self)

        self.connect(self.buttonOPLOT, 
                QtCore.SIGNAL("clicked()"), self.onPLOT)    
        self.connect(self.buttonPRED, 
                QtCore.SIGNAL("clicked()"), self.onPRED)
    def onPRED
        if self.button_1.checkState(): 
            a=1
        if self.button_2.checkState(): 
            a=2
        query=np.zeros((1,18))
        for i in range(0,18,1):
            try:
                query[0,i]= float(self.tableWidget.item(0,i).text())

        ### when user has made his choices the data goes do this
        from sk_calc import main, pred
        main() #after main, "pred" should be called with some definitions that 
        have been made in "main"
        pred(a) #a is some parameter of a regression (i try to keep it easy)

at the moment i use different "calculation" programms "sk_plot and sk_pred" in different files- the goal is to change only ONE... where "main" runs before the specifiv job( PRED or PLOT...)

THE UNIQUE calculation program should "look"/ be structured similar to this:

def main():
    import numpy as np
    import #all modules from scikitlearn

    DATA=np.genfromtxt(direc+"\some.csv",delimiter=";",dtype=float ,skip_header=2, usecols=range(0,22)) #reading in a csv file with my data

    features=DATA[:,4:22]#the "X" of my DATA
    targets=DATA[:,1]#the "Y" of my DATA

    svr_rbf = SVR(kernel='rbf', C=2e4, gamma=a) #Regression using the DATA #a comes from user click
    svr_rbf.fit(features, targets).predict(features)# method of scikit-learn

        def pred():
            Prediction=svr_rbf.predict(query)
            #query is defined by the user in the gui typing in some values 
            print(Pred_ic)

        def plot():
            #... something different using pylab but ALSO DATA features and targets

You See that i want that some code (main) runs unindependantly whick button is clicked ,afterwards a part of the "calculation program" should be executed that has variables and DATA defined in main().

Do i use a class for this? If yes, what do i have to keep in mind? What are the steps for this...

解决方案

You are correct that classes are a good way to structure your code.

A class can maintain its own state, and has pre-defined behaviour that can be manipulated through methods and properties.

However, I am not going to give general advice about using classes, because that is off-topic for stackoverflow, which focuses on specific programming problems. If you want to know more, just do a web-search for python books/tutorials on the subject - there are dozens of good ones out there.

Instead, I will do my best to re-structure the code in your question to use a class. The code below is for illustration purposes only. It is not meant to be a complete, runnable example. Hopefully there are enough hints there to give you an idea of how to proceed:

gui.py:

import numpy as np
import sk_calc

class MyDia(QtGui.QDialog, Dlg):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.buttonOPLOT.clicked.connect(self.onPLOT)
        self.buttonPRED.clicked.connect(self.onPRED)

    def onPRED(self):
        if self.button_1.isChecked():
            a = 1
        elif self.button_2.isChecked():
            a = 2
        else:
            a = 0
        query = np.zeros((1,18))
        # ... etc

        # when user has made his choices the data goes do this

        # create an instance of the Calc class, passing in
        # parameters from the gui
        calc = sk_calc.Calc(a)

        # call methods of the instance, passing in parameters
        # from the gui, and receiving returned values
        prediction = calc.pred(query)

        # calc.plot() ... etc

sk_calc.py:

import numpy as np
from sklearn.svm import SVR
# import other stuff from scikitlearn

DEFAULT_CSVPATH = 'path/to/some/file.csv'

class Calc(object):
    def __init__(self, a, csvpath=None):
        if csvpath is None:
            csvpath = DEFAULT_CSVPATH
        # reading in a csv file with my data
        self.data = np.genfromtxt(
            csvpath , delimiter=';', dtype=float,
            skip_header=2, usecols=range(0,22))

        self.features = data[:,4:22] # the "X" of my DATA
        self.targets = data[:,1]     # the "Y" of my DATA

        # Regression using the DATA, a comes from user click
        self.svr_rbf = SVR(kernel='rbf', C=2e4, gamma=a)

        # method of scikit-learn
        self.svr_rbf.fit(features, targets).predict(features)

    def pred(self, query):
        # query is defined by the user in the gui typing in some values
        prediction = self.svr_rbf.predict(query)
        return prediction

    def plot(self):
        # ... use pylab with DATA features and targets
        # self.data ...
        # self.features ...

这篇关于从“主程序”获取所有预定义变量的子程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆