日常笔记: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实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文