日常笔记:python(2)

2024-05-08 03:48
文章标签 python 笔记 日常

本文主要是介绍日常笔记:python(2),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Preface

日常纪录自己所查所用,为日后回忆留个方便,也给碰到类似问题的童鞋留个小参考。

不知不觉,进行到第二弹了,之前的 日常笔记:Python(1) 已经比较冗余了。开一个新的吧,作为 (2)。


查看 python 程序所占内存

import resourceprint("{}".format(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss))


python 的 filter 函数

The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function function returns True.

The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l.

Only if f returns True will the element of the list be included in the result list.

>>> fib = [0,1,1,2,3,5,8,13,21,34,55]
>>> result = filter(lambda x: x % 2, fib)
>>> print result
[1, 1, 3, 5, 13, 21, 55]
>>> result = filter(lambda x: x % 2 == 0, fib)
>>> print result
[0, 2, 8, 34]
>>> 


何时该使用 GPU

Not all operations can be done on GPUs.

If you get the following error, you are trying to do an operation that can not be done on a GPU:

Cannot assign a device to node PyFunc: Could not satisfy explicit device specification /device:GPU:1 because no devices matching that specification are registered in this process.


python 的 zip 函数

https://docs.python.org/2/library/functions.html#zip


python 的 linspace 函数

https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html


画训练误差曲线

import matplotlib.pyplot as plterrors = []plt.plot([np.mean(errors[i-50:i]) for i in range(len(errors))])
plt.show()
plt.savefig("errors.png")


Tensorflow 中 rnn_cell 问题

在训练中,碰到了如下的问题:

output, state = lstm(lstm_input, state)ValueError: setting an array element with a sequence.

具体的,十分的类似于这个链接里所描述的:https://github.com/Russell91/TensorBox/issues/59

#-*- coding: utf-8 -*-
import tensorflow as tf
import pandas as pd
import numpy as np
import os
import ipdbimport cv2#from tensorflow.models.rnn import rnn_cellfrom keras.preprocessing import sequenceself.lstm1 = tf.nn.rnn_cell.BasicLSTMCell(dim_hidden, state_is_tuple=False)
self.lstm2 = tf.nn.rnn_cell.BasicLSTMCell(dim_hidden, state_is_tuple=False)

这是由于新版本的 Tensorflow 与旧版本的冲突导致的,加一个:

state_is_tuple = False


matplotlib 画图

用来画 loss 的曲线图:
http://www.cnblogs.com/wei-li/archive/2012/05/23/2506940.html
http://www.jianshu.com/p/ee8bb1bd0019
http://blog.csdn.net/freewebsys/article/details/52577631


ipdb 单步调试

这几天才发现的一个大杀器,很好用:
http://tt4it.com/exchange/blog/discuss/22/


caffe 指定运行的 GPU 编号

http://kawahara.ca/caffe-how-to-specify-which-gpu-to-use-in-pycaffe/

import caffe
GPU_ID = 1 # Switch between 0 and 1 depending on the GPU you want to use.
caffe.set_mode_gpu()
caffe.set_device(GPU_ID)

事实上,可以先在 ~/.bashrc 文件中:

export CUDA_VISIBLE_DEVICES = 0

如果这里的 ~/.bashrc 文件中指定了 0 号 GPU,那么,后面指定几号都没用了。所以,如果要想后面指定 GPU,这里一定好使得所有的 GPU 都可见:

export CUDA_VISIBLE_DEVICES = 0, 1, 2, 3


删除 list 中最后一个元素

http://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index-in-python

>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]

或者:

>>> a.pop()
8
>>> a
[0, 1, 2, 3, 4, 5, 6, 7]

看自己喜欢用哪一种吧~


返回所有索引

http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list

indices = [i for i, x in enumerate(my_list) if x == "whatever"]

这一句话搞定,代码很 python~


NLTK 计算 BLEU 值

http://stackoverflow.com/questions/32395880/calculate-bleu-score-in-python/32395945#32395945

import nltkhypothesis = ['It', 'is', 'a', 'cat', 'at', 'room']
reference = ['It', 'is', 'a', 'cat', 'inside', 'the', 'room']#there may be several references
BLEUscore = nltk.translate.bleu_score.sentence_bleu([reference], hypothesis)
print BLEUscore


subprocess 模块

在 python 程序中,调用 Terminal 运行脚本:

http://stackoverflow.com/questions/89228/calling-an-external-command-in-python

from subprocess import call# Way 1
call(["ls", "-l"])# Way 2
subprocess.call(['ping', 'localhost'])# Way 3
return_code = subprocess.call("echo Hello World", shell=True)


将字符串转为小写

x = 'Hello world'
print x.lower()

这里写图片描述

cv2模块找不到问题

经常在编译完 OpenCV 之后,在 python 下面,我们想导入 cv2 模块:

import cv2

这时候会找不到 cv2 模块,碰到这样的问题,通常编辑环境变量:

sudo vim ~/.bashrc

然后:

export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH

或者:

import sys
sys.path.append('/usr/local/lib/python2.7/site-packages')

datetime

今天又看到一种新的计时方法:

import datetimeprint 'DONE (t=%0.2fs)'%((datetime.datetime.utcnow() - time_t).total_seconds())

众数

from scipy.stats import mode
mode(data)

中位数

import numpy as np
np.median(data)

这篇关于日常笔记:python(2)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/969221

相关文章

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

基于Python开发一个图像水印批量添加工具

《基于Python开发一个图像水印批量添加工具》在当今数字化内容爆炸式增长的时代,图像版权保护已成为创作者和企业的核心需求,本方案将详细介绍一个基于PythonPIL库的工业级图像水印解决方案,有需要... 目录一、系统架构设计1.1 整体处理流程1.2 类结构设计(扩展版本)二、核心算法深入解析2.1 自

从入门到进阶讲解Python自动化Playwright实战指南

《从入门到进阶讲解Python自动化Playwright实战指南》Playwright是针对Python语言的纯自动化工具,它可以通过单个API自动执行Chromium,Firefox和WebKit... 目录Playwright 简介核心优势安装步骤观点与案例结合Playwright 核心功能从零开始学习

Python 字典 (Dictionary)使用详解

《Python字典(Dictionary)使用详解》字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力,:本文主要介绍Python字典(Dictionary)... 目录字典1.基本特性2.创建字典3.访问元素4.修改字典5.删除元素6.字典遍历7.字典的高级特性默认字典

Python自动化批量重命名与整理文件系统

《Python自动化批量重命名与整理文件系统》这篇文章主要为大家详细介绍了如何使用Python实现一个强大的文件批量重命名与整理工具,帮助开发者自动化这一繁琐过程,有需要的小伙伴可以了解下... 目录简介环境准备项目功能概述代码详细解析1. 导入必要的库2. 配置参数设置3. 创建日志系统4. 安全文件名处

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数