Anem a generar un conjunt de dades que s'ajusten la funció \(\sin(x)\) amb una lleugera desviació.
importnumpyasnpfromsklearn.model_selectionimporttrain_test_splitdeff(x):returnnp.sin(x/5)np.random.seed(42)n_samples=200X=np.random.uniform(-50,50,n_samples)Y=f(X)+np.random.randn(n_samples)*0.25X=X.reshape(-1,1)# Convertim X en una matriu de 1 columnaX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=42)X_test,Y_test=zip(*sorted(zip(X_test,Y_test)))# Ordenem les dades de test per visualitzar-les correctament
Figura 3. Dades generades a partir de la funció \(\sin(x)\).
Figura 4. Model de regressió mitjançant arbre de decisió.
També podem visualitzar l'arbre de decisió amb la llibreria graphviz.
fromsklearn.treeimportexport_graphvizfromgraphvizimportSource# Export the tree to a DOT formatdot_data=export_graphviz(model,out_file=None,# Leave as None to return the DOT data as a stringfilled=True,# Color the nodes based on their valuesrounded=True,# Round the corners of the boxesspecial_characters=True# Allow for special characters in labels)# Render the DOT data to a graphgraph=Source(dot_data)graph.format="png"graph.render("decision_tree")graph.view()# Open the PNG file
#!/usr/bin/env pythonimportnumpyasnpfromsklearn.model_selectionimporttrain_test_splitdeff(x):returnnp.sin(x/5)np.random.seed(42)n_samples=200X=np.random.uniform(-50,50,n_samples)Y=f(X)+np.random.randn(n_samples)*0.25X=X.reshape(-1,1)# Convertim X en una matriu de 1 columnaX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=42)X_test,Y_test=zip(*sorted(zip(X_test,Y_test)))# Ordenem les dades de test per visualitzar-les correctamentimportmatplotlib.pyplotaspltplt.scatter(X_train,Y_train,color='blue')plt.scatter(X_test,Y_test,color='orange')plt.show()fromsklearn.treeimportDecisionTreeRegressormax_depth=5model=DecisionTreeRegressor(max_depth=max_depth)model.fit(X_train,Y_train)fromsklearn.metricsimportmean_squared_errorfromsklearn.metricsimportr2_scorepred_Y=model.predict(X_test)rmse=mean_squared_error(Y_test,pred_Y)r2=r2_score(Y_test,pred_Y)print(f'RMSE arbre decisió: {rmse:.2f}')print(f'R2 arbre decisió: {r2:.2f}')importmatplotlib.pyplotaspltplt.scatter(X_train,Y_train,color='blue')plt.scatter(X_test,Y_test,color='orange')plt.plot(X_test,pred_Y,color='red',lw=2)plt.show()fromsklearn.treeimportexport_graphvizfromgraphvizimportSource# Export the tree to a DOT formatdot_data=export_graphviz(model,out_file=None,# Leave as None to return the DOT data as a stringfilled=True,# Color the nodes based on their valuesrounded=True,# Round the corners of the boxesspecial_characters=True# Allow for special characters in labels)# Render the DOT data to a graphgraph=Source(dot_data)graph.format="png"graph.render("decision_tree")graph.view()# Open the PNG file