python类row_stack()的实例源码

period.py 文件源码 项目:gdax-trader 作者: mcardillo55 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def add_stick(self, stick_to_add):
        self.candlesticks = np.row_stack((self.candlesticks, stick_to_add.close_candlestick(self.name)))
period.py 文件源码 项目:gdax-trader 作者: mcardillo55 项目源码 文件源码 阅读 51 收藏 0 点赞 0 评论 0
def close_candlestick(self):
        if not self.updated_hist_data:
            self.time_of_first_candlestick_close = datetime.datetime.now()
        if len(self.candlesticks) > 0:
            self.candlesticks = np.row_stack((self.candlesticks,
                                              self.cur_candlestick.close_candlestick(period_name=self.name,
                                                                                     prev_stick=self.candlesticks[-1])))
        else:
            self.candlesticks = np.array([self.cur_candlestick.close_candlestick(self.name)])
test_gpmcc_simple_composite.py 文件源码 项目:cgpm 作者: probcomp 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
def generate_quadrants(rows, rng):
    Q0 = rng.multivariate_normal([2,2], cov=[[.5,0],[0,.5]], size=rows/4)
    Q1 = rng.multivariate_normal([-2,2], cov=[[.5,0],[0,.5]], size=rows/4)
    Q2 = rng.multivariate_normal([-2,-2], cov=[[.5,0],[0,.5]], size=rows/4)
    Q3 = rng.multivariate_normal([2,-2], cov=[[.5,0],[0,.5]], size=rows/4)
    colors = iter(cm.gist_rainbow(np.linspace(0, 1, 4)))
    for q in [Q0, Q1, Q2, Q3]:
        plt.scatter(q[:,0], q[:,1], color=next(colors))
    plt.close('all')
    return np.row_stack((Q0, Q1, Q2, Q3))
factor.py 文件源码 项目:cgpm 作者: probcomp 项目源码 文件源码 阅读 47 收藏 0 点赞 0 评论 0
def joint_parameters(self):
        mean = np.concatenate((np.zeros(self.L), self.mux))
        cov = np.row_stack((
            np.column_stack((np.eye(self.L), self.W.T)),
            np.column_stack((self.W, np.dot(self.W, self.W.T) + self.Psi))
        ))
        return mean, cov
factor.py 文件源码 项目:cgpm 作者: probcomp 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def mvn_marginalize(mu, cov, query, evidence):
        Q, E = query, evidence
        # Retrieve means.
        muQ = mu[Q]
        muE = mu[E]
        # Retrieve covariances.
        covQ = cov[Q][:,Q]
        covE = cov[E][:,E]
        covJ = cov[Q][:,E]
        covQE = np.row_stack((
            np.column_stack((covQ, covJ)),
            np.column_stack((covJ.T, covE))
        ))
        assert np.allclose(covQE, covQE.T)
        return muQ, muE, covQ, covE, covJ
InventoryDemandPre.py 文件源码 项目:mlprojects-py 作者: srinathperera 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def parse_parameter_sweep(file='/Users/srinath/playground/data-science/BimboInventoryDemand/logs/xgboost_params-explore-case4.txt'):
    file = open(file,'r')
    data =  file.read()

    data = data.replace('\n','')
    data = re.sub(r'\[=+\'\].*?s', '', data)
    #28. feature 27 =Producto_ID_Dev_proxima_StdDev (0.002047)

    p1 = re.compile('Run ([0-9+]) XGBoost_nocv {(.*?)} .*?rmsle=([0-9.]+)')

    readings = []
    for match in p1.finditer(data):
        data_index = int(match.group(1))
        params_as_str = match.group(2)
        rmsle = float(match.group(3))
        print data_index, rmsle, params_as_str

        kvmap = parse_map_from_str(params_as_str)
        print kvmap
        readings.append([data_index, rmsle, kvmap['eta'], kvmap['max_depth'], kvmap['min_child_weight'], kvmap['gamma'],
                         kvmap['subsample'], kvmap['colsample_bytree']])

    df_data = np.row_stack(readings)
    para_sweep_df= pd.DataFrame(df_data, columns=['data_index' , 'rmsle', 'eta', 'max_depth', 'min_child_weight', 'gamma',
                         'subsample', 'colsample_bytree'])
    print para_sweep_df
    return para_sweep_df
