Write my own keras layer - python-2.7

I want to write my own keras layer with taking as input a tensor with shape (nb_batch, input_dim) and producing a tensor with shape (nb_batch, context_size, output_dim) . I have write a demo below:
class MyLayer(Layer):
def __init__(self, output_dim, context_size, init="uniform", **kwargs):
self.output_dim = output_dim
self.context_size = context_size
self.init = initializations.get(init)
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
input_dim = input_shape[1]
self.W_vec = self.init(
(self.context_size, input_dim, self.output_dim),
name="W_vec")
self.trainable_weights = [self.W_vec]
super(MyLayer, self).build() # be sure you call this somewhere!
def call(self, x, mask=None):
return K.dot(x, self.W_vec)
# return K.dot(x, self.W)
def get_output_shape_for(self, input_shape):
return (input_shape[0], self.context_size, self.output_dim)
when I ran it , got a error "TypeError: build() takes exactly 2 arguments (1 given)"enter code here

Looks like build needs input shape argument
super(MyLayer, self).build(input_shape) # be sure you call this somewhere!

Related

Python - Overriding a parent variable with a getter/setter

So I have a parent class BaseAdd that I'm trying to subclass. The BaseAdd uses self.left and self.right, I want to use self.nodes to make it easier to access both left and right at once:
class BaseAdd():
def __init__(self, leftright):
self.left = leftright[0]
self.right = leftright[1]
class Add(BaseAdd):
def __init__(self, leftright):
self.nodes = leftright
#property
def left(self):
return self.nodes[0]
#left.setter
def left(self, value):
self.nodes[0] = value
foo = Add(('L', 'R'))
foo.left = "new"
print(foo.left, foo.nodes[0])
>>> ('new', 'L')
The problem is that the setter is never getting called, my hunch is that it's using the BaseAdd.left somehow instead. How can I make the setter properly set the list element?

Update class instance StringVar() from abstract method

