当前位置: 首页>>代码示例>>Python>>正文


Python Model.Model类代码示例

本文整理汇总了Python中Model.Model的典型用法代码示例。如果您正苦于以下问题:Python Model类的具体用法?Python Model怎么用?Python Model使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Model类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: update

 def update(self, itemid, data):
     assert(self.table_name != '')
     if data.has_key('imagefile') and len(data.imagefile['value']) > 10:
         data['itemtype'] = self.table_name
         data.Imageid = new_image_id = Image().insert(data) # set Imageid for update
         Image().setItemID(new_image_id, itemid)
     Model.update(self,itemid,data)
开发者ID:ajiexw,项目名称:old-zarkpy,代码行数:7,代码来源:ImgLink.py

示例2: runFull

def runFull():
    nbrUserids = KNNSearch.Search([ 1.0 , -1.2,  1.0, 7.79 ], 2000)
    
#     print "Neighbours\n"
#     pprint.pprint(nbrUserids)
    
    split = FeatureSet.featureExtract(nbrUserids)
    
#     print "split\n"
#     pprint.pprint(split)
    
#     testData = getTestData()
#     print "Test Data\n"
#     pprint.pprint(testData);
#     
#     sys.exit(0)
    
    featureSet = split[0][0]
    interested = split[0][1]
    notinterested = split[0][2]
    
    z = [True] * len(featureSet[0])
    w = [True] * len(featureSet[0])
    
    C = 0.03
    #C = 0.3
    model = Model(compress=z, has_none=w, C=C)
    model.fit(featureSet, interested)
    
    testData = getTestData()
    
    result = runModel(model, testData)
    
    print result
开发者ID:ngthanhtrung23,项目名称:Personalized-Events-Recommendation,代码行数:34,代码来源:Flow.py

示例3: __init__

	def __init__(self, amt, radius):
		Model.__init__(self)
		self.source = vtk.vtkAppendPolyData()
		for i in range(amt):
			opX = 1.0
			opY = 1.0
			opZ = 1.0
			if random() > 0.5:
				opX *= -1.0
			if random() > 0.5:
				opY *= -1.0
			if random() > 0.5:
				opZ *= -1.0
			sRad = 0.25 + ( random() * 0.25 )
			x = float(random() * radius) * opX
			y = float(random() * radius) * opY
			z = float(random() * radius) * opZ
			s = vtk.vtkSphereSource()
			s.SetCenter(x,y,z)
			s.SetRadius(float(sRad))
			s.Update()
			self.source.AddInput(s.GetOutput())
		#add center
		s = vtk.vtkSphereSource()
		s.SetCenter(0.0, 0.0, 0.0)
		s.SetRadius(0.5)
		s.Update()
		self.source.AddInput(s.GetOutput())
		self.Update()
开发者ID:aglowacki,项目名称:ScanSimulator,代码行数:29,代码来源:PrimitiveModels.py

示例4: __init__

	def __init__(self, ID, params):
		Model.__init__(self, ID, params)
		h2o.init()

		datadir = os.path.expanduser('~') +'/FSA/data/'
		trainingFile = datadir + params[1][0]
		valFile = datadir + params[1][1]
		testingFile = datadir + params[1][2]


		self.trainData = h2o.import_file(path=trainingFile)
		self.valData = h2o.import_file(path=valFile)
		#self.valData = self.trainData
		self.testData = h2o.import_file(path=testingFile)

		# print self.trainData.col_names()
		# drop the invalid columns
		self.trainData = self.trainData.drop("away_score").drop("home_score")
		self.valData = self.valData.drop("away_score").drop("home_score")
		self.testData = self.testData.drop("away_score").drop("home_score")

		self.params = params

		if self.params[0] == False:
			self.trainData = self.trainData.drop('spread')
			# self.valData   = self.valData.drop('spread')
			self.testData  = self.testData.drop('spread')

		# for h2o, creating the model is the same as training the model so
		# need to hold of here
		self.model = None
开发者ID:Aakash282,项目名称:1ia,代码行数:31,代码来源:h2o_DL.py

