python

小tip

  • 传参时,如果接受的不是元组或列表,但想把元组或列表传入,可在前面加*。如果想把dict传入(关键字参数),可在前面加**

python面向对象

class Employee:
   '所有员工的基类'
   empCount = 0  #类变量,它的值在这个类的所有实例之间共享
 
   def __init__(self, name, salary):		#类的构造函数、初始化方法,创建这个类的实例时就会调用
      self.name = name		#self表示类的实例,在定义类的方法时是必须有的,代表类的实例,而非类
      self.salary = salary	#self.__class__指向类
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount
 
   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary
    
    def __del__(self):		#析构函数,在对象被销毁的时候调用
      class_name = self.__class__.__name__
      print class_name, "销毁"
    
emp1 = Employee("Zara", 2000)	#创建类的实例
emp1.displayEmployee()	#访问对象属性
emp1.age = 7  # 添加一个 'age' 属性
emp1.age = 8  # 修改 'age' 属性
del emp1.age  # 删除 'age' 属性

hasattr(emp1, 'age')    # 如果存在 'age' 属性返回 True。
getattr(emp1, 'age')    # 返回 'age' 属性的值
setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8
delattr(emp1, 'age')    # 删除属性 'age'

print "Employee.__doc__:", Employee.__doc__		#类的文档字符串,‘所有员工的基类’
print "Employee.__name__:", Employee.__name__		#类名,Employee
print "Employee.__module__:", Employee.__module__		#类定义所在的模块,__main__
print "Employee.__bases__:", Employee.__bases__		#类的所有父类组成的元组
print "Employee.__dict__:", Employee.__dict__		#类的所有属性


类的继承

class Parent:        # 定义父类
    __secretCount = 0  # 私有变量,实例不能访问,而单下划线开头的是protected类型的变量,只允许本身和子类访问
    parentAttr = 100
    def __init__(self):
        print "调用父类构造函数"
 
    def parentMethod(self):
        print '调用父类方法'
 
    def setAttr(self, attr):
        Parent.parentAttr = attr
 
    def getAttr(self):
        print "父类属性 :", Parent.parentAttr
        
     def myMethod(self):
      print '调用父类方法'
 
class Child(Parent): # 定义子类
    def __init__(self):
        print "调用子类构造方法"
 
    def childMethod(self):
        print '调用子类方法'
    
    def myMethod(self):		#子类方法重写
      	print '调用子类方法'
 
c = Child()          # 实例化子类
c.childMethod()      # 调用子类的方法
c.parentMethod()     # 调用父类方法
c.setAttr(200)       # 再次调用父类的方法 - 设置属性值
c.getAttr()          # 再次调用父类的方法 - 获取属性值

numpy

