2016-08-16 4 views
0

저는 파이썬에서 클래스를 사용하는 것에 익숙하지 않으며 루프에서 클래스를 사용하는 방법/리소스를 참조 할 수있는 몇 가지 지침을 사용할 수 있습니다.루프 - 파이썬에서 클래스 사용하기

샘플 데이터 : 여기

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) 
df2 = pd.DataFrame(np.random.randint(0, 1, size=(100, 1)), columns=list('E')) 
df['E']= df2 

는 클래스 외부의 코드입니다 :

styles = [1, 3, 7] 

def train_model(X, y): 
    clf = LogisticRegression(random_state=0, C=1, penalty='l1') 
    clf.fit(X, y) 

for value in styles: 
    X = df[['A', 
      'B', 
      'C']][df['D']==value] 
    y = df['E'][df['D']==value] 
    train_model(X, y) 

내가 지금처럼 클래스로이 번역해야합니다

class BaseTrainer(object): 
""" Abstract class to define run order """ 

    def run(self): 
     self.import_training_data() 
     for value in [1, 3, 7]: 
      self.extract_variables(value) 
      self.train_model() 
      # I think there's a better way to do this 
      if value = 1: 
       pickle_model(self.model, self.model_file) 
      if value = 3: 
       pickle_model(self.model, self.model_file2) 
      if value = 7: 
       pickle_model(self.model, self.model_file3) 


class ModelTrainer(BaseTrainer): 
""" Class to train model for predicting Traits of Customers """ 

    def __init__(self): 
     self.model_file = '/wayfair/mnt/crunch_buckets/central/data_science/customer_style/train_modern.pkl' 
     self.model_file2 = '/wayfair/mnt/crunch_buckets/central/data_science/customer_style/train_traditional.pkl' 
     self.model_file3 = '/wayfair/mnt/crunch_buckets/central/data_science/customer_style/train_rustic.pkl' 

def import_training_data(self): 
    _execute_vertica_query('get_training_data') 

    self.df = _read_data('training_data.csv') 
    self.df.columns = [['CuID', 'StyID', 'StyName', 
    'Filter', 'PropItemsViewed', 'PropItemsOrdered', 'DaysSinceView']] 

def extract_variables(self, value): 
    # Take subset of columns for training purposes (remove CuID, Segment) 
    self.X = self.df[['PropItemsViewed', 'PropItemsOrdered', 
    'DaysSinceView']][df['StyID']==value] 

    y = self.df[['Filter']][df['StyID']==value] 
    self.y = y.flatten() 

def train_model(self): 
    self.model = LogisticRegression(C=1, penalty='l1') 

    self.model.fit(self.X, self.y) 

나는 생각한다 그것을 구조화하거나 스타일 목록의 세 가지 다른 값을 통해 실행하는 더 좋은 방법이 있어야합니다. 그러나 나는 이것을 개선하기 위해 무엇을 찾아야할지조차 모른다. 어떤 제안, 포인터, 등 감사하겠습니다!

답변

0

그것을 할 우아한 방법은, 그것은 예를 들어

을 개선 할 수있는 디자인에 관해서는 zip

def run(self): 
    self.import_training_data() 
    for value,model_file in zip([1, 3, 7],[self.model_file, self.model_file2, self.model_file3]): 
     self.extract_variables(value) 
     self.train_model() 

     pickle_model(self.model, model_file) 

사용하여 동시에 두 목록을 통해 반복 A와 모델 파일을 정의하는 것입니다 직접 목록 :

self.model_list = map(lambda x : os.path.join('/wayfair/mnt/crunch_buckets/central/data_science/customer_style',x),['train_modern.pkl','train_traditional','train_rustic.pkl']) 

주는 :

def run(self): 
    self.import_training_data() 
    for value,model_file in zip([1, 3, 7],self.model_file_list): 
     self.extract_variables(value) 
     self.train_model() 
+0

대단합니다. 고마워요! – user2573355

0

당신은이 질문에 대답 않도록

files = [self.model_file, self.model_file2, self.model_file3] 
values = [1 ,5 ,7] 
for n in range(len(value)): 
    pickle_model(self.model, files[n]) 

처럼 파일을 열거 할 수 있을까?

+0

파티. 하지만 나는 더 분명했을 수 있습니다. 내가했던 것처럼 "def run"에 루프를 포함해야합니까, 아니면 전체적으로 클래스를 사용하여 목록을 반복 할 수 있습니까? 기본적으로 클래스의 여러 함수를 반복해야하는이 유형의 루프를 포함하는 가장 좋은 방법은 무엇입니까? 감사! – user2573355