說一下幾點思考方法:
with open('ONE.TXT',mode='r+',encoding='utf-8') as f: data = f.read()
包括但不限于:數(shù)據(jù)大小、維度、類型、含義、排序、索引等
1. data.info()2. data.head()3. data.loc[]4. data.shape5. data.dtype6. data.sort_values(by=['A'],ascending=False)7. data.reset_index(drop=True,inplace=True)8. data['F'].values9. data['F'].value_counts()
統(tǒng)計分析、相關(guān)性分析、圖形分析(散點圖、直方圖、計數(shù)圖、柱狀圖、熱力圖)等
data.corr() #method = 'pearson', 'spearman', 'kendall'
seaborn.scatterplot(x=None, y=None, hue=None, style=None, size=None, data=None)
mask = np.zeros_like(data.corr())mask[np.tril_indices_from(mask)]=Trueseaborn.heatmap(data.corr(),mask=mask,annot=True,fmt='.2f')
seaborn.distplot(x=data['A'])
seaborn.countplot(X='G',data=data)
x是名稱,y是數(shù)量
plt.bar(x,y)
plt.pie(data['A'])
繪制成一張圖
import seabornimport matplotlib.pyplot as pltplt.style.use('seaborn-whitegrid')fig = plt.figure(figsize=(20,10))fig.subplots_adjust(wspace=0.5,hspace=0.5)for i,column in enumerate (data.columns): ax = fig.add_subplot(3,5,i+1) ax.set_title(column) if data.dtypes[column] == np.object: g = seaborn.countplot(y=column,data=data) plt.xticks(rotation=25) else: g = seaborn.distplot(data[column]) plt.xticks(rotation=25)
更多繪圖請看Seaborn常見繪圖總結(jié)
data.replace('XXX',np.NaN,inplace=True)data.loc[data['G']=='F','G'] = 'K'
使用pandas模塊
data.isnull().any() #查看那些列存在缺失data.isnull().sum() #統(tǒng)計缺失值數(shù)量data[data.isnull().values==True] #篩選出所有的缺失值data.isnull().sum()/data.shape[0] #計算缺失值比例(data.isnull().sum()/data.shape[0]).plot.bar() #缺失值比例柱狀圖
使用missingno
#安裝pip install missingnomissingno.matrix(df1, labels=True) # 無效數(shù)據(jù)密度顯示missingno.bar(df1) # 條形圖顯示missingno.heatmap(df1) # 熱圖相關(guān)性顯示
使用pandas模塊
data.dropna(axis=0,subset=['A'])
data['A'].fillna(data['A'].mean())# mean、median、mode().iloc[0]
使用
sklearn.impute.SimpleImputer模塊
simple = SimpleImputer(missing_values=nan, strategy=’mean’, fill_value=None)# strategy = mean、median、most_frequent、constantsimple.fit_transform(data)
seaborn.kdeplot(data['A']) #繪制核密度圖查看數(shù)據(jù)分布def xigema(X): lower = X.mean() - 3 * X.std() upper = X.mean() + 3 * X.std() X = (X < lower) | (X > upper) return X#查看那些列存在缺失data[xigema(data)==True].any()#查看所有缺失的數(shù)據(jù)data[data[xigema(data)==True].any(1)]
seaborn.boxplot(data['A']) #繪制箱線圖查看數(shù)據(jù)分布def box(X,IQR): lower = X.quantile(0.25) - IQR * (X.quantile(0.75) - X.quantile(0.25)) upper = X.quantile(0.75) + IQR * (X.quantile(0.75) - X.quantile(0.25)) X = (X < lower) | (X > upper) return X#查看那些列存在缺失data[box(data,1.5)==True].any()#查看所有缺失的數(shù)據(jù)data[box(data,1.5)==True].any(1)]
# 異常值會被NaN代替,然后當作缺失值處理data[xigema(data)==False]
# 使用mask判斷data.mask(xigema(data),np.NaN)
pd.get_dummies(data,columns=['F','G'])#使用sklearnsklearn.preprocessing.OneHotEncoder(sparse=False).fit_transform(data['F'].values.reshape(-1,1))
# 全量替換(包括數(shù)值),注意記得只編碼非數(shù)值有序變量labelencoder = LabelEncoder()data[['G','F']].apply(labelencoder.fit_transform)
加、減、乘、除、取對數(shù)、構(gòu)造多項式等
data['K'] = data['A'] + data['B']data['M'] = np.log10(data['A'])
data.drop(index=data[data['G']==0].index) #默認刪除包含0的行,axis=1,刪除列del data['K']
在不改變數(shù)據(jù)相對大小的情況下,只關(guān)心元素之間的大小關(guān)系
from sklearn.preprocessing import KBinsDiscretizer# strategy=quantile-等頻,uniform-等寬,kmeans-聚類kbins = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='quantile')pd.DataFrame(kbins.fit_transform(data),columns=data.columns)
from sklearn.feature_selection import VarianceThreshold,chi2,mutual_info_classifX_var=VarianceThreshold(threshold=0.5).fit_transform(X, y) #使用閾值0.5 進行選擇
X_chi2 = SelectKBest(chi2, k=2).fit_transform(X, y)
X_mut = SelectKBest(mutual_info_classif, k=2).fit_transform(X, y)
from sklearn.feature_selection import SelectFromModelfrom sklearn.ensemble import RandomForestClassifier as RFCRFC_ = RFC(n_estimators =10,random_state=0) #先隨機森林的實例化X_embedded = SelectFromModel(RFC_,threshold=0.005).fit_transform(X,y) #在這里我只想取出來有限的特征。X_embedded.shape #(42000,47)#模型的維度明顯被降低了 #通過學(xué)習(xí)曲線來找最佳閾值import numpy as npimport matplotlib.pyplot as pltthreshold = np.linspace(0,(RFC_.fit(X,y).feature_importances_).max(),20)#0到feature_importances_最大值平均取20個score = []for i in threshold: X_embedded = SelectFromModel(RFC_,threshold=i).fit_transform(X,y) once = cross_val_score(RFC_,X_embedded,y,cv=5).mean() score.append(once)plt.plot(threshold,score)plt.show()
from sklearn.feature_selection import RFEfrom sklearn.linear_model import LogisticRegressionx_rfe = RFE(estimator=LogisticRegression(), n_features_to_select=3).fit(X, y)print(x_rfe.n_features_ ) # 所選特征的數(shù)量print(x_rfe.support_ ) # 按特征對應(yīng)位置展示所選特征,True 表示保留,F(xiàn)alse 表示剔除。print(x_rfe.ranking_ ) # 特征排名,使得 ranking_[i]對應(yīng)于第 i 個特征的排名位置,1 表示最優(yōu)特征。x_rfe.transform(X)
降維訓(xùn)練前需要對數(shù)據(jù)標準化
from sklearn.decomposition import PCAfrom sklearn import preprocessing # 調(diào)用預(yù)處理模塊X_std = preprocessing.scale(X)# 降維訓(xùn)練前需要對數(shù)據(jù)標準化pca = PCA(n_components=2).fit(X_std) # 保留 2 個主成分X_pca =pca.transform(X_std)print(pca.explained_variance_ratio_) # 查看利用 PCA 方法降維后保留的 2 個維度的信息量大小plt.subplot(1,2,1)plt.bar(range(0, pca.explained_variance_ratio_.size), pca.explained_variance_ratio_)#繪制 LDA 降維后不同簇與 y 的散點圖colors = ['r', 'b', 'g']markers = ['s', 'x', 'o']plt.subplot(1,2,2)for l, c, m in zip(np.unique(y), colors, markers): plt.scatter(X_pca[y==l, 0], X_pca[y==l,1], c=c, label=l, marker=m) # 散點圖plt.xlabel('pca1')plt.ylabel('pca2')plt.title('PCA')plt.legend(loc='lower left')plt.show()
一般在有標簽的分類問題上,對數(shù)據(jù)降維,建議優(yōu)先考慮有監(jiān)督的 LDA 降維方法,結(jié)果一般會更加準確。
#此處與 PCA 方法不同,不必對原始數(shù)據(jù)進行標準化就能有較好的降維效果from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDAlda = LDA(n_components=2).fit(X,y)print(lda.explained_variance_ratio_) # 查看利用 LDA 方法降維后保留的 2 個維度的信息量大小plt.subplot(1,2,1)plt.bar(range(0, lda.explained_variance_ratio_.size), lda.explained_variance_ratio_)X_lda =lda.transform(X)#繪制 LDA 降維后不同簇與 y 的散點圖,通過兩種降維后的散點圖對比不同方法的效果。colors = ['r', 'b', 'g']markers = ['s', 'x', 'o']plt.subplot(1,2,2)for c,l,m in zip(colors, np.unique(y), markers): plt.scatter(X_lda[y == l, 0], X_lda[y == l, 1], c=c, label=l, marker=m)plt.xlabel('lda1')plt.ylabel('lda2')plt.title('LDA')plt.legend(loc='lower left')plt.show()
from sklearn.model_selection import train_test_split# 30%數(shù)據(jù)用于測試,70%用于訓(xùn)練,42是隨機種子Xtrain, Xtest, Ytrain, Ytest = train_test_split(X,y,test_size=0.3,random_state=420)
from sklearn.preprocessing import StandardScaler,MinMaxScalerscaler = StandardScaler().fit(Xtrain)X_train_std = scaler.transform(Xtrain)X_test_std = scaler.transform(Xtest)
最小-最大規(guī)范化對原始數(shù)據(jù)進行線性變換,變換到[0,1]區(qū)間
from sklearn.preprocessing import MinMaxScalerminmax = MinMaxScaler().fit(Xtrain)X_train_std = minmax.transform(Xtrain)X_test_std = minmax.transform(Xtest)
rfc = RandomForestClassifier(random_state=42) #建立模型: 隨機森林rfc = rfc.fit(Xtrain, Ytrain) # 訓(xùn)練模型: 隨即森林print(rfc.feature_importances_) #特征重要性
rfc.predict(Xtest)
類 | 含義 |
sklearn.metrics.confusion_matrix | 混淆矩陣 |
sklearn.metrics.accuracy_score | 準確率accuracy |
sklearn.metrics.precision_score | 精確度precision |
sklearn.metrics.recall_score | 召回率recall |
sklearn.metrics.precision_recall_curve | 精確度-召回率平衡曲線 |
sklearn.metrics.f1_score | F1-Score |
sklearn.metrics.roc_auc_score | ROC |
sklearn.metrics.plot_roc_curve | ROC繪圖 |
sklearn.metrics.plot_precision_recall_curve | P-R曲線繪圖 |
sklearn.metrics.plot_confusion_matrix | 混淆舉證繪圖 |
from sklearn.metrics import accuracy_score, precision_score, f1_score, roc_auc_score, recall_scorerecall_score(y_true, y_pred, average='micro')
繪圖
from sklearn.metrics import plot_confusion_matrix,plot_precision_recall_curve,plot_roc_curvefrom sklearn.svm import SVCX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)clf = SVC(random_state=42)clf.fit(X_train, y_train)#混淆舉證plot_confusion_matrix(clf, X_test, y_test,normalize='true')#P-R曲線plot_precision_recall_curve(clf, X_test, y_test)#ROC曲線plot_roc_curve(clf, X_test, y_test)
from sklearn.model_selection import GridSearchCV,RandomizedSearchCVparam_grid = {'n_estimators' : np.arange(100,200,10), 'max_depth' : np.arange(1, 20, 1), 'max_features' : np.arange(5,30,1), 'criterion' : ['gini', 'entropy'] }rfc = RandomForestClassifier(random_state=42)GS = GridSearchCV(rfc,param_grid,cv=10,scoring='roc_auc')GS.fit(X,y)print(GS.best_params_) # 最優(yōu)參數(shù)print(GS.best_score_) # 最優(yōu)得分print(GS.best_estimator_) # 最有分類器
from sklearn.model_selection import cross_val_scorecross_val_score(rfc, X, y, cv=5,scoring='roc_auc')
from sklearn import svm from sklearn import datasetsimport joblib# sklearn.externals.joblib函數(shù)是用在0.21及以前的版本中,在最新的版本中,該函數(shù)應(yīng)被棄用改為直接導(dǎo)入joblib# from sklearn.externals import joblibclf = svm.SVC()clf.fit(X,y) # 保存訓(xùn)練好的clf模型 joblib.dump(clf,'clf.pkl') # 重新加載訓(xùn)練好的clf模型 clf = joblib.load('clf.pkl') # 打印預(yù)測值print(clf.predict(X[0:1000]))
聯(lián)系客服