import numpy as np
a = numpy.array([1,2,3],[4,5,6])
x = np.empty([3,2],dtype=int)
y = np.zeros([2,2],dtype=np.int)
z = np.ones([2,2],dtype=int)
N = z.T
#从已有的数组创建数组
x = [1,2,3]
a = np.asarray(x,dtype=float)
#从数值范围创建数组
a = np.arange(10,20,2)#[10 12 14 16 18]
a = np.linspace(1,10,10)#等差数列起始值、终止值、个数
a = np.logspace(1,10,10)#等比数列起始值、终止值、个数
#切片和索引
b = a[2:5]
b = a[...,1]#第二列元素
b = a[...,1:]#第二列及剩下的所有元素
print(a[a>5])#打印出大于5的元素
print(a[~np.isnan(a)])#过滤空值
x = np.arange(32).reshape((8,4))
print(x[4,2,1,7])#如果目标是一维数组,索引结果是对应元素,如果目标是二维数组,那么就是对应下标的行
#数组操作
print(np.cancatenate(a,b),axis=1)#轴0是增加行,轴1是增加列,拼接维度的长度可以不同,其他维度必须相同
print(np.stack([a,b]))#沿新轴连接数组序列,两个数组必须有相同形状,输出结果比输入多一维
print(np.vstack([a,b]))#如果vstack对象是二维数组,就相当于concatenate,axis=0,如果是一维则结果不同
print(np.hstack([a,b]))#如果vstack对象是二维数组,就相当于concatenate,axis=1,如果是一维则结果不同
np.split(a,3)	np.hsplit(a,3)	np.vsplit(a,3)#沿特定的轴将数组分割为子数组
np.resize(a,(3,2))#返回指定大小的新数组,如果新数组大小大于原始大小,则包含原始数组中的元素的副本
np.append(a,[7,8,9],axis=0)#在数组的末尾添加值
np.insert(a,1,[11],axis=0)#在给定索引之前,沿给定轴在输入数组中插入值
np.delete(a,1,axis=1)#返回从输入数组中删除指定子数组的新数组
u = np.unique(a)#给数组去重
#函数
np.sin(a*np.pi/180)#同理有cos、tan、arcsin、arccos、arctan,这些函数的结果可以用np.degrees转换为角度
np.around(a,decimals=1)#返回数字的四舍五入值
np.floor(a)#向下取整
np.ceil(a)#向上取整	
np.add(a,b)#两数相加,同理subtract、multiply、devide
np.power(a,2)#数组相应元素的幂,同理mod余数
np.amin(a,0)#计算数组中元素沿指定轴的最小值,同理amax求最大值
np.percentile(a,q,0)#返回数组中元素沿指定轴的百分位数,类似的np.median
np.mean(a)#返回数组中元素的算术平均值
np.average(a,weight=[4,3,2,1])#返回数组元素的加权平均值
np.sort(a,axis=0)#排序,从小到大是argsort
np.argmax(a)#最大元素的索引,同理最小argmin
np.nonzero(a)#非0元素的索引
y=np.where(x>3)#大于3的元素的索引
#广播
c = a*b#如果ab形状相同,运算结果就是对应位相乘,否则将触发广播机制
##广播的规则:输出数组的形状是输入数组形状各个维度上的最大值。输入数组的某个维度和输出数组对应维度长度相同或为1时,这个数组能够用来计算,否则出错。输入数组某个维度为1时,沿着此维度运算时都用从此维度上的第一组值
#迭代数组
for x in np.nditer(a,order='F'):#F是列序优先,C是行序优先
    print(x)

pandas

import pandas as pd
df = pd.read_csv(myfile.csv,sep=;,nrows=1000,skiprow=[2,5])#读取前1000行,跳过第二行第五行
df = pd.DataFrame({"id":[1001,1002,1003,1004,1005,1006], 
 "date":pd.date_range('20130102', periods=6),
  "city":['Beijing ', 'SH', ' guangzhou ', 'Shenzhen', 'shanghai', 'BEIJING '],
 "age":[23,44,54,32,34,32],
 "category":['100-A','100-B','110-A','110-C','210-A','130-F'],
  "price":[1200,np.nan,2133,5433,np.nan,4432]},
  columns =['id','date','city','category','age','price'])
df.to_csv(my_new_file.csv,index=None)
df.shape#查看维度
df.info#数据表基本信息
df.describe()#计算基本统计数据
df.head(3)#打印出前3行,同理tail
df.dtypes#每一列的数据格式
df.columns#查看列名

df.isnull()#返回整个所有数据的T/F矩阵
df.isnull().any()#判断哪些列含有缺失值
df[df.isnull().values==True]#判断哪些行有缺失值
df.index[np.where(np.isnan(df))[0]] #返回缺失值的行索引,如果是1则返回缺失值的列索引
df.fillna(0)#df['price'].fillna(df['price'].mean())填充空值
df.dropna()#删除含缺失值的行,axis=1则删除列

df.unique()#唯一值
df.values()
df['city'].value_counts()
df['price'].std()
df['price'].cov(df['age'])
df.corr()

#dataframe以列名来获取某一列的值,用loc和iloc来索引行,loc是根据index来索引,而iloc是根据行号索引
df.drop(index=1,inplace=True,axis=1)#删除
df.loc[8,col_1]#打印第8行名为col_1的列
df.reset_index()#重设索引
df[(df['id']==1001)&(df['age']==23)]
df.sample(n=2,weight=[0,0.5,0.5,0],replace=False)

df['age'].astype('int')#更改数据类型
df.rename(columns={'category':'cate'})#更改列名称
df['city'].drop_duplicates()#删除后出现的重复值
df['city'].replace('sh','shanghai')#数据替换
df['city'].isin(['beijing'])

