python关于机器学习和深度学习经常用到的代码
显示中文字体、负号
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #python用来显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
将特征和标签合并成一张表
import pandas as pd
pd.concat([pd.DataFrame(wine.data),pd.DataFrame(wine.target)],axis=1)
打包展开对象
[*zip(feature_name,clf.feature_importances_)]#注意zip和range一样,是一个惰性对象,需要对其进行展开。
实例
以上实例运用过程见链接实例1
用GridSearchCV寻找最优参数
param = {
'criterion': ['gini','entropy'],
'max_depth': [30, 50, 60, 100],
'min_samples_leaf': [2, 3, 5, 10],
'min_impurity_decrease': [0.1, 0.2, 0.5]
}
grid = GridSearchCV(DecisionTreeClassifier(), param_grid=param, cv=6)
grid.fit(x_train, y_train)
print('最优分类器:', grid.best_params_, '最优分数:', grid.best_score_) # 得到最优的参数和分值
DecisionTreeClassifier()是评估类型,可以进行替换,param是需要进行筛选的参数,x_train, y_train是训练数据
plt画单,多图
fig=plt.figure(figsize=(12,8))
ax=fig.add_subplot(121)
ax.scatter(df[:50]['sepal length'], df[:50]['sepal width'], label='0')
ax.set_xlabel('sepal length', fontsize=18)
ax.set_ylabel('sepal width', fontsize=18)
plt.legend()
ax=fig.add_subplot(122)
ax.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1')
ax.set_xlabel('sepal length', fontsize=18)
ax.set_ylabel('sepal width', fontsize=18)
plt.legend()
plt.show()
单图
plt.subplots(figsize=(12,8))
#plt.figure()
plt.scatter(df[:50]['sepal length'], df[:50]['sepal width'], label='0')
plt.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1')
plt.xlabel('sepal length', fontsize=18)
plt.ylabel('sepal width', fontsize=18)
plt.legend()
plt.show()
PCA降维
def pca(X):
# normalize the features
X = (X - X.mean()) / X.std()
# compute the covariance matrix
X = np.matrix(X)
cov = (X.T * X) / X.shape[0]
# perform SVD
U, S, V = np.linalg.svd(cov)
return U, S, V
#恢复数据,实际上并不上完全恢复,只是主要对轴线恢复
#这也是进行降维的作用,相当于提取主要特征
def project_data(X, U, k):
U_reduced = U[:,:k]
return np.dot(X, U_reduced)
忽略警告信息
import warnings
warnings.simplefilter("ignore")
具体其它信息见链接warnings