Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

indenta este codigo: class RegresionLogisticaMiniBatch(): def…

  1. User

    indenta este codigo: class RegresionLogisticaMiniBatch():

    def init(self,rate=0.1,rate_decay=False,n_epochs=100, batch_tam=64):

    self.rate = rate self.rate_decay = rate_decay self.n_epochs = n_epochs self.batch_tam = batch_tam

    def entrena(self,X,y,Xv=None,yv=None,n_epochs=100,salida_epoch=False, early_stopping=False,paciencia=3):

    self.n_clases = np.unique(y).size self.clases = np.unique(y).tolist()

    if not self.clases[1] == 1: self.clases.reverse() X = X[:,::-1] if not Xv is None: Xv = Xv[:,::-1]

    if y.ndim == 1: y = y.reshape((-1,1))

    normalizar datos

    X_max, X_min = X.max(axis=0), X.min(axis=0) self.X_max, self.X_min = X_max, X_min X = (X - self.X_min)/(self.X_max - self.X_min + 1e-8) if not Xv is None: Xv = (Xv - self.X_min)/(self.X_max - self.X_min + 1e-8)

    bias = np.ones((X.shape[0],1)) X = np.hstack((bias,X)) if not Xv is None: bias = np.ones((Xv.shape[0],1)) Xv = np.hstack((bias,Xv))

    self.w = np.random.rand(X.shape[1],self.n_clases)-0.5

    idx = np.arange(X.shape[0]) batches = np.array_split(idx,X.shape[0]/self.batch_tam)

    EC_list = [] rendimiento_list = [] ECv_list = [] rendimiento_v_list = []

    best_Ecv = np.inf n_epochs_sin_mejora = 0

    for epoch in range(n_epochs):

    rate_epoch = self.rate*((1+epoch)**(-1))(self.rate_decay==True)

    for batch_i in batches: Xt = X[batch_i,:] yt = y[batch_i,:]

    o = Xt.dot(self.w) s = expit(o)

    error = yt-s grad = Xt.T.dot(error)

    self.w = self.w + rate_epochgrad

    if salida_epoch or early_stopping:

    EC = -np.mean( np.where( y==1, np.log(s), np.log(1-s) ) ) EC_list.append(EC)

    rendimiento = np.mean( (self.clasifica(X)>0.5) == y ) rendimiento_list.append(rendimiento)

    if not Xv is None: ov = Xv.dot(self.w) sv = expit(ov) ECv = -np.mean( np.where( yv==1, np.log(sv), np.log(1-sv) ) ) ECv_list.append(ECv) rendimiento_v = np.mean( (self.clasifica(Xv)>0.5) == yv ) rendimiento_v_list.append(rendimiento_v)

    if early_stopping: if ECv < best_Ecv: best_Ecv = ECv best_w = self.w.copy() n_epochs_sin_mejora = 0 else: n_epochs_sin_mejora += 1

    if n_epochs_sin_mejora >= paciencia: print(“PARADA TEMPRANA”) self.w = best_w return

    Fin del if de salida_epoch/early_stopping

    Fin del for de cada epoch

    if salida_epoch: print(f"Inicialmente, en entrenamiento EC: {EC_list[0]}, rendimiento: {rendimiento_list[0]}.“) print(f"Inicialmente, en validación EC: {ECv_list[0]}, rendimiento: {rendimiento_v_list[0]}.”) for epoch in range(1,n_epochs): print(f"Epoch {epoch}, en entrenamiento EC: {EC_list[epoch]}, rendimiento: {rendimiento_list[epoch]}.“) if not Xv is None: print(f” en validación EC: {ECv_list[epoch]}, rendimiento: {rendimiento_v_list[epoch]}.")

    def clasifica_prob(self,ejemplos): if not hasattr(self, ‘w’): raise ClasificadorNoEntrenado(‘El clasificador no está entrenado’)

    bias = np.ones((ejemplos.shape[0],1)) ejemplos = np.hstack((bias,ejemplos))

    o = ejemplos.dot(self.w) s = expit(o)

    return s[:,1]

    def clasifica(self,ejemplo): if not hasattr(self, ‘w’): raise ClasificadorNoEntrenado(‘El clasificador no está entrenado’)

    bias = np.ones((1,1)) ejemplo = np.hstack((bias,ejemplo.reshape((1,-1))))

    o = ejemplo.dot(self.w) s = expit(o)

    return self.clases[1] if s[0,1] >= 0.5 else self.clases[0]

  2. Assistant

    class RegresionLogisticaMiniBatch(): def init(self,rate=0.1,rate_decay=False,n_epochs=100,batch_tam=64): self.rate = rate self.rate_decay = rate_decay self.n_epochs = n_epochs self.batch_tam = batch_tam

    def entrena(self,X,y,Xv=None,yv=None,n_epochs=100,salida_epoch=False,early_stopping=False,paciencia=3):
        self.n_clases = np.unique(y).size
        self.clases = np.unique(y).tolist()
    
        if not self.clases[1] == 1:
            self.clases.reverse()
            X = X[:,::-1]
            if not Xv is None: Xv = Xv[:,::-1]
    
        if y.ndim == 1:
            y = y.reshape((-1,1))
    
        # normalizar datos
        X_max, X_min = X.max(axis=0), X.min(axis=0)
        self.X_max, self.X_min = X_max, X_min
        X = (X - self.X_min)/(self.X_max - self.X_min + 1e-8)
        if not Xv is None:
            Xv = (Xv - self.X_min)/(self.X_max - self.X_min + 1e-8)
    
        bias = np.ones((X.shape[0],1))
        X = np.hstack((bias,X))
        if not Xv is None:
            bias = np.ones((Xv.shape[0],1))
            Xv = np.hstack((bias,Xv))
    
        self.w = np.random.rand(X.shape[1],self.n_clases)-0.5
    
        idx = np.arange(X.shape[0])
        batches = np.array_split(idx,X.shape[0]/self.batch_tam)
    
        EC_list = []
        rendimiento_list = []
        ECv_list = []
        rendimiento_v_list = []
    
        best_Ecv = np.inf
        n_epochs_sin_mejora = 0
    
        for epoch in range(n_epochs):
            rate_epoch = self.rate*((1+epoch)**(-1))
            if self.rate_decay:
                rate_epoch = rate_epoch/(epoch/self.n_epochs)
    
            for batch_i in batches:
                Xt = X[batch_i,:]
                yt = y[batch_i,:]
    
                o = Xt.dot(self.w)
                s = expit(o)
    
                error = yt-s
                grad = Xt.T.dot(error)
    
                self.w = self.w + rate_epoch*grad
    
            if salida_epoch or early_stopping:
                EC = -np.mean( np.where( y==1, np.log(s), np.log(1-s) ) )
                EC_list.append(EC)
    
                rendimiento = np.mean( (self.clasifica(X)>0.5) == y )
                rendimiento_list.append(rendimiento)
    
                if not Xv is None:
                    ov = Xv.dot(self.w)
                    sv = expit(ov)
                    ECv = -np.mean( np.where( yv==1, np.log(sv), np.log(1-sv) ) )
                    ECv_list.append(ECv)
                    rendimiento_v = np.mean( (self.clasifica(Xv)>0.5) == yv )
                    rendimiento_v_list.append(rendimiento_v)
    
                    if early_stopping:
                        if ECv < best_Ecv:
                            best_Ecv = ECv
                            best_w = self.w.copy()
                            n_epochs_sin_mejora = 0
                        else:
                            n_epochs_sin_mejora += 1
    
                        if n_epochs_sin_mejora >= paciencia:
                            print("PARADA TEMPRANA")
                            self.w = best_w
                            return
    
            # Fin del if de salida_epoch/early_stopping
    
        # Fin del for de cada epoch
    
        if salida_epoch:
            print(f"Inicialmente, en entrenamiento EC: {EC_list[0]}, rendimiento: {rendimiento_list[0]}.")
            print(f"Inicialmente, en validación EC: {ECv_list[0]}, rendimiento: {rendimiento_v_list[0]}.")
            for epoch in range(1,n_epochs):
                print(f"Epoch {epoch}, en entrenamiento EC: {EC_list[epoch]}, rendimiento: {rendimiento_list[epoch]}.")
                if not Xv is None:
                    print(f" en validación EC: {ECv_list[epoch]}, rendimiento: {rendimiento_v_list[epoch]}.")
    
    def clasifica_prob(self,ejemplos):
        if not hasattr(self, 'w'):
            raise ClasificadorNoEntrenado('El clasificador no está entrenado')
            
        bias = np.ones((ejemplos.shape[0],1))
        ejemplos = np.hstack((bias,ejemplos))
        
        o = ejemplos.dot(self.w)
        s = expit(o)
        
        return s[:,1]
    
    def clasifica(self,ejemplo):
        if not hasattr(self, 'w'):
            raise ClasificadorNoEntrenado('El clasificador no está entrenado')
            
        bias = np.ones((1,1))
        ejemplo = np.hstack((bias,ejemplo.reshape((1,-1))))
        
        o = ejemplo.dot(self.w)
        s = expit(o)
        
        return self.clases[1] if s[0,1] >= 0.5 else self.clases[0]