日常笔记: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

相关文章

Sping 源码深度解析——容器的功能扩展 【学习笔记】

我为什么 看的不够远,因为高度不够! 学习和整理总结Spring容器的功能扩展,本文为学习笔记,其中有一些内容是自己的思考总结! 一、两种Spring中bean加载的方式 第一种 # 第一种使用 BeanFactory 以及它默认的实现类 XmlBeanFactoryBeanFactory bf = new XmlBeanFactory(new ClassPathResource(

学习笔记:从技术到管理,在蜕变中成长

大家好,我是阿飞云 怕什么真理无穷,进一步有近一步的欢喜 前几天分享了一篇有关于:从程序员到管理团队,分享一些职场管理的心得,相关内容也可点击下面卡片跳转查看。 本文分享一个看到过的视频内容,视频分享人是 特赞科技 CTO 黄勇,做了关于《从技术到管理,在蜕变中成长》的主题分享,对做技术与做管理的不同,到如何把事情做好有哪些模式,以及团队作战能力方面做了深入的分析。 看完后觉得挺有收获的,学习

我这两年收藏的嵌入式AI资源,并做了学习笔记

有粉丝问我:“当前乃至未来5-10年,嵌入式开发者还有哪些风口?” 画外音:风口的本质,其实就是一段时间的人才供需不平衡。说白了就是由于行业突变,敏锐的资本快速进入,导致短时间内行业大量扩张,需要大量开发者。 目前的嵌入式开发越来越倾向于智能化,也就是我们所说的智能硬件(硬件+软件)。 以百度机器人为例,机器人的核心是大脑,即是“数据和算法” ,但机器人大脑想机器人身躯能够像人类一样活动,能说会

threejs坑记录-笔记

雪花 注意depthTest: false 否则会出现有transparent无效 const createSnow = () => {let map = new THREE.TextureLoader().load(snow);let material = new THREE.SpriteMaterial({map: map,transparent: true,side: THREE.Dou

Vue学习笔记:拦截器

原文地址 Vue可以对http request和http response添加全局拦截,最典型的例子就是在请求头里添加token,和监测是否登录,如果没有登录则跳转到登录页面。 main.js中添加拦截器的代码: 1. request 拦截器 //request 拦截器,在请求头中加tokenaxios.interceptors.request.use(config => {if (lo

Zen of Python -Python之禅

在浏览Python官方文档时无意发现了这个彩蛋,只需在终端中import this The Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than compli

Pytorch学习笔记_4_训练一个分类器

关于数据 一般来说,对于图像、文本、音频或视频数据,可以使用标准的Python包来将这些数据加载为numpy array,之后可以将这些array转换为torch.*Tensor 对于图像,Pillow、OpenCV包音频,scipy、librosa包文本,可以使用原始Python和Cython加载,或NLKT和SpaCy 特别的,对于视觉任务,有一个包torchvision,其中包含了处理

Pytorch学习笔记_3_构建一个神经网络

Neural Networks 神经网络可以通过使用torch.nn包来创建 nn依赖于autograd来定义模型并求导。 一个nn.Module类包含各个层和一个forward(input)前向传播方法,该方法返回output 例如这个分类数字图像的网络: 这是个简单的前馈神经网络,它接受一个输入,然后一层接一层的传递,最后输出计算结果 一个神经网络的典型训练过程: 定义包

Pytorch学习笔记_2_Autograd自动求导机制

Autograd 自动求导机制 PyTorch 中所有神经网络的核心是 autograd 包。 autograd 包为张量上的所有操作提供了自动求导。它是一个在运行时定义的框架,可以通过代码的运行来决定反向传播的过程,并且每次迭代可以是不同的。 通过一些示例来了解 Tensor 张量 torch.tensor是这个包的核心类。 设置.requires_grad为True,会追踪所有对于

Pytorch学习笔记_1_tensor张量

Tensors Tensors与Numpy中的ndarrays类似 torch.new_* 与 torch.*_like 前者创建的对象会保持原有的属性(如dtype),但shape不同 >>> x = torch.zeros(5, 3, dtype=torch.double)>>> x.new_ones(2, 3)tensor([[1., 1., 1.],[1., 1., 1.]],