__init__.py 文件源码 项目:mlprojects-py 作者: srinathperera 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def vote_with_lr(conf, forecasts, best_model_index, y_actual):
    start = time.time()
    best_forecast = forecasts[:, best_model_index]
    forecasts = np.sort(np.delete(forecasts, best_model_index, axis=1), axis=1)
    forecasts = np.where(forecasts <=0, 0.1, forecasts)

    data_train = []

    for i in range(forecasts.shape[0]):
        f_row = forecasts[i,]
        min_diff_to_best = np.min([cal_rmsle(best_forecast[i], f) for f in f_row])
        comb = list(itertools.combinations(f_row,2))
        avg_error = scipy.stats.hmean([cal_rmsle(x,y) for (x,y) in comb])
        data_train.append([min_diff_to_best, avg_error, scipy.stats.hmean(f_row), np.median(f_row), np.std(f_row)])


    X_all = np.column_stack([np.row_stack(data_train), best_forecast])
    if conf.target_as_log:
        y_actual = transfrom_to_log(y_actual)
    #we use 10% full data to train the ensamble and 30% for evalaution
    no_of_training_instances = int(round(len(y_actual)*0.25))
    X_train, X_test, y_train, y_test = train_test_split(no_of_training_instances, X_all, y_actual)
    y_actual_test = y_actual[no_of_training_instances:]

    lr_model =linear_model.Lasso(alpha = 0.2)
    lr_model.fit(X_train, y_train)
    lr_forecast = lr_model.predict(X_test)
    lr_forcast_revered = retransfrom_from_log(lr_forecast)
    calculate_accuracy("vote__lr_forecast " + str(conf.command), y_actual_test, lr_forcast_revered)
    print_time_took(start, "vote_with_lr")
    return lr_forcast_revered
__init__.py 文件源码 项目:mlprojects-py 作者: srinathperera 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def parse_feature_explore_output(file_name, feature_importance_map):
    #[IDF1] ['clients_combined_vh_Mean_x', 'clients_combined_vhci_x', 'clients_combined_vh_median_x', 'Producto_ID_Venta_hoy_Mean', 'Producto_ID_Venta_hoyci', 'Producto_ID_Venta_hoy_median', 'Producto_ID_Dev_proxima_Mean', 'Producto_ID_Dev_proximaci', 'Producto_ID_Dev_proxima_median', 'agc_product_Mean', 'agc_productci', 'agc_product_median'] XGB 0.584072902792

    file = open(file_name,'r')
    data =  file.read()

    data = data.replace('\n','')
    data = re.sub(r'\[=+\'\].*?s', '', data)
    #28. feature 27 =Producto_ID_Dev_proxima_StdDev (0.002047)

    p1 = re.compile('\[IDF1\] (\[.*?\]) XGB ([0-9.]+)')

    readings = []
    for match in p1.finditer(data):
        feature_set = match.group(1)
        rmsle = float(match.group(2))
        if 0.56 < rmsle < 0.57:
            for f in parse_list_from_str(feature_set):
                count = feature_importance_map.get(f, 0)
                count += 1
                feature_importance_map[f] = count
        readings.append([feature_set, rmsle])

    df_data = np.row_stack(readings)
    para_sweep_df= pd.DataFrame(df_data, columns=['feature_set' , 'rmsle'])
    return para_sweep_df
utils.py 文件源码 项目:keras-face-attribute-manipulation 作者: wkcw 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def combine_label_batch(num0, num1, numt=0, order='01'):
    assert order=='01' or order=='10'
    label_batch_0 = np.tile((1,0,0),(num0,1))
    label_batch_1 = np.tile((0,1,0),(num1,1))
    label_batch_t = np.tile((0,0,1),(numt,1))
    if order == '01':
        label_batch_all = np.row_stack((label_batch_0, label_batch_1, label_batch_t))
    else:
        label_batch_all = np.row_stack((label_batch_1, label_batch_0, label_batch_t))
    label_batch_all = label_batch_all.astype('float32')
    return label_batch_all
branch.py 文件源码 项目:SamuROI 作者: samuroi 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def linescan(self, data, mask):
        """
        Calculate the trace for all children and return a 2D array of traces.
        :param data: the data to apply on.
        :param mask: some additional overlay mask
        :return: 2D numpy array holding traces for all children
        """
        return numpy.row_stack((child(data, mask) for child in self.segments))