示例5: insert

 def insert(self,data):
     if data.has_key('imagefile'):
         assert(data.imagefile.has_key('filename') and data.imagefile.has_key('value'))
         data.imagefile['filetype'] = data.imagefile['filename'].rpartition('.')[2].lower()
         validated_msg = self._insertValidate(data)
         # 如果validated_msg is not None, 则post的图片数据有错
         if validated_msg is not None:
             raise Exception(validated_msg)
         # 插入数据
         new_id = Model.insert(self,data)
         file_path = '%s%d.%s' % (self._getSaveDir(data), new_id, data.imagefile['filetype'])
         # 更新数据库中的uri字段
         self._getDB().update('update '+self.table_name+' set uri=%s where '+self.table_name+'id=%s' ,('%s%d.%s' % (self._getUriBase(data), new_id, data.imagefile['filetype']) ,new_id))
         # 创建文件夹
         if not os.path.exists(file_path.rpartition('/')[0]):
             os.mkdir(file_path.rpartition('/')[0])
         # 保存图片
         with open(file_path,'w') as f:
             f.write(data.imagefile['value'])
         # 压缩图片
         if data.has_key('ifResize'):
             pass
         else:
             self.resizeImage(file_path)
     else:
         new_id = Model.insert(self, data)
     return new_id
开发者ID:ajiexw,项目名称:old-zarkpy,代码行数:27,代码来源:Image.py

示例6: __init__

 def __init__(self, bactDensity, chemDensity, dt, lamda, d, e):
     self.motility = d
     self.chemSens = lamda * bactDensity/(1+e*bactDensity)
     self.liveCycle = 0
     self.chemProd = bactDensity
     self.chemDegr = 1
     Model.__init__(self, bactDensity, chemDensity, dt)
开发者ID:ePaulius,项目名称:Bakt_modeliavimas,代码行数:7,代码来源:DensityDependentSensitivity.py

示例7: Controller

class Controller():
    '''Main class for controlling the operations of the application'''
    def __init__(self):
        #Create a new Tkinter interface
        self.root = Tk()
        #Set an exit protocol
        self.root.protocol("WM_DELETE_WINDOW", self.exitRoot)

        #Create a model
        self.model = Model()
        self.model.loadConfig() #Load default configuration parameters
        #self.view  = View()

        #Start timer thread
        self.txTimer = TimerThread(self, "tmr")
        #Create joystick interface
        self.jsFrame = JoystickFrame(self.root)
        self.joystick = self.jsFrame.getJSHandle()
        self.statusBox = self.jsFrame.getTextHandle()

        #Initialise a telnet rxtx thread for wireless communication
        self.rxThread = RxTxThread(self,"rxtxthread", self.model.getHost(), self.model.getPort())
        if (self.rxThread.getTN() == 0):
            self.statusBox.setText('Could not establish a connection. Terminating...')
            return
        #Start Threads
        self.rxThread.start()
        self.txTimer.start()

        self.statusBox.setText('Connected\n')

        print self.rxThread.getRXText()

        self.rxThread.checkConnection()
        self.root.mainloop()

    def processMessages(self, messages):
        '''Displays received messages in a window box'''
        for msg in messages:
            self.statusBox.setText(msg + '\n')

    def transmitControl(self):
        '''Transmits the coordinates of the joystick if it it being actuated.
        Not complete in interfacing.'''
        if not self.joystick.isReleased():         #Joystick in use
            spdL,spdR =  self.joystick.getSpeeds() #Retrieve position as speeds
            print spdL, spdR
        if self.jsFrame.keyReady():                # WASD Control
            keyChar = self.jsFrame.getJSKey()      # Retrieve valid keypresses
            self.statusBox.setText("Pressed: "+keyChar+"\n")

            self.rxThread.txCmd(keyChar)           #Transmit typed character

    def exitRoot(self):
        '''Protocol for exiting main application'''
        self.rxThread.txCmd('!') #Stop robot
        self.txTimer.pause(True) #Stop timer
        self.rxThread.stop()     #Stop thread
        self.root.destroy()     
开发者ID:jttaufa,项目名称:Rattus2,代码行数:59,代码来源:Controller.py

示例8: __init__

 def __init__(self, controller):
   from collections import OrderedDict
   Model.__init__(self, controller)
   self._currentPlotSet = None
   self._plotSets = OrderedDict()    # key: plotSet ID, value: instance of XYPlotSetModel. We use an OrderedDict so that
                                     # when removing elemetns, we can easily re-select the last-but-one.
   self._lockRepaint = False  # if True, repaint routines are blocked.
   self._plotSetsRepaint = set() # plot waiting for repaint/update while repaint is locked
开发者ID:FedoraScientific,项目名称:salome-gui,代码行数:8,代码来源:PlotManager.py

