日常笔记:python

Posted chenxp2311

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了日常笔记:python相关的知识,希望对你有一定的参考价值。

Preface

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

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


查看 python 程序所占内存

import resource

print("".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 plt

errors = []

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 ipdb

import cv2

#from tensorflow.models.rnn import rnn_cell

from keras.preprocessing import sequence

self.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 nltk

hypothesis = ['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 datetime

print '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的主要内容,如果未能解决你的问题,请参考以下文章

Python日常笔记(42)-Django数据库交互

python 日常笔记 hmmlearn 隐性马尔科夫模型案例分析

linux日常笔记5

Python学习笔记

Python学习笔记4 高级特性_20170618

《跟老齐学python Django实战 》笔记