I am trying to update 4 StringVar() with values read only after a file is opened. I'm trying to use an abstract method set_values() on the class TestPage to update the 4 StringVar().
...
class TestPage(Tk.Frame):
def __init__(self, parent, *controller):
Tk.Frame.__init__(self, parent)
self.x = Tk.StringVar()
self.y = Tk.StringVar()
self.z = Tk.StringVar()
self.w = Tk.StringVar()
...
x_label = ttk.Label(self, textvariable=self.x)
y_label = ttk.Label(self, textvariable=self.x)
z_label = ttk.Label(self, textvariable=self.x)
w_label = ttk.Label(self, textvariable=self.x)
...
def set_values(self):
self.x.set(some.list[0])
self.y.set(some.other_list.last_index)
self.z.set(some.list_total_entries)
self.w.set('herro worr')
...
TestPage inherets from Tk.Frame. I believe I 'instantiate' the TestPage object when I call show_frame() in the main Application class, which inherets from Tk:
# ***** Tkinter Gui classes *****
# Main container, called by app.gui.Application() in main.py
class Application(Tk.Tk):
def __init__(self, *args, **kwargs):
Tk.Tk.__init__(self, *args, **kwargs)
container = Tk.Frame(self, name='container')
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (EntryPage, TestPage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(EntryPage)
# ***** Change view/frame *****
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
# ***** Open file *****
def open_file(self):
functions.load_file()
...
I would like to call set_values() from my existing load_file function which is in a seperate functions module. I call load_file() to do some populating of graphs, and to parse the file selected for openening.
...
def load_file():
...
if file_name:
gui.TestPage.set_values()
...
...
When I try I get the error:
TypeError: unbound method set_values() must be called with TestPage instance as first argument (got nothing instead)
I need to call the method on the instantiated instance of TestPage, but I do not understand what parameter to supply to set_values() to indicate self or the current instance of TestPage. In the Application class I thought I was instantiating TestPage as frame in the line frame = F(container, self). But I have not been able to reference set_values() using frame either.
I am not even sure this is the best way to do it. I tried to replace the method with binds, events, and also #classmethod and #staticmethod, but with no real succes. Should I be using an abstract method for this?
The values you are changing are attributes of an object, so you need to change them via the instance. In other words, don't pass something to the "self" parameter of a class or abstract function, simply call the function on the object itself.
For example:
...
testfile = TestPage(...)
...
load_file(testpage)
...
def load_file(page):
...
page.set_values()

object inheritance arugment input error

Playing around with inheritance and came across an error stating that I am inputing too many arguments. What could I be doing wrong?
This first file is called media.py
class Video():
def __init__(self, title, duration):
self.title = title
self.duration = duration
class Movie(Video):
def __init__(self, movie_story, movie_poster, trailer_youtube):
Video.__init__(self, title, duration)
self.storyline = movie_story
self.poster_image_url = movie_poster
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
class TvShow(Video):
def __init__(self, season, episode, tv_station):
Video.__init__(self, title, duration)
self.season = season
self.episode = episode
self.tv_station = tv_station
This second file creates the objects.
import fresh_tomatoes
import media
family_guy = media.TvShow("Family Guy",
"2000-Present",
"Fifteen Seasons",
"Twenty-Eight",
"Fox")
print family_guy.title
The terminal output states I'm passing 6 arguments when only 4 may be accepted. Why is that?
Calling the parent __init__ will only invoke it , but you still need to pass in the arguments to it.
So when you invoke __init__ method for TvShow it only expects 3 +1(self) arguments , while you were trying to send more than that. So to solve the issue you just need to increase the number of arguments excepted by the __init__.
class Video():
def __init__(self, title, duration):
self.title = title
self.duration = duration
class Movie(Video):
def __init__(self, movie_story, movie_poster, trailer_youtube):
Video.__init__(self, title, duration)
self.storyline = movie_story
self.poster_image_url = movie_poster
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
class TvShow(Video):
def __init__(self, season, episode, tv_station, title, duration):
Video.__init__(self, title, duration)
self.season = season
self.episode = episode
self.tv_station = tv_station

How to invoke a method from combo box event

I am trying to invoke a method from combo box selected change event
with lambda expression but I am stuck with following error
TypeError: () takes no arguments (1 given)
I think I have passed 1 argument as per the method definition, could somebody please help me where I am wrong
or any other combobox selected change event code will be great help!
please note my code
self.boxWidget[boxName].bind("<<ComboboxSelected>>", lambda:invoke_Setting_Group(self))
def invoke_My_method1(self):
print "expand another window"
I am trying to pass the first class object to the second python script file for variable value assigning easeness.I tried to use this combox event change code without lambda then I noticed that this method is getting called automatically so I used lambda to prevent this automatic method calling
Sorry I am not having the knowledge on lambda expression usage; here I used only to prevent the automatic method execution. Without lambda expression I noticed my combo box function starts automatically, I did not understand why it happens so?
I am using TKinter python 2.6
More Detailed Code of above:
#Main_GUI_Class.py
##----------------------
import sys
class App():
def __init__ (self,master,geometry=None,root=None):
try:
self.master=master
if not root:
self.root=Tkinter.Toplevel(master)
def initUI(self):
try:
self.master.title("GUI")
menubar = Menu(self.master)
self.root.config(menu=menubar)
fileMenu.add_command(label='Open')
submenu_ncss.add_command(label='Model Setting',command=lambda:Combo_Expand_Script.Call_Model_Setting(self))
##----------------------
def main():
r = Tkinter.Tk()
r.withdraw()
r.title("GUI Sample")
r.wm_iconbitmap(Pic1)
v = App(r)
r.mainloop()
if __name__ == "__main__":
main()
##Combo_Expand_Script.py
##-----------------------
import sys
import Tkinter
import Main_GUI_Class
def Call_Model_Setting(self):
try:
self.PopUpWin = Toplevel(bg='#54596d',height=500, width=365)
self.PopUpWin.title("POP UP SETTING")
#Combo Boxs in Pop Up
boxNameGroup="boxSetting"
boxPlaceY=0
for Y in range(4):
boxName=boxNameGroup+str(Y)
if Y == 0:
boxPlaceY=50
else:
boxPlaceY=boxPlaceY+40
self.box_value = StringVar()
self.boxWidget[boxName] = ttk.Combobox(self.PopUpWin, height=1, width=20)
if Y== 0:
self.boxWidget[boxName]['values'] = ('A', 'B')
self.boxWidget[boxName].current(1)
if Y== 1:
self.boxWidget[boxName]['values'] = ('X', 'Y')
self.boxWidget[boxName].bind("<<ComboboxSelected>>",lambda:invoke_Setting_Group(self))
self.boxWidget[boxName].place(x=180, y = boxPlaceY)
#Buttons in Pop Up
self.btnApply = tk.Button(self.PopUpWin,width=10, height=1,text="Apply",relief=FLAT,bg=btn_Bg_Color,command=lambda: treeDataTransfer(self,0))
self.btnApply.pack()
self.btnApply.place(x=75, y = 460)
self.btnCancel = tk.Button(self.PopUpWin,width=10, height=1,text="Cancel",relief=FLAT,command=lambda: deleteTreeNodes(self))
self.btnCancel.pack()
self.btnCancel.place(x=170, y = 460)
except IOError:
print "Error: data error"
def invoke_Setting_Group(self):#, event=None
try:
#self.boxName.current(0)
self.boxWidget["boxSetting3"].current(0)
self.PopUpWin['width']=1050
self.PopUpWin['height']=700
self.btnApply.place(x=500, y = 550)
self.btnCancel.place(x=600, y = 550)
self.txtWidget={}
lsttxtSetting = ['1', '2','3 ','4','5 ','6','7','8','9','10']
for t in range(10):
txtName=txtNameGroupTS+str(t)
if t == 0:
txtPlaceY=120
else:
txtPlaceY=txtPlaceY+30
self.txtWidget[txtName] = Text(self.groupSettingFrame,height=1, width=10,borderwidth = 2)
self.txtWidget[txtName].insert(INSERT, lsttxtSetting[t])
self.txtWidget[txtName].pack()
self.txtWidget[txtName].place(x=200, y = txtPlaceY)
except IOError:
print "Error: Group Settings Popup error"
def turbDataTransferBind(self):
for P in range(0,3):
boxName="boxSetting"+str(X)
dataSettingbox=self.lstTurb[X]+" "+self.boxWidget[boxName].get()
self.root_node_Setting = self.tree.insert( self.root_node_ChildSetting["ChildSettingNode"], 'end', text=dataSettingbox, open=True)
def treeDataTransfer(self,dlgTurbFlag):
self.treeDataTransferBind()
print "data tranfer sucess"
def deleteTreeNodes(self):
print "delete nodes"
command= and bind expect function name - without () and arguments - so in place of
If you use
.bind("<<ComboboxSelected>>", invoke_Setting_Group(self) )
then you use result from invoke_Setting_Group(self) as second argument in .bind(). This way you could dynamicly generate function used as argument in bind
TypeError: () takes no arguments (1 given)
This means you have function function() but python run it as function(arg1)
You run lambda:invoke_Setting_Group(self) but python expects lambda arg1:self.invoke_Setting_Group(self)
You could create function with extra argument
def invoke_My_method1(self, event):
print "expand another window"
print "event:", event, event.widget, event.x, event.y
And then you could use it
.bind("<<ComboboxSelected>>", lambda event:invoke_Setting_Group(self, event))
BTW: it looks strange - you have class App() but in second file you use only functions instead of some class too.

OpenMaya API (python or C++): Given string with DAG name or path, get MDagPath

Test case:
Maya 2014, New scene, create polygonal plane.
Result is a plane named "pPlane1".
If I know the name of an object, here "pPlane1", I want an OpenMaya (OM) MDagPath instance, so that I can pass it to other OM methods.
This works (python), but it requires modifying the selection, and seems cumbersome:
import maya.OpenMaya as om # Version 1
from maya.OpenMaya import MGlobal as omg
# Returns [dagPath]. If none, returns [].
def GetDag(name):
omg.clearSelectionList()
omg.selectByName(name)
selectionList = om.MSelectionList()
omg.getActiveSelectionList(selectionList)
#
iterator = om.MItSelectionList( selectionList, om.MFn.kDagNode )
dagPath = om.MDagPath()
result = []
if not iterator.isDone():
iterator.getDagPath( dagPath )
result = [dagPath]
return result
# ---------- Testing ----------
name = "pPlane1"
result = GetDag(name)
if len(result) > 0:
dagPath = result[0]
...
Is there an easier way? Have I overlooked some class or method in OM?
NOTE: I'm not using pymel, because "import pymel.core as pm" results in an error on my system. That is a question for Autodesk's forums. For now, my goal is to learn to use OpenMaya APIs.
You don't need to use the global selection list, you can create an MSelectionList for the purpose of getting the dag only:
def DagNode ( xform ):
selectionList = OpenMaya.MSelectionList()
try:
selectionList.add( xform )
except:
return None
dagPath = OpenMaya.MDagPath()
selectionList.getDagPath( 0, dagPath )
return dagPath