branch.py 文件源码 项目:SamuROI 作者: samuroi 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def outline(self):
        """
        Return the corners of the branch in such order that they encode a polygon.
        """
        return numpy.row_stack((self.corners[:, 0, :], self.corners[::-1, 1, :]))
branch.py 文件源码 项目:SamuROI 作者: samuroi 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def quadrilaterals(self):
        """
        Generator over quadrilateral segments of that branch.
        """
        if self.nquadrilaterals > 0:
            corners = self.corners
            for i in range(self.nquadrilaterals):
                yield numpy.row_stack((corners[i, 0, :], corners[i + 1, 0, :], corners[i + 1, 1, :], corners[i, 1, :]))
rasterview.py 文件源码 项目:SamuROI 作者: samuroi 项目源码 文件源码 阅读 47 收藏 0 点赞 0 评论 0
def linescan(self):
        """
        Calculate the trace for all children and return a 2D array aka linescan for that branch roi.
        """
        if self.parent_mask in self.__linescans:
            return self.__linescans[self.parent_mask]
        import numpy
        data = self.segmentation.data
        overlay = self.segmentation.overlay
        postprocessor = self.segmentation.postprocessor
        self.__linescans[self.parent_mask] = numpy.row_stack(
            (postprocessor(child(data, overlay)) for child in self.parent_mask.children))
        return self.__linescans[self.parent_mask]
openglscene.py 文件源码 项目:car-detection 作者: mmetcalfe 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def draw(self, program, model=None, rawVertices=False):
        scale = np.eye(4, dtype=np.float32)
        scale[0,0] = self.scale[0]
        scale[1,1] = self.scale[1]
        scale[2,2] = self.scale[2]

        if not rawVertices:
            if model == None:
                orient = lookAtTransform(self.pos, self.pos + self.dir, self.up, square=True)
                # model = np.linalg.inv(orient)*scale
                model = np.linalg.inv(orient)*scale
            else:
                orient = lookAtTransform(self.pos, self.pos + self.dir, self.up, square=True)
                # model = model*np.linalg.inv(orient)*scale
                model = model*np.linalg.inv(orient)*scale
        else:
            model = np.eye(4, dtype=np.float32)
        program.setUniformMat4('model', model)

        # for mesh in self.aiModel.meshes:
        #     for i in range(0, len(mesh.vertices)):
        #         # print 'model', model
        #         vert = np.row_stack([np.matrix(mesh.vertices[i]).T, np.array([1])])
        #         worldVert = model*vert
        #         eyeVert = proj*worldVert
        #         ndcVert = eyeVert[:3]/eyeVert[3]
        #         print 'worldVert:', worldVert.T
        #         # print '   m->w', worldVert.T
        #         print '   w->e', eyeVert.T
        #         print '   e->n', ndcVert.T

        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)

        for mesh in self.meshBuffers:
            mesh.draw(program)

        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
camera.py 文件源码 项目:car-detection 作者: mmetcalfe 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def getOpenGlCameraMatrix(self):
        K, R, t = self.factor()
        # print 'R', R

        # print 'getOpenGlCameraMatrix:'
        # print 'Kraw:', K

        K = convertToOpenGLCameraMatrix(K, self.framebufferSize, self.near, self.far)

        # print 'K:', K

        V = np.column_stack((R, t))
        V = np.row_stack((
            V,
            np.array([0,0,0,1], np.float32)
        ))

        # print 'V:', V

        P = K*V

        # print 'P:', P

        # vpMat = viewPortMatrix(framebufferSize)
        # print 'vpMat:', vpMat
        # print 'VpP:', vpMat*P

        return P
network.py 文件源码 项目:gail-driver 作者: sisl 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _predict(self, t, X):
        sess = tf.get_default_session()

        N, _ = X.shape
        B = self.input_var.get_shape()[0].value

        if B is None or B == N:
            pred = sess.run(t, {self.input_var: X})
        else:
            pred = [sess.run(t, {self.input_var: X[i:i + B]})
                    for i in range(0, N, B)]
            pred = np.row_stack(pred)

        return pred
liberty523422842.py 文件源码 项目:HIT_ML_2017 作者: Red-Night-Aria 项目源码 文件源码 阅读 47 收藏 0 点赞 0 评论 0
def calc_L(matrix):
    (x, y) = np.shape(matrix)
    return np.row_stack((np.mat(np.ones((1, y))), Sigmoid(matrix)))