df.apply(lambda x:x.count(),axis=1)#axis=0时函数作用在每一列上,axis=1时函数作用在每一行上
df.groupby('year').agg(np.mean)#分组计算每一组的均值,想计算个数用size

df.sort_values(by=['age'])#按照特定的列排序
df = pd.merge(df,df1,how='inner')#how:'left'、'right'、'outer'
df = df.append(df1)
df = df.join(df1,on='date')

#绘图:pandas的两类基本数据结果series和dataframe都提供了统一的接口plot()
df.plot(x=None, y=None, kind='line', ax=None,figsize=None, title=None, grid=None, legend=True, xticks=None, yticks=None, xlim=None, ylim=None)#kind类型包括line、bar、barh、hist、box、kde、density、area、pie

matplotlib

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False#matplotlib中文显示乱码解决方法

plt.style.use('ggplot')#使用ggplot风格
fig = plt.figure('lalala', figsize = (7,7), dpi = 100, facecolor = 'y', edgecolor = 'r')#fig表示当前画布
plt.plot([1, 2, 3], [1, 2, 3])
plt.grid(True)#设置网格线
plt.xlim(-2,20)#设置坐标轴范围,同理ylim
plt.xlabel('y-label',color='pink',fontsize=40)#设置坐标轴标题,同理ylabel
plt.tick_params(labelsize=15)#坐标轴刻度字体大小
plt.title('SIN(X)',fontsize=60,color='purple',rotation=45,loc='left')#设置标题
plt.legend(['fast','normal','slow'],loc=[0.4,1.1],ncol=3)#设置图例,loc表示位置,ncol表示列数
plt.show()
fig.savefig('18011.png',dpi=50)#保存图片
#设置子画布
ax1=plt.subplot(211)#指定为2行1列画布的第一个位置
ax1.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
ax2=plt.subplot(212)    # 指定为2行1列画布的第二个位置
#print(plt.gca())
ax2.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

seaborn

import seaborn as sns
#seabron是在matplotlib的基础上进行了更高级的API封装,要求原始数据的输入类型为pandas的dataframe或Numpy数组

sns.set_style("whitegrid")#设置主题的,Seaborn有五个预设好的主题:darkgrid,whitegrid,dark,white,ticks
sns.set(style="white", palette="muted", color_codes=True)#设置主题调色板等
f, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True)
sns.distplot(d, hist=False, color="g", kde_kws={"shade": True}, ax=axes[1, 0])#displot是hist加强版
sns.boxplot(x = df_iris['class'],y = df_iris['sepal width'])#箱型图
sns.heatmap(data)#热图

sklearn

from sklearn.preprocessing import LabelEncoder#把类别数据转换成多个数字
from sklearn.preprocessing import OneHotEncoder#把类别数据转换成多列0/1数据
columns = []#类别变量
for feature in columns:
    dt[feature] = LabelEncoder().fit_transform(dt[feature])
from sklearn.model_selection import train_test_split#划分训练基测试集
x_train,x_test, y_train, y_test = train_test_split(x, y,test_size=0.2, random_state=2)
from sklearn.feature_selection import SelectKBest#特征选择Filter
sk=SelectKBest(k=120)
new_train=sk.fit_transform(x_train,y_train)
print(new_train.shape)
select_columns=sk.get_support(indices = True)
select_columns_name=x_test.columns[select_columns]
new_test=test[select_columns_name]
from sklearn.model_selection import KFold#k折交叉验证
kf=KFold(n_split=5,shuffle=False,random_state=None)
for train_index,test_index in kf.split(X):
    print('train_index:%s , test_index: %s ' %(train_index,test_index))
for fold_, (trn_idx, val_idx) in enumerate(folds.split(x_train.values, y_train.values)):
    print(fold_) 
from sklearn.metrics import accuracy_score#分类准确率
accuracy_score(y_true, y_pred)
from sklearn.metrics import recall_score#召回率
from sklearn.metrics import roc_auc_score
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error#均方差

from sklearn.ensemble import RandomForestClassifier#随机森林分类
from sklearn.ensemble import RandomForestRegressor#随机森林回归
from sklearn.ensemble import GradientBoostingRegressor#GBDT回归

