In [1]:
import pandas as pd
import numpy as np
df = pd.read_csv('housing.csv') # df = document frequency
df
Out[1]:
In [2]:
# Para ver apenas as features
df[:0]
Out[2]:
In [3]:
# Aqui vai melhor (para ver as features):
df.columns
Out[3]:
In [4]:
df.info()
In [5]:
# aqui para obter direto a quantidade de linhas e colunas, respectivamente
print(df.shape)
In [6]:
# para obter apenas a quantidade de linhas
print(df.shape[0])
In [7]:
# verificando o tipo de variável, é int!
type(df.shape[0])
Out[7]:
In [8]:
# e aqui a quantidade de colunas
print(df.shape[1])
In [9]:
type(df.shape[1])
Out[9]:
In [10]:
# obtendo os atributos (features)
print(df.keys())
In [11]:
print(df.dtypes) # para obter os tipos de todos os atributos
In [12]:
# imprimir as primeiras 10 linhas apenas
df.head(10)
Out[12]:
In [13]:
# imprimir as 10 últimas linhas
df.tail(10)
Out[13]:
In [14]:
df.iloc[0]
Out[14]:
In [15]:
# para acessar a coluna 'longitude'
df.longitude
Out[15]:
In [16]:
# acessando o valor da longitude na primeira linha
df.iloc[0].longitude
Out[16]:
In [17]:
# apenas a mediana dos preços das casas
df.median_house_value
Out[17]:
In [18]:
df.iloc[0].median_house_value # o primeiro valor do preço
Out[18]:
In [19]:
# método braçal para obter o maior valor da mediana dos preços das casas
rows = df.shape[0]
higher = df.iloc[0].median_house_value # atribuindo o primeiro valor como o maior
for i in range(rows):
if df.iloc[i].median_house_value > higher:
higher = df.iloc[i].median_house_value
higher
Out[19]:
In [20]:
# método braçal para obter o menor valor da mediana dos preços das casas
lower = df.iloc[0].median_house_value # atribuindo o primeiro valor como o menor
for i in range(rows):
if df.iloc[i].median_house_value < lower:
lower = df.iloc[i].median_house_value
lower
Out[20]:
In [21]:
# Método Braçal para obter a média dos valores da mediana dos preços das casas
mean = 0
for i in range(rows):
mean += df.iloc[i].median_house_value
mean /= rows
mean
Out[21]:
In [22]:
format(mean, '.2f')
Out[22]:
In [23]:
# Método mais prático:
print('Max value of median_house_value:' , format(np.max(df.median_house_value), '.2f'))
print('Min value of median_house_value:' , format(np.min(df.median_house_value), '.2f'))
print('Mean value of median_house_value:' , format(np.mean(df.median_house_value), '.2f'))
In [24]:
# obter os diferentes valores de 'ocean proximity'
df['ocean_proximity'].value_counts()
Out[24]:
In [25]:
# função describe() do Pandas mostra um resumão dos dados, com a quantidade (count), média (mean),
# desvio padrão (std = standard deviation), valor mínimo (min), 25º, 50º e 75º percentil, valor máximo (max)
df.describe()
Out[25]:
In [26]:
# alterando o valor da precisão, para duas casas decimais:
pd.set_option('precision', 2) # https://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html#pandas.set_option
df.describe()
Out[26]:
In [27]:
# exibir histogramas
import matplotlib.pyplot as plt # https://matplotlib.org/api/pyplot_api.html
df.hist(sharex=False, sharey=False, xlabelsize=1, ylabelsize=1)
# https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist
plt.show()
# os parâmetros sharex, sharey, xlabelsize e ylabelsize aqui são apenas para dispor melhor os gráficos...
In [28]:
# Outro modo com mais detalhes:
%matplotlib inline
df.hist(bins=50, figsize=(20,15))
# save_fig("attribute_histogram_plots")
plt.show()
In [29]:
df['median_house_value'].hist()
Out[29]:
In [30]:
# Histograma do median_house_value
#hist(x, bins=None, range=None, normed=False, weights=None, cumulative=False, bottom=None,
# histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None,
# label=None, stacked=False, hold=None, data=None, **kwargs)
df.hist('median_house_value', bins=50, figsize=(20,15))
plt.show()
In [31]:
# Mostrando os Quartis:
# boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None,
# bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None,
# showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None,
# meanprops=None, capprops=None, whiskerprops=None, manage_xticks=True, autorange=False, zorder=None,
# hold=None, data=None)
df.boxplot("median_house_value", patch_artist=True)
Out[31]:
In [32]:
df.hist('median_house_value', bins=50, figsize=(20,15))
plt.axvline(df['median_house_value'].mean(), color='g', linestyle='dashed', linewidth=2) # traço do valor médio em verde
plt.axvline(np.percentile(df['median_house_value'], [25]), color='b', linestyle='dashed', linewidth=2) # traço do 1º Quartil, em azul
plt.axvline(np.percentile(df['median_house_value'], [50]), color='r', linestyle='dashed', linewidth=2) # traço do 2º Quartil, em vermelho
plt.axvline(np.percentile(df['median_house_value'], [75]), color='m', linestyle='dashed', linewidth=2) # traço do 3º Quartil, em roxo
plt.show()
In [33]:
q1 = 0
for i in df['median_house_value']:
if i <= 119600.00:
q1 += 1
q1
Out[33]:
In [34]:
q2 = 0
for i in df['median_house_value']:
if i > 119600.00 and i <= 179700.00:
q2 += 1
q2
Out[34]:
In [35]:
q3 = 0
for i in df['median_house_value']:
if i > 179700.00 and i <= 264725.00:
q3 += 1
q3
Out[35]:
In [36]:
q4 = 0
for i in df['median_house_value']:
if i > 264725.00:
q4 += 1
q4
Out[36]:
In [37]:
q1+q2+q3+q4 == len(df['median_house_value'])
Out[37]:
In [38]:
# exibir a densidade
# https://pandas.pydata.org/pandas-docs/version/0.18.1/generated/pandas.DataFrame.plot.html
df.plot(kind='density', subplots=True, layout=(3, 3), sharex=False, sharey=False, legend=False, fontsize=1)
plt.show()
# legendas retiradas para ficarem legíveis os gráficos.
In [39]:
# ...senão:
df.plot(kind='density', subplots=True, layout=(3, 3), sharex=False, sharey=False, legend=True, fontsize=1)
plt.show()
# porém, vemos aqui que não está na mesma ordem que os do histograma!
E agora uma matriz de correlação:
In [40]:
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(df.corr(), vmin=-1, vmax=1, interpolation='none')
fig.colorbar(cax)
ticks = np.arange(0,14,1)
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xticklabels(df.keys(), rotation = 'vertical') # https://matplotlib.org/devdocs/api/_as_gen/matplotlib.axes.Axes.set_yticklabels.html#matplotlib-axes-axes-set-yticklabels
ax.set_yticklabels(df.keys())
plt.show()
In [41]:
# outra forma para matriz de correlação, usando seaborn
import seaborn as sns
import matplotlib.pyplot as plt
sns.heatmap(df.corr())
plt.show()
Aqui uns testes para aplicar nos dados das casas. Verificando a função train_test_split, se ela divide aleatóriamente os dados de treinamento e teste.
In [42]:
# http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
# Verificando se divide de forma aleatória os dados.
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)
In [43]:
X
Out[43]:
In [44]:
list(y)
Out[44]:
In [45]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
Por padrão, pega dados aleatóriamente.
Sobre o random_state: Can be any integer between 0 and 2**32 - 1 inclusive, an array (or other sequence) of such integers, or None (the default). If seed is None, then RandomState will try to read data com /dev/urandom (or the Windows analogue) if avaliable os seed from the clock otherwise.
data_train, data_test, labels_train, labels_test = train_test_split(data, labels, test_size=0.20, random_state=42)
In [46]:
X_train
Out[46]:
In [47]:
X_test
Out[47]:
In [48]:
y_train
Out[48]:
In [49]:
y_test
Out[49]:
In [50]:
# Testando agora para apenas um conjunto de dados X:
X = np.arange(10).reshape((5, 2))
X_train, X_test = train_test_split(X, test_size=0.33, random_state=42)
In [51]:
X_train
Out[51]:
In [52]:
X_test
Out[52]:
It works!
In [53]:
from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split(df, test_size=0.3, random_state=42)
In [54]:
test_set.head()
Out[54]:
In [55]:
test_set.tail()
Out[55]:
In [56]:
df["median_income"].hist()
Out[56]:
In [57]:
# Divide por 1.5 para limitar o número de categorias de renda
df["income_cat"] = np.ceil(df["median_income"] / 1.5)
# Categoriza-os de 1 a 5
df["income_cat"].where(df["income_cat"] < 5, 5.0, inplace=True)
In [58]:
df["income_cat"].value_counts()
Out[58]:
In [59]:
df["income_cat"].hist()
Out[59]:
In [60]:
from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(df, df["income_cat"]):
strat_train_set = df.loc[train_index]
strat_test_set = df.loc[test_index]
In [61]:
strat_test_set["income_cat"].value_counts() / len(strat_test_set)
Out[61]:
In [62]:
df["income_cat"].value_counts() / len(df)
Out[62]:
In [63]:
for set_ in (strat_train_set, strat_test_set):
set_.drop("income_cat", axis=1, inplace=True)
In [64]:
df = strat_train_set.copy()
In [65]:
df = strat_train_set.copy()
df.plot(kind="scatter", x="longitude", y="latitude")
Out[65]:
In [66]:
df.plot(kind="scatter", x="longitude", y="latitude", alpha=0.1)
Out[66]:
In [67]:
df.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4,
s=df["population"]/100, label="population", figsize=(10,7),
c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True,
sharex=False)
plt.legend()
Out[67]:
In [68]:
import matplotlib.image as mpimg
california_img=mpimg.imread('pics/california_pic.png')
ax = df.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4,
s=df["population"]/100, label="population", figsize=(10,7),
c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True,
sharex=False)
plt.imshow(california_img, extent=[-124.55, -113.8, 32.45, 42.05], alpha=0.5)
plt.ylabel("Latitude", fontsize=14)
plt.xlabel("Longitude", fontsize=14)
plt.legend(fontsize=16)
plt.show()
Correlation coefficient: A statistic used to show how the scores from one measure relate to scores on a second measure for the same group of individuals. A high value (approaching +1.00) is a strong direct relationship, a low negative value (approaching -1.00) is a strong inverse relationship, and values near 0.00 indicate little, if any, relationship.
In [69]:
# Coeficiente de correlação padrão (standard correlation coefficient)
corr_matrix = df.corr()
# Signature: df.corr(method='pearson', min_periods=1)
# Docstring: Compute pairwise correlation of columns, excluding NA/null values
In [70]:
corr_matrix["median_house_value"].sort_values(ascending=False)
Out[70]:
Os três atributos mais relevantes para median_house_value são median_income (mediana da renda), total_rooms (total de cômodos) e housing_median_age (mediana da idade das casas)
Outra forma de verificar a correlação, plotando pelo Pandas cada atributo numérico contra todos os outros atributos numéricos.
Para otimizar e evitar gráficos desnecessários, foi escolhido os atributos mais importantes.
In [71]:
from pandas.plotting import scatter_matrix
attributes = ["median_house_value", "median_income", "total_rooms", "housing_median_age"]
scatter_matrix(df[attributes], figsize=(12, 8))
Out[71]:
Por estes gráficos, vemos que o mais promissor para median_house_value é o median_income (gráfico crescente e com algum padrão/tendência). Vendo-os mais próximos:
In [72]:
df.plot(kind="scatter", x="median_income", y="median_house_value",
alpha=0.1)
plt.axis([0, 16, 0, 550000])
Out[72]:
Há poucos pontos que ficam dispersos. E há duas curiosas retas horizontais, na linha dos 500k e por volta dos 350k.
In [74]:
len(df["median_house_value"])
Out[74]:
In [75]:
len(df)
Out[75]:
Criando alguns novos atributos para tentar combinações dos atributos. Será criado 3, a quantidade de cômodos por famílias, total de quartos por total de cômodos e população por famílias:
In [99]:
df["rooms_per_household"] = df["total_rooms"]/df["households"]
df["bedrooms_per_room"] = df["total_bedrooms"]/df["total_rooms"]
df["population_per_household"]= df["population"]/df["households"]
In [100]:
corr_matrix = df.corr()
corr_matrix["median_house_value"].sort_values(ascending=False)
Out[100]:
Vemos que o novo atributo rooms_per_household ficou entre os 3 melhores. Como era de se esperar, as casas maiores são mais caras.
In [101]:
df.plot(kind="scatter", x="rooms_per_household", y="median_house_value",
alpha=0.2)
plt.axis([0, 5, 0, 520000])
plt.show()
In [102]:
df.describe()
Out[102]:
In [103]:
# separando em dados e rótulos, respectivamente:
df = strat_train_set.drop("median_house_value", axis=1) # conjunto de treinamento sem os rótulos
# o drop cria uma cópia dos dados
df_labels = strat_train_set["median_house_value"].copy()
Sobre o axis:
In [104]:
df
Out[104]:
In [105]:
df_labels #median_house_value
Out[105]:
In [106]:
# aqui verificamos que há alguns valores com NaN (not a number), estes 5.
sample_incomplete_rows = df[df.isnull().any(axis=1)].head()
sample_incomplete_rows
Out[106]:
In [107]:
# 1ª Opção - Retirar os NaN (Not a Number)
sample_incomplete_rows.dropna(subset=["total_bedrooms"])
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html
# Return object with labels on given axis omitted where alternately any or all of the data are missing
# 2ª Opção - retirar a coluna inteira
sample_incomplete_rows.drop("total_bedrooms", axis=1)
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html
# axis=0 seria aplicado em cada linha numa mesma coluna (por default, axis=0)
# axis=1 é ao longo da coluna numa mesma linha
# 3ª Opção - completar com os valores médios
median = df["total_bedrooms"].median()
sample_incomplete_rows["total_bedrooms"].fillna(median, inplace=True) # option 3
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html
# Fill NA/NaN values using the specified method
# inplace : boolean, default False
# If True, fill in place. Note: this will modify any other views on this object,
# (e.g. a no-copy slice for a column in a DataFrame).
In [108]:
sample_incomplete_rows
Out[108]:
In [110]:
# http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Imputer.html
# Imputation transformer for completing missing values.
# Remove o atributo textual para os cálculos estatísticos
from sklearn.preprocessing import Imputer
imputer = Imputer(strategy="median")
In [111]:
# copia os dados sem o atributo textual ocean_proximity
housing_num = df.drop("ocean_proximity", axis=1)
In [112]:
# http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Imputer.html#sklearn.preprocessing.Imputer.fit
# __init__(missing_values=’NaN’, strategy=’mean’, axis=0, verbose=0, copy=True)
imputer.fit(housing_num)
Out[112]:
O imputer computou a média de cada atributo e armazenou em statistics_.
In [113]:
# statistics_ : array of shape (n_features,)
# The imputation fill value for each feature if axis == 0.
imputer.statistics_
Out[113]:
In [114]:
# Confirmando aqui:
housing_num.median().values
Out[114]:
In [115]:
# Transformando o conjunto de treinamento substituindo os valores que faltam pelas medianas aprendidas:
X = imputer.transform(housing_num)
In [116]:
# Resulta num array do Numpy que contém as features transformadas. Colocando num DataFrame do Pandas:
housing_tr = pd.DataFrame(X, columns=housing_num.columns, index = (df.index.values))
In [117]:
# listando as linhas com valores incompletos
housing_tr.loc[sample_incomplete_rows.index.values]
Out[117]:
In [118]:
imputer.strategy
Out[118]:
In [119]:
housing_tr = pd.DataFrame(X, columns=housing_num.columns)
housing_tr.head()
Out[119]:
Logo acima deixamos de lado o ocean_proximity por ser um atributo textual, que impossibilitava o cálculo da mediana.
O sk-learn possui um transformador, o LabelEncoder:
In [120]:
# http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html
# Encode labels with value between 0 and n_classes-1.
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()
housing_cat = df["ocean_proximity"]
housing_cat_encoded = encoder.fit_transform(housing_cat)
housing_cat_encoded
Out[120]:
In [121]:
print(encoder.classes_)
Vemos que os mais similares ficaram distantes na numeração, como 0 e 4. Para isso, pode-se criar um atributo binário para cada categoria. Por exemplo, um atributo igual a 1 quando a categoria é <1H OCEAN (e 0 se não for), da mesma forma para os outros atributos.
No sklean tem o OneHotEncoder. Quando o atributo é 1 ("quente"), enquanto os outros serão 0 ("frio").
In [122]:
# http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder()
housing_cat_1hot = encoder.fit_transform(housing_cat_encoded.reshape(-1,1))
housing_cat_1hot
Out[122]:
Na matriz vemos que cada linha possui um 1 e o resto é zero.
In [123]:
housing_cat_1hot.toarray()
Out[123]:
In [124]:
print(housing_cat_1hot) # tuplas com a linha da matriz e a posição do valor 1, respectivamente.
In [125]:
# este aqui em baixo faz o mesmo que o OneHotEncoder de cima.
# http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html
from sklearn.preprocessing import LabelBinarizer
encoder = LabelBinarizer()
housing_cat_1hot = encoder.fit_transform(housing_cat)
housing_cat_1hot
Out[125]:
In [126]:
# Transformador personalizado para adicionar atributos extras
from sklearn.base import BaseEstimator, TransformerMixin
# índice da coluna
rooms_ix, bedrooms_ix, population_ix, household_ix = 3, 4, 5, 6
class CombinedAttributesAdder(BaseEstimator, TransformerMixin):
def __init__(self, add_bedrooms_per_room = True):
self.add_bedrooms_per_room = add_bedrooms_per_room
def fit(self, X, y=None):
return self
def transform(self, X, y=None):
rooms_per_household = X[:, rooms_ix] / X[:, household_ix]
population_per_household = X[:, population_ix] / X[:, household_ix]
if self.add_bedrooms_per_room:
bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix]
return np.c_[X, rooms_per_household, population_per_household,
bedrooms_per_room]
else:
return np.c_[X, rooms_per_household, population_per_household]
attr_adder = CombinedAttributesAdder(add_bedrooms_per_room=False)
housing_extra_attribs = attr_adder.transform(df.values)
In [127]:
df.columns
Out[127]:
In [128]:
list(zip(df.columns))
Out[128]:
In [129]:
housing_extra_attribs = pd.DataFrame(housing_extra_attribs, columns=list(df.columns)+["rooms_per_household", "population_per_household"])
housing_extra_attribs.head()
Out[129]:
In [130]:
# Pipeline para pré-processar os atributos numéricos
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
num_pipeline = Pipeline([
('imputer', Imputer(strategy="median")),
('attribs_adder', CombinedAttributesAdder()),
('std_scaler', StandardScaler()),
])
housing_num_tr = num_pipeline.fit_transform(housing_num)
In [131]:
housing_num_tr
Out[131]:
In [132]:
# Transformador para selecionar um subconjunto das colunas Pandas DataFrame
from sklearn.base import BaseEstimator, TransformerMixin
# Classe para selecionar colunas numéricas ou categóricas
class DataFrameSelector(BaseEstimator, TransformerMixin):
def __init__(self, attribute_names):
self.attribute_names = attribute_names
def fit(self, X, y=None):
return self
def transform(self, X):
return X[self.attribute_names].values
In [133]:
# Juntando todos esses componentes num grande pipeline que irá processar as características numéricas e categóricas
num_attribs = list(housing_num)
cat_attribs = ["ocean_proximity"]
num_pipeline = Pipeline([
('selector', DataFrameSelector(num_attribs)),
('imputer', Imputer(strategy="median")),
('attribs_adder', CombinedAttributesAdder()),
('std_scaler', StandardScaler()),
])
cat_pipeline = Pipeline([
('selector', DataFrameSelector(cat_attribs)),
('label_binarizer', LabelBinarizer()),
])
In [134]:
from sklearn.pipeline import FeatureUnion
full_pipeline = FeatureUnion(transformer_list=[
("num_pipeline", num_pipeline),
("cat_pipeline", cat_pipeline),
])
In [135]:
housing_prepared = full_pipeline.fit_transform(df)
housing_prepared
Out[135]:
In [136]:
housing_prepared.shape
Out[136]:
In [137]:
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(housing_prepared, df_labels) # Fit linear model
# From docummentation:
#lin_reg.fit(X, y, sample_weight=None)
# X : numpy array or sparse matrix of shape [n_samples,n_features]
# Training data
#y : numpy array of shape [n_samples, n_targets]
# Target values
Out[137]:
In [138]:
# tentando o pipeline completo de algumas instâncias de treinamento
some_data = df.iloc[:5]
some_labels = df_labels.iloc[:5]
some_data_prepared = full_pipeline.transform(some_data) # Transform some_data separately by each transformer, concatenate results.
print("Predictions:", lin_reg.predict(some_data_prepared))
Comparando contra os valores atuais:
In [139]:
print("Labels:", list(some_labels))
In [140]:
some_data_prepared
Out[140]:
In [141]:
# http://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html
from sklearn.metrics import mean_squared_error
housing_predictions = lin_reg.predict(housing_prepared)
lin_mse = mean_squared_error(df_labels, housing_predictions)
lin_rmse = np.sqrt(lin_mse)
lin_rmse
Out[141]:
In [142]:
# http://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html
from sklearn.metrics import mean_absolute_error
lin_mae = mean_absolute_error(df_labels, housing_predictions)
lin_mae
Out[142]:
In [143]:
# http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html
from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor(random_state=42)
tree_reg.fit(housing_prepared, df_labels)
Out[143]:
In [144]:
housing_predictions = tree_reg.predict(housing_prepared)
tree_mse = mean_squared_error(df_labels, housing_predictions)
tree_rmse = np.sqrt(tree_mse)
tree_rmse
Out[144]:
Estranho aqui ter dado zero de erro, é mais provável que o modelo tenha se sobreajustado (overfitting) aos dados.
In [145]:
tree_mae = mean_absolute_error(df_labels, housing_predictions)
tree_mae
Out[145]:
Melhorando a avaliação com Validação Cruzada k-fold, que randomicamente divide o conjunto de treinamento em 10 subconjuntos distintos chamados folds, que treina e avalia o modelo de Árvore de Decisão 10 vezes, pegando um fold diferente para avaliação a cada vez e treinando os outros 9 folds.
In [146]:
from sklearn.model_selection import cross_val_score
scores = cross_val_score(tree_reg, housing_prepared, df_labels, scoring="neg_mean_squared_error", cv=10)
tree_rmse_scores = np.sqrt(-scores)
In [147]:
def display_scores(scores):
print("Scores:", scores)
print("Mean:", scores.mean())
print("Standard deviation:", scores.std())
display_scores(tree_rmse_scores)
In [148]:
# Calculando agora as mesmas pontuações para o modelo de Regressão Linear
lin_scores = cross_val_score(lin_reg, housing_prepared, df_labels,
scoring="neg_mean_squared_error", cv=10)
lin_rmse_scores = np.sqrt(-lin_scores)
display_scores(lin_rmse_scores)
In [149]:
from sklearn.ensemble import RandomForestRegressor
forest_reg = RandomForestRegressor(random_state=42)
forest_reg.fit(housing_prepared, df_labels)
Out[149]:
In [150]:
housing_predictions = forest_reg.predict(housing_prepared)
forest_mse = mean_squared_error(df_labels, housing_predictions)
forest_rmse = np.sqrt(forest_mse)
forest_rmse
Out[150]:
In [151]:
from sklearn.model_selection import cross_val_score
forest_scores = cross_val_score(forest_reg, housing_prepared, df_labels,
scoring="neg_mean_squared_error", cv=10)
forest_rmse_scores = np.sqrt(-forest_scores)
display_scores(forest_rmse_scores)
In [152]:
scores = cross_val_score(lin_reg, housing_prepared, df_labels, scoring="neg_mean_squared_error", cv=10)
pd.Series(np.sqrt(-scores)).describe()
Out[152]:
In [ ]: