1. zip()
可以一次性迭代两个List,zip的作用是生成一个tuple的zip对象,迭代结果可以表示为list(zip(a,b)) = [(0, 10),(1,11),(2,12).....]
a = [x for x in range(10)]
b = [x for x in range(10,20)]
for a_, b_ in zip(a,b)
print(a_+b_)
2.eval()
eval自动识别str格式并转换成相应的对象,假如把一个str保存到文件,例如 str1=‘[1,2,3,4,]’
使用eval就能自动把str转换成List =eval=(str1)=[1,2,3,4]
3.csv数据读取技巧
在python3使用read_csv的时候,如果传入的参数不是文件名而是文件的路径,就会报这个错。
原因应该是这个库的问题,解决方法是,先切换到这个目录,然后传文件名作为参数。
出错代码:
‘’‘python’
import pandas as pd
import os
trainFile = "F:/Projects/Python/coursera/intro-to-data-science/kaggle/data/train.csv"
pwd = os.getcwd()
os.chdir(os.path.dirname(trainFile))
trainData = pd.read_csv(os.path.basename(trainFile))
os.chdir(pwd)
4.numpy矩阵操作
一维矩阵np.array[]矩阵转置等于其本身,
一维矩阵np.array[]矩阵可以正常转置 .T即可
注意np.ones(1,2) = array[[1, 2]],np.ones(2) = array[1, 2]
5.list拼接:
1> L1 + L2
2>L1.extend(L2)
3> L1[len(L1):len(L1)]=L2
6.注意python赋值!一定要正确!两个list不能直接使用a=b这样会导致a==b,指向同一片内存
1、切片操作:b = a[:] 或者 b = [each for each in a]
2、工厂函数:b = list(a)
3、copy函数:b = copy.copy(a)
7.python调用list的时候需要指示第几个list,使用enumerate
for i,j in enumerate([x for x in range(5)]):
print(i*j):::0 1 4 9 16
8.三维矩阵展开二维矩阵
a = np.arange(24).reshape(2,3,4)
a
Out[43]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
a.reshape(2, -1) -1的意思是不管多少,展开完为止
Out[44]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
9.urllib.request.urlretrieve下载文件
首先定义一个回显函数
defcallbackfunc(blocknum, blocksize, totalsize):
pass
urllib.request.urlretrieve(url, localname, callbackfunc)
10.sorted中的key
dict = {'the':10, 'abc':10}
sorted(dict.items, key = lambda x : (x[1], x[0]) 首先按照 数字排序,数字一样的再按照字母排序
11. 获取当前路径,和当前路径的所有文件
print ("os.getcwd()=%s" % os.getcwd())
print ("sys.path[0]=%s" % sys.path[0])
print ("sys.argv[0]=%s" % sys.argv[0])
---》"G:\work" "G:\work" "G:\work\xxxx.py"
第二个第三个在console中不适中。
获取路径中的文件已经文件夹
for root, dirs, files in os.walk(file_dir): 每次迭代对应的是一个tuple(root,dirs files)
获取文件夹 os.listdir()
12.使用setup.py install 安装的文件卸载问题
To record a list of installed files, you can use:
python setup.py install --record files.txt
Once you want to uninstall you can use xargs to do the removal:
cat files.txt | xargs rm -rf
Or if you're running Windows, use Powershell:
Get-Content files.txt | ForEach-Object {Remove-Item $_ -Recurse -Force}
非常有效!!!
13.有关conda
命令行输入
conda install -c anaconda anaconda-navigator=1.6.2
conda update conda
conda update anaconda
conda update --all
conda update
用来更新……
14. tensorflow变量重用问题
通过共享 变量作用域(variable_scope) 来实现 共享变量 。在重复使用(即 非第一次使用)时,设置 reuse=True 来 再次调用 该共享变量作用域(variable_scope)。主要有两种方法进行reuse。
注意!:定义变量时使用tf.Variable() 定义的变量均不能共享,必须使用tf.get_variable()才可进行共享!使用高级api(不用自己定义变量自动生成)的时候默认使用的后者,能够进行共享!
方法一:
使用 tf.Variable_scope(..., reuse=tf.AUTO_REUSE)
。
def net(...):
with tf.variable_scope('this scope', reuse=tf.AUTO_REUSE): ### 改动部分 ###
w1 = tf.get_variable(name='w1', initilizer=0......)
x = tf.placeholder(...)
x1 = tf.placeholder(...)
D_logits = net(x)
G_logits = net(x1)#这时net里面的变量都是共享的,
variables = tf.trainable_variables()
print([var.name for var in variables])
#只有一个w1变量
方法二:
使用 if reuse:
。
tf.get_variable_scope().reuse_variables()scope(..., reuse=tf.AUTO_REUSE)
def net(...):
with tf.variable_scope('this scope', reuse=tf.AUTO_REUSE): ### 改动部分 ###
if reuse:
tf.get_variable_scope().reuse_variables()
w1 = tf.get_variable(name='w1', initilizer=0......)
x = tf.placeholder(...)
x1 = tf.placeholder(...)
D_logits = net(x)
G_logits = net(x1)
variables = tf.trainable_variables()
print([var.name for var in variables])
#只有一个w1变量
15.dlib库编译安装问题
使用vs2015,记得安装vs里面的vc++ sdk8.1(这俩是在一起的)其他的不用过多勾选,安装好以后编译即可。
16.读取keras保存的h5文件(只有参数没有模型)
import datetime
import os
import h5py
import numpy as np
import pandas as pd
def h5py2dict(path0=None):
file = h5py.File(path0)
d = {}
keys_groups = list(file.keys())
# print(keys_groups)
for key in keys_groups:
if 'conv2d' in key:
# print(key)
bias = file['/'+key+'/'+list(file[key])[0]+'/'+'bias:0'].value
kernel = file['/'+key+'/'+list(file[key])[0]+'/'+'kernel:0'].value
d[key] = [kernel, bias]
# if 'batch_normalization' in key:
# # ['beta:0', 'gamma:0', 'moving_mean:0', 'moving_variance:0']
# beta = file['/'+key+'/'+key+'/'+'beta:0'].value
# gamma = file['/'+key+'/'+key+'/'+'gamma:0'].value
# moving_mean = file['/'+key+'/'+key+'/'+'moving_mean:0'].value
# moving_variance = file['/'+key+'/'+key+'/'+'moving_variance:0'].value
# d[key] = [beta, gamma, moving_mean, moving_variance]
if 'dense' in key:
bias = file['/'+key+'/'+list(file[key])[0]+'/'+'bias:0'].value
kernel = file['/'+key+'/'+list(file[key])[0]+'/'+'kernel:0'].value
d[key] = [kernel, bias]
with open(path0.split('.')[0]+'.txt', 'w+') as f:
f.write(str(d))
file.close()
return d
读取并保存为txt文件,格式为字典,d['conv2d_1'] = [***...] 记得重复读入txt 使用d = eval(f.read())恢复原籍
17.ROC,PR曲线
Precision:P=TP/(TP+FP)
Recall:R=TP/(TP+FN)
F1-score:2/(1/P+1/R)
ROC/AUC:TPR=TP/(TP+FN), FPR=FP/(FP+TN)
18.python2 python3 编码问题
1.在python2默认编码是ASCII, python3里默认是unicode
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
# -*- utf-8 -*-只是为了让脚本文件以utf8编码,里面的数据还是需要指定。