zoukankan      html  css  js  c++  java
  • [Python] 常用小函数

    将Python里的字典dict保存成csv:

    df = pd.DataFrame.from_dict(csv_dict, orient='columns')
    df.to_csv('/home/lxg/data/animal_data/Result.csv')

    从csv中读取数据

    PATH = '/home/lxg/data/animal_data/Result.csv'
    df = pd.read_csv(PATH,index_col=0) # index_col=0 读取时忽略序号列

    将两列数据组合成一列,map函数将该列映射成str格式,以便相加

    df['data'] = df['year'].map(str)+'-'+df['month'].map(str)

    plt.imshow() 清晰度调整+灰度二值图

    labelImage = cv2.imread('RGB-PanSharpen_AOI_2_Vegas_img1314_mask.tif')
    labelImage = cv2.cvtColor(labelImage, cv2.COLOR_RGB2GRAY)
    labelImage = np.where(labelImage > 10 , 0, 1).astype(np.uint8)
     
    plt.rcParams['figure.dpi'] = 100
    fig = plt.figure()
    plt.imshow(labelImage,cmap=plt.cm.gray)
    
    cv2.imwrite(path, array)
    

    OTHER

    #######################################
    # 用于多类别分类任务中,统计各类别的个数
    #######################################
    import numpy as np
    def statics(label_arr):
        cls = np.unique(label_arr)
        print('*******Dataset*******')
        for c in list(cls):
            count = np.sum([int(x==c) for x in label_arr ])
            print('| 类别',c,'| 个数',count)
        print('| 总数', label_arr.shape[0])
        print('*' * 20)
    
    
    #######################################
    # 统一记录接口,logging库
    #######################################
    import os
    import logging
    def init_log(output_dir):
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s %(message)s',
                            datefmt='%Y%m%d-%H:%M:%S',
                            filename=os.path.join(output_dir, 'log.log'),
                            filemode='w')
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        logging.getLogger('').addHandler(console)
        return logging
    
    # 使用
    logging = init_log(SAVE_DIR)
    _print = logging.info
    # 调用,可在终端输出并在log文件里保存相同内容
    _print('| epoch:{} | train | loss: {:.3f} | correct: {} | total: {} | acc: {:.3f} |'.format(
                epoch, loss, train_correct, train_total, train_acc
            ))
    
    #######################################
    # 训练测试集的划分,可保证各个类别的比例。十分好用!
    #######################################
    from sklearn.model_selection import train_test_split
    x1, x2, y1, y2= train_test_split(IMAGES, LABELS,test_size=0.33, random_state=42)
    
    #######################################
    # 单通道图像转三通道
    #######################################
    # Numpy object
    if len(img.shape) == 2:
        img = np.stack([img] * 3, 2)
    # PIL object
    imgs = [img,img,img]
    imgs = Image.merge("RGB",imgs)   #合并三通道
    
  • 相关阅读:
    [转载]DFT与IDFT
    OFDM符号速率与子载波间隔的关系
    OFDM时域削峰法降峰均比的原理及影响
    OFDM发端硬件实现原理图
    Flask-Script模块
    shutil 模块
    werzeug之LocalProxy源码
    flask启动流程02
    Werkzeug库的routing模块(Rule, Map)
    flask启动流程01
  • 原文地址:https://www.cnblogs.com/geoli/p/15400579.html
Copyright © 2011-2022 走看看