segmentation.py 文件源码 项目:crankshaft 作者: CartoDB 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def predict_segment(model, features, target_query):
    """
    Use the provided model to predict the values for the new feature set
        Input:
            @param model: The pretrained model
            @features: A list of features to use in the model prediction (list of column names)
            @target_query: The query to run to obtain the data to predict on and the cartdb_ids associated with it.
    """

    batch_size = 1000
    joined_features = ','.join(['"{0}"::numeric'.format(a) for a in features])

    try:
        cursor = plpy.cursor('SELECT Array[{joined_features}] As features FROM ({target_query}) As a'.format(
            joined_features=joined_features,
            target_query=target_query))
    except Exception, e:
        plpy.error('Failed to build segmentation model: %s' % e)

    results = []

    while True:
        rows = cursor.fetch(batch_size)
        if not rows:
            break
        batch = np.row_stack([np.array(row['features'], dtype=float) for row in rows])

        #Need to fix this. Should be global mean. This will cause weird effects
        batch = replace_nan_with_mean(batch)
        prediction = model.predict(batch)
        results.append(prediction)

    try:
        cartodb_ids = plpy.execute('''SELECT array_agg(cartodb_id ORDER BY cartodb_id) As cartodb_ids FROM ({0}) As a'''.format(target_query))[0]['cartodb_ids']
    except Exception, e:
        plpy.error('Failed to build segmentation model: %s' % e)

    return cartodb_ids, np.concatenate(results)
segmentation.py 文件源码 项目:crankshaft 作者: CartoDB 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def predict_segment(model, features, target_query):
    """
    Use the provided model to predict the values for the new feature set
        Input:
            @param model: The pretrained model
            @features: A list of features to use in the model prediction (list of column names)
            @target_query: The query to run to obtain the data to predict on and the cartdb_ids associated with it.
    """

    batch_size = 1000
    joined_features = ','.join(['"{0}"::numeric'.format(a) for a in features])

    try:
        cursor = plpy.cursor('SELECT Array[{joined_features}] As features FROM ({target_query}) As a'.format(
            joined_features=joined_features,
            target_query=target_query))
    except Exception, e:
        plpy.error('Failed to build segmentation model: %s' % e)

    results = []

    while True:
        rows = cursor.fetch(batch_size)
        if not rows:
            break
        batch = np.row_stack([np.array(row['features'], dtype=float) for row in rows])

        #Need to fix this. Should be global mean. This will cause weird effects
        batch = replace_nan_with_mean(batch)
        prediction = model.predict(batch)
        results.append(prediction)

    try:
        cartodb_ids = plpy.execute('''SELECT array_agg(cartodb_id ORDER BY cartodb_id) As cartodb_ids FROM ({0}) As a'''.format(target_query))[0]['cartodb_ids']
    except Exception, e:
        plpy.error('Failed to build segmentation model: %s' % e)

    return cartodb_ids, np.concatenate(results)
segmentation.py 文件源码 项目:crankshaft 作者: CartoDB 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def predict_segment(model, features, target_query):
    """
    Use the provided model to predict the values for the new feature set
        Input:
            @param model: The pretrained model
            @features: A list of features to use in the model prediction (list of column names)
            @target_query: The query to run to obtain the data to predict on and the cartdb_ids associated with it.
    """

    batch_size = 1000
    joined_features = ','.join(['"{0}"::numeric'.format(a) for a in features])

    try:
        cursor = plpy.cursor('SELECT Array[{joined_features}] As features FROM ({target_query}) As a'.format(
            joined_features=joined_features,
            target_query=target_query))
    except Exception, e:
        plpy.error('Failed to build segmentation model: %s' % e)

    results = []

    while True:
        rows = cursor.fetch(batch_size)
        if not rows:
            break
        batch = np.row_stack([np.array(row['features'], dtype=float) for row in rows])

        #Need to fix this. Should be global mean. This will cause weird effects
        batch = replace_nan_with_mean(batch)
        prediction = model.predict(batch)
        results.append(prediction)

    try:
        cartodb_ids = plpy.execute('''SELECT array_agg(cartodb_id ORDER BY cartodb_id) As cartodb_ids FROM ({0}) As a'''.format(target_query))[0]['cartodb_ids']
    except Exception, e:
        plpy.error('Failed to build segmentation model: %s' % e)

    return cartodb_ids, np.concatenate(results)


问题


面经


文章

微信
公众号

扫码关注公众号