Reputation: 564
I would like to reshape numpy array and send it to neural network for prediction, instead of calling reshape
and create new object (which must be costly) I would like to have faster code - keep function "private" variable/object with proper shape and simply copy values into this object
is it a best pythonic way to create this variable __reshaped_board
like bellow?
whole idea with starting underscores is to signal that this is private variable and do not use it :)
def predict_move(self, board, __reshaped_board=np.zeros([1, 4, 4, 1])):
np.copyto(__reshaped_board[0, :, :, 0], board)
return self.model.predict(__reshaped_board)
one possible solutions is to keep copyto
outside of this function but calling this function in several places would require to make wrapper/decoator to this function
!! I keep in mind that this object will be created once when interpreter will evaluate definition of function and if somewhere I will reassign this reference then original object will be lost
Upvotes: 0
Views: 17
Reputation: 140307
Besides other drawbacks (bad readability, ability for callers to mistakingly passing 2 parameters to your method), your method is going to share this data all across instances of your object. Is that what you want?
what's wrong with instance attribute that will keep your storage all along object life?
def __init__(self):
self.__reshaped_board = np.zeros([1, 4, 4, 1]
def predict_move(self, board):
np.copyto(self.__reshaped_board[0, :, :, 0], board)
return model.predict(self.__reshaped_board)
if you want to share across all instances just define your variable outside __init__
to create a class variable.
class Whatever:
__reshaped_board = np.zeros([1, 4, 4, 1]
Upvotes: 1