日常笔记:python(2)

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)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值