text_plain_output_1.png image_output_1.png
from sklearn.ensemble import RandomForestRegressor

from sklearn.metrics import mean_absolute_error

from sklearn.model_selection import train_test_split

from sklearn.tree import DecisionTreeRegressor

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

df = pd.read_csv('../input/data.csv')

list(df.columns)

def clean_d(string):
    last_char = string[-1]
    if last_char == '0':
        return 0
    string = string[1:-1]
    num = float(string)
    if last_char == 'K':
        num = num * 1000
    elif last_char == 'M':
        num = num * 1000000
    return num

df['Wage_Num'] = df.apply(lambda row: clean_d(row['Wage']), axis=1)

df['Value_Num'] = df.apply(lambda row: clean_d(row['Value']), axis=1)

df.shape

df.isna().sum()

df = df.dropna(axis=0, subset=['Preferred Foot'])
df.isna().sum()

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from learntools.core import *
y = df.Overall
features = ['Age', 'Value_Num', 'Wage_Num', 'Potential']
X = df[features]
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)
ml_model = DecisionTreeRegressor(random_state=1)
ml_model.fit(train_X, train_y)
val_predictions = ml_model.predict(val_X)
val_mae = mean_absolute_error(val_predictions, val_y)

rf_model = RandomForestRegressor(random_state=1)
rf_model.fit(train_X, train_y)
rf_val_predictions = rf_model.predict(val_X)
rf_val_mae = mean_absolute_error(rf_val_predictions, val_y)
print('Validation MAE for Random Forest Model: {:,.0f}'.format(rf_val_mae))
print(train_X)
print(train_y)
print(val_X)
print(val_predictions)
print(val_y)