clf = RandomForestClassifier(n_estimators=25,#控制弱学习器的数量,太小容易过拟合
                             max_depth=7,#树的深度,深度越大越容易过拟合
                             max_features = 10,#划分时考虑的最大特征数
                             min_samples_leaf=200,#叶子节点最少样本数
                             subsample = 0.75#采样
                            )
clf.fit(feature_train,target_train)
predict_results=clf.predict(feature_test)
from sklearn.ensemble import GradientBoostingRegressor#GBDT回归
gbdt = RandomForestRegressor(n_estimators=100,#弱学习器数量,默认为100,50到120
                             max_depth=7,#树的深度,深度越大越可能过拟合,1到20
                             max_features=2,#划分时考虑的最大特征数,1到20
                             min_samples_split=558,#叶子节点最少样本数,100到800
                             subsample=0.75)#采样比例
gbdt.fit(train_x,train_y)

xgboost

import xgboost as xgb
########  XGBoost原生接口  ##########
dtrain = xgb.DMatrix( data, label=label)
params = {
    'booster': 'gbtree',
    'objective': 'multi:softmax',  # 多分类的问题
    'num_class': 10,               # 类别数,与 multisoftmax 并用
    'gamma': 0.1,                  # 用于控制是否后剪枝的参数,越大越保守,一般0.1、0.2这样子。
    'max_depth': 12,               # 构建树的深度,越大越容易过拟合
    'lambda': 2,                   # 控制模型复杂度的权重值的L2正则化项参数,参数越大,模型越不容易过拟合。
    'subsample': 0.7,              # 随机采样训练样本
    'colsample_bytree': 0.7,       # 生成树时进行的列采样
    'min_child_weight': 3,
    'silent': 1,                   # 设置成1则没有运行信息输出,最好是设置为0.
    'eta': 0.007,                  # 如同学习率
    'seed': 1000,
    'nthread': 4,                  # cpu 线程数
}

num_round = 10
bst = xgb.train( plst, dtrain, num_round, evallist )
dtest = DMatrix(X_test)
ans = model.predict(dtest)

######		sklearn接口	##########
model = xgb.XGBClassifier(max_depth=5, learning_rate=0.1, n_estimators=160, silent=True, objective='multi:softmax')#XGBRegressor
model.fit(X_train, y_train)

hyperopt

hyperopt是利用贝叶斯优化进行自动调参的工具包

import hyperopt
from hyperopt import hp, fmin, tpe, STATUS_OK, Trials
from sklearn.ensemble import RandomForestRegressor

obj_call_count = 0
cur_best_score = 0
def objective(params):
    global obj_call_count, cur_best_score
    obj_call_count += 1
    print('
GBDT objective call #{} cur_best_score={:7.5f}'.format(obj_call_count,cur_best_score) )

    folds = KFold(n_splits=5, shuffle=True, random_state=2333)
    oof_lgb = np.zeros(len(x_train))
    
    for fold_, (trn_idx, val_idx) in enumerate(folds.split(x_train.values, y_train.values)):
        print("fold {}".format(fold_))
        trn_data = x_train.iloc[trn_idx]
        val_data = x_train.iloc[val_idx]
        trn_y = y_train.iloc[trn_idx]        
        gbdt = RandomForestRegressor(**params)
        gbdt.fit(trn_data,trn_y)        
        oof_lgb[val_idx] = clf.predict(val_data)    
    score = r2_score(y_train,oof_lgb)
    print('val_r2_score={}'.format(score))
    if score>cur_best_score:
        cur_best_score = score
        print('NEW BEST SCORE={}'.format(cur_best_score))
    return {'loss': -score, 'status': STATUS_OK}

space ={
        'n_estimators':  hp.choice ('n_estimators', range(50,120)),
        'max_depth': hp.choice('max_depth', range(1,20)),
        'min_samples_split': hp.choice ('min_samples_split', range(100,800)),
        'max_features':hp.choice('max_features',range(7,20)),
        'random_state':2020
       }

trials = Trials()
best = hyperopt.fmin(fn=objective,
                     space=space,
                     algo=HYPEROPT_ALGO,
                     max_evals=N_HYPEROPT_PROBES,
                     trials=trials,
                     verbose=1)
print('-'*20)
print(best)

pickle

  • 针对数据量比较大的列表、字典,可以采用将其加工为pickle来调用,减小文件大小
  • 只能在python中使用,只支持python的基本数据类型

1.利用pickle包

#pickle.dump
import pickle
f = open('data_one.pkl', 'wb')
datas = {'name': 'oscar', 'age': 25, 'high': 175}
data_one = pickle.dump(datas, f, -1)
f.close()
#pickle.load
f = open('data_one.pkl','rb')
print(pickle.load(f))
f.close()

2.pandas库

import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(20).reshape(4, 5))
df.to_pickle('foo.pkl')
dr = pd.read_pickle('foo.pkl')

