按升序/降序排列条形图

时间:2018-12-31 02:37:02

标签: python scikit-learn visualization sklearn-pandas

我有一个随机森林特征重要性程序。已为每个变量生成了所有功能重要性参数。我也将其绘制在水平条形图上。

现在,我想将条形按升/降序排序。我该怎么做?

我的代码如下:

#Feature Selection (shortlisting key variables)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel
from sklearn.metrics import accuracy_score

df = pd.read_excel(r'C:\Users\z003v0ee\Desktop\TP Course\project module\ProjectDataSetrev4.xlsx',sheet_name=0)
df2 = pd.read_excel(r'C:\Users\z003v0ee\Desktop\TP Course\project module\ProjectDataSetrev4.xlsx',sheet_name=1)

## Convert date time format and set as index
df['DateTime']=pd.to_datetime(df['Time Stamp'], format='%Y-%m-%d %H:%M:%S')
df.set_index(df['DateTime'], inplace=True)

## Save each feature to a list (independent variables)
allvarlist = list()
for each_var in df2.columns:
    allvarlist.append(each_var)

countvar = len(allvarlist)
allvar = df[allvarlist]
allvar = allvar.values.reshape(len(allvar),countvar)

## Define dependent variable
target = df['(CUP) Chiller Optimization Plant Efficiency [kW/RT]']
target=target.values.reshape(len(target),1)

## Split into training and test data
allvar_train,allvar_test,target_train,target_test= train_test_split(allvar,target, random_state=0, test_size=0.7)

## Choose a model
clf = RandomForestRegressor(n_estimators=10000, random_state=0, n_jobs=-1)
#print(allvar_train)
#print(target_train)

clf.fit(allvar_train,np.ravel(target_train))

## Show feature importance results
for feature in zip(allvarlist, clf.feature_importances_):
    print(feature)

## Plot feature importance results
importances = clf.feature_importances_
#indices = np.argsort(importances)

plt.figure().set_size_inches(14,16)
plt.barh(range(allvar_train.shape[1]), importances, color="r")
plt.yticks(range(allvar_train.shape[1]),allvarlist)

我的图看起来像this

绘制水平条形图的更新代码:

plt.figure(figsize=(14,16))
df3=pd.DataFrame({'allvarlist':range(countvar),'importances':allvarlist})
df3.sort_values('importances',inplace=True)
df3.plot(kind='barh',y='importances',x='allvarlist',color='r')

仍然不起作用。错误是“ TypeError:空的DataFrame:没有要绘制的数字数据”

还有其他建议吗?

1 个答案:

答案 0 :(得分:0)

您可以做这样的事情! 向allVarlist输入特征名称。

plt.figure(figsize=(14,16))
df=pd.DataFrame({'allvarlist':range(5),'importances':np.random.randint(50,size=5)})
df.sort_values('importances',inplace=True)
df.plot(kind='barh',y='importances',x='allvarlist',color='r')

enter image description here

编辑:

plt.figure(figsize=(14,16))
df3=pd.DataFrame({'allvarlist':allvarlist,'importances':clf.feature_importances_})
df3.sort_values('importances',inplace=True)
df3.plot(kind='barh',y='importances',x='allvarlist',color='r')