示例9: View

class Controller:
    """ a 'middleman' between the View (visual aspects) and the Model (information) of the application.
        It ensures decoupling between both.
    """

    def __init__(self, app):
        # initialize the model and view
        # * The model handles all the data, and signal-related operations
        # * The view handles all the data visualization
        self.model = Model()
        self.view = View()

        # subscribe to messages sent by the view
        pub.subscribe(self.parse_file, "FILE PATH CHANGED")
        pub.subscribe(self.reprocess_fft, "FFT CONTROLS CHANGED")

        # subscribe to messages sent by the model
        pub.subscribe(self.signal_changed, "SIGNAL CHANGED")
        pub.subscribe(self.signal_changed, "FFT CHANGED")

        self.view.Show()

    def parse_file(self, message):
        """
        Handles "FILE PATH CHANGED" messages, send by the View. It tells the model to parse a new file.
        message.data should contain the path of the new file
        """
        try:
            self.model.parse_file(message.data)

        except Exception as exception:
            self.view.show_exception(
                "Error reading file", "The following error happened while reading the file:\n%s" % str(exception)
            )

    def reprocess_fft(self, message):
        """
        Handler "FFT CONTROLS CHANGED" messages from the View. It tells the model to re-process the fft.
        message.data should contain the array [window, slices, max_peaks]
        """
        self.model.reprocess_fft(*message.data)

    def signal_changed(self, message):
        """
        Handles "SIGNAL CHANGED" messages sent by the model. Tells the view to update itself.
        message is ignored
        """
        self.view.signal_changed(self.model)

    def fft_changed(self, message):
        """
        Handles "FFT CHANGED" messages sent by the model. Tells the view to update itself.
        message is ignored
        """
        self.view.fft_changed(self.model)
开发者ID:splendeo,项目名称:adctest,代码行数:55,代码来源:Controller.py

示例10: generateJson

	def generateJson(self,outputDictionary,analyzeData,key):
		inner_json_list = []
		questions = analyzeData[key]
		for question in questions:
			answers = outputDictionary[question]
			dict_of_answers =  dict(Counter(answers))
			DataModel = Model(key,question,dict_of_answers) 	
			DataModelJson = DataModel.toJson()
			inner_json_list.append(DataModelJson)
		inner_json = json.dumps({'data':inner_json_list})	
		return inner_json
开发者ID:nischalhp,项目名称:Feedlyze,代码行数:11,代码来源:generatejson.py

示例11: Controller

class Controller(object):
  def __init__(self):
    self.model = Model()
    self.view = View()

  def run(self):
    name = self.view.welcome()
    if name == 'Ken':
      print(self.model.say_hello(name))
    else:
      print(self.model.say_bye())
开发者ID:mendoncakr,项目名称:testing,代码行数:11,代码来源:Controller.py

示例12: __init__

 def __init__(self,root='',database_path='data/',database_name='mydatabase.db'):
     Model.__init__(self,root,database_path,database_name)
     self.name = 'courses'
     self.columns["name"] = 'TEXT'
     self.columns["semester"] = 'TEXT'
     self.columns["type"] = 'TEXT'
     self.columns["lecture_group"] = 'TEXT'
     self.columns["day"] = 'TEXT'
     self.columns["start_time"] = 'TEXT'
     self.columns["end_time"] = 'TEXT'
     self.columns["venue"] = 'TEXT'
开发者ID:jamiewannenburg,项目名称:TimeTable,代码行数:11,代码来源:AllCoursesDB.py

示例13: __reBuildViewTree

 def __reBuildViewTree(self):
     """Creates a new Model using the current folder"""
     self.view.filesTree.buttons.set_sensitive(False)
     if len(self.folders) == 1:
         self.model = Model([self.folders[0]], self.view.progressBar)
     else:
         self.model = Model(self.folders, self.view.progressBar, group=True)
     self.saveCache()
     self.__refreshViewTree()
     self.view.vbox.remove(self.view.progressBar)
     self.model.lastUpdate = time.time()
     self.view.filesTree.buttons.set_sensitive(True)
开发者ID:andrebask,项目名称:cometsound,代码行数:12,代码来源:Controller.py

示例14: __init__