HDF5

hdf5文件相比pickle,读取速度更快,更加方便。
hdf5支持压缩,使用的方式是blosc,这个是速度最快也是pandas默认支持的。 使用压缩可以提磁盘利用率,节省空间。 开启压缩也没有什么劣势,只会慢一点点。 压缩在小数据量的时候优势不明显,数据量大了才有优势。 同时发现hdf读取文件的时候只能是一次写,写的时候可以append,可以put,但是写完成了之后关闭文件,就不能再写了,会覆盖。
写入文件

import numpy as np
import pandas as pd
####生成9000,0000条数据,9千万条
a = np.random.standard_normal((90000000,4))
b = pd.DataFrame(a)
####普通格式存储:
h5 = pd.HDFStore('/data/stock/test_s.h5','w')
h5['data'] = b
h5.close()
 
####压缩格式存储
h5 = pd.HDFStore('/data/stock/test_c4.h5','w', complevel=4, complib='blosc')
h5['data'] = b
h5.close()

读取文件

data=pd.read_hdf('/data/stock/test_c4.h5',key='data')

logging模块

可以设置不同的等级,在release版本中只输出重要信息而不输出debug过程中的信息

logging的日志可以分为 debug(), info(), warning(), error(), critical()5个级别

import logging
logging.basicConfig(level=logging.INFO,format = '%(asctime)s-%(name)s-%(levelname)s-%(message)s')
logger = logging.getLogger(__name__)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")

warning模块

import warnings
warnings.filterwarnings('ignore')

忽略警告信息

tensorflow

"tensor"(张量)意味着N维数组。“flow”意味着基于数据流图的计算,“tensorflow”为张量从数据流图的一端流动到另一端的计算过程。

数据流图由节点和边组成,节点代表数值操作(比如加法、乘法、卷积和池化等),代表流动的张量。一次计算由输入节点开始,产生的张量在图中流动,经过不同操作节点时进行各种数值计算,最后产生张量结果输出。

张量是一个N维数组,比如零维张量就是数字(标量),一维张量就是向量,二维张量就是矩阵。

tensorflow中的计算操作通过操作(operation)来进行, 操作是数据流图中的一个节点,对张量进行操作。一个操作节点的输入是零个或者多个张量对象,输出是零个或者多个张量。操作对象通过python初始化来得到。

对于一个计算图来说,每个节点将零个或多个张量作为输入,并产生张量作为输出。一种类型的节点是一个常量。像所有tensorflow常量一样,它不需要输入,而是输出一个内部存储的值。

会话(session)是tensorflow中用于控制数据流图执行的对象。运行session.run()可以执行你想要运算的部分获得运算结果。为了进行计算,数据流图需要在会话中启动,而会话会将图的操作分发给CPU或者GPU等设备执行后返回tensor结果

tensorflow通过变量来维护图执行过程中的状态信息。变量在计算过程中是可变的,并且在训练过程中会自动更新或优化。变量必须先被初始化,然后可以在训练时和训练后保存到磁盘中或者再恢复保存的变量值来训练和测试模型。

占位符用来给计算图提供输入,常用于传递训练样本

tensorflow中还提供了优化器,可以按照一定的规则优化每个变量以最大限度地减少损失函数。最简单地优化器是梯度下降。

spyder

spyder连接远程服务器

  • 安装spyder-kernels
  • 服务器端用命令 “python -m spyder_kernels.console”开启一个kernel
  • 服务器端用命令 “jupyter --runtime-dir” 找到kernel文件)所在的路径
  • spyder查看是否安装paramiko
  • spyder连接
原文地址:https://www.cnblogs.com/rjxu/p/13225271.html