<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Coal prediction in mines 2013
by Bad Wizard  
Abstract
Step1:  Cleaned data
We cleaned this data in the notebook stored in
Step2:  Predict the Production of coal mines
Step3:  first, look at the interplay between each possible predictor and the target variable
Step4:  Random Forest Regressor
<ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import explained_variance_score, r2_score, mean_squared_error
sns.set();
Explanation: Coal prediction in mines 2013
by Bad Wizard  
Abstract: We did a lot of analysis and came to some interesting conclusions.
End of explanation
df = pd.read_csv('../data/cleaned_coalpublic2013.csv',header=0,index_col='MSHA ID')
df[['Year','Mine_Name']].head()
Explanation: Cleaned data
We cleaned this data in the notebook stored in: deliver/Data_cleaning.ipynb
End of explanation
features = ['Average_Employees',
            'Labor_Hours',
          ]
categoricals = ['Mine_State',
                'Mine_County',
                'Mine_Status',
                'Mine_Type',
                'Company_Type',
                'Operation_Type',
                'Union_Code',
                'Coal_Supply_Region',
          ]
target = 'log_production'
Explanation: Predict the Production of coal mines
End of explanation
fig = plt.subplots(figsize = (14,8))
sns.set_context('poster')
sns.violinplot(y='Company_Type',x='log_production', data=df,
              split=True, inner = 'stick',)
plt.tight_layout()
plt.savefig("../figures/Coal_prediction_company_type_vs_log_production.png")
dummy_categoricals = []
for categorical in categoricals:
    drop_var = sorted(df[categorical].unique())[-1]
    temp_df = pd.get_dummies(df[categorical],prefix=categorical)
    df = pd.concat([df,temp_df],axis = 1)
    temp_df.drop('_'.join([categorical, str(drop_var)]), axis = 1, inplace = True)
    dummy_categoricals +=temp_df.columns.tolist()
Explanation: first, look at the interplay between each possible predictor and the target variable
End of explanation
train, test = train_test_split(df, test_size = 0.3)
rf = RandomForestRegressor(n_estimators=100, oob_score=True)
rf.fit(train[features + dummy_categoricals], train[target])
sns.set_context('poster')
fig = plt.subplots(figsize = (8,8))
sns.regplot(test[target],rf.predict(test[features + dummy_categoricals]),color='green')
plt.ylabel('Predicted log_production')
plt.xlim(0, 22)
plt.ylim(0, 22)
plt.tight_layout()
plt.savefig('../figures/Coal-production-RF-prediction.png')
predicted = rf.predict(test[features + dummy_categoricals])
print('R^2 score:',r2_score(test[target], predicted))
print("Explained variance score:", explained_variance_score(test[target], predicted))
print('MSE:', mean_squared_error(test[target], predicted))
# find out the relative importance of each feature
rf_importances = pd.DataFrame({'name':train[features + dummy_categoricals].columns,
                              'importance':rf.feature_importances_
                              }).sort_values(by='importance', 
                                             ascending = False).reset_index(drop=True)
rf_importances[:5]
Explanation: Random Forest Regressor
End of explanation
<END_TASK>