class Controller:
    def __init__(self):
        self.model = Model()
        self.view = View()
        self.firstTime = True
        self.result = 0.0
        self.a = 0.0
        self.b = 0.0
        self.usePrev = 0
    
    def run(self):
        while True:
            self.view.printMenu()
            selection = self.view.inputSelection()
            if selection <= 0:
                continue
            elif selection == 5:
                self.view.terminate()
                return
            elif not self.firstTime:
                if self.model.isNumber(self.result):
                    self.usePrev = self.view.usePrevious(self.result)
                else:
                    self.usePrev = 0
            else:
                self.firstTime = False
            if self.usePrev == 0:
                # Enter both operands
                self.a = self.view.oneOp(1)
                self.b = self.view.oneOp(2)
            elif self.usePrev == 1:
                # Enter second operand
                self.a = self.result
                self.view.printOp(1, self.a)
                self.b = self.view.oneOp(2)
            elif self.usePrev == 2:
                # Enter first operand
                self.a = self.view.oneOp(1)
                self.b = self.result
                self.view.printOp(2, self.b)
            else:
                # ERROR: Should never reach this block
                self.view.printInvalidArg()
                continue
            self.view.printCalc(selection, self.a, self.b)
            self.result = self.model.calculate(selection, self.a, self.b)
            self.view.printResult(self.result)
            if self.view.anotherOp():
                continue
            else:
                return
开发者ID:krauskc,项目名称:EECS448-Lab09,代码行数:51,代码来源:Controller.py

示例15: test1

def test1(transition_samples):
    def momentum(current, previous, decay):
        new = current + decay * previous
        return new

    w_init = [-1.3, -1.2, -1, -0.8, -0.8, -1.4, -1.5, -3.0, -2.0, -1.0, -0.3, -0.5, -8.0, -3.0]

    # w_init /=np.linalg.norm(w_init)
    steps = 10
    diff = []
    m = DiscModel()
    model = Model(m, w_init)
    initial_transition = model.transition_f
    policy = caus_ent_backward(model.transition, model.reward_f, 3, steps, conv=0.1, z_states=None)
    start_states = [400, 45, 65, 67, 87, 98, 12, 34, 54, 67, 54, 32, 34, 56, 80, 200, 100, 150]
    # statistics = [generate_test_statistic(policy,model,start_state,steps) for start_state in start_states]
    statistics, dt_states_base = generate_test_statistic(policy, model, start_states, steps)

    model.w = [-1, -1.2, -1, -0.8, -0.8, -4.4, -2, -2.0, -3.0, -1.0, -2.3, -1.5, -4.0, -3.0]
    # model.w =[-2.,-0.6,-4.,-4.,-3.,-5.,-2.,-0.5,-4.,-0.8,-4.,-3.,-5.]
    # model.w /=np.linalg.norm(model.w)
    model.buildRewardFunction()
    if transition_samples != 1:
        model.buildTransitionFunction(transition_samples, learn=False)
    transition_diff = np.sum(np.absolute(initial_transition - model.transition_f))
    initial_transition = 0
    gamma = 0.04
    iterations = 110
    for i in range(iterations):
        policy2 = caus_ent_backward(model.transition, model.reward_f, 1, steps, conv=0.1, z_states=None)
        # gradients = np.array([(statistics[j] - generate_test_statistic(policy,model,start_state,steps)) for j,start_state in enumerate(start_states)])
        state_freq, dt_states_train = generate_test_statistic(policy2, model, start_states, steps)
        gradients = statistics - state_freq
        if i == 0:
            image = np.absolute(dt_states_train - dt_states_base)
            gradient = gradients
        else:
            gradient = momentum(gradients, prev, 0.8)
            image = np.append(image, np.absolute(dt_states_train - dt_states_base), axis=1)
        model.w = model.w * np.exp(-gamma * gradient)
        # model.w /=np.linalg.norm(model.w)
        prev = gradient
        gamma = gamma * 1.04

        model.buildRewardFunction()
        print "Iteration", i
        print "Gradient", gradient
        print "New Weights", model.w
        print "Real weights", w_init
        print "Policy Difference", np.sum(np.sum(np.absolute(policy - policy2)))
        diff.append(np.sum(np.sum(np.absolute(policy - policy2))))
    policy_diff = np.sum(np.sum(np.absolute(policy - policy2)))
    w_diff = np.absolute(w_init - model.w)
    grad = np.sum(np.absolute(gradient))
    return image, diff, grad, w_diff, transition_diff
开发者ID:KyriacosShiarli,项目名称:MDP,代码行数:55,代码来源:learn_test.py


注:本文中的Model.Model类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。