0% encontró este documento útil (1 voto)
2K vistas59 páginas

Weka Tutorials Spanish

Este documento presenta el tutorial introductorio del WEKA Explorer, la principal interfaz gráfica para acceder a las funcionalidades de WEKA. El WEKA Explorer contiene seis paneles para cargar y preprocesar datos, clasificarlos e visualizarlos. El panel Preprocess permite cargar datos y ver información sobre ellos, mientras que el panel Classify invoca métodos de clasificación y el panel Visualize crea diagramas de dispersión de los datos.

Cargado por

Kevin Wong
Derechos de autor
© Attribution Non-Commercial (BY-NC)
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (1 voto)
2K vistas59 páginas

Weka Tutorials Spanish

Este documento presenta el tutorial introductorio del WEKA Explorer, la principal interfaz gráfica para acceder a las funcionalidades de WEKA. El WEKA Explorer contiene seis paneles para cargar y preprocesar datos, clasificarlos e visualizarlos. El panel Preprocess permite cargar datos y ver información sobre ellos, mientras que el panel Classify invoca métodos de clasificación y el panel Visualize crea diagramas de dispersión de los datos.

Cargado por

Kevin Wong
Derechos de autor
© Attribution Non-Commercial (BY-NC)
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd

Practical Data Mining Tutorial 1: Introduction to the WEKA Explorer

Mark Hall, Eibe Frank and Ian H. Witten May 5, 2011


c 2006-2012 University of Waikato

Getting started
Este tutorial presenta la interfaz grca de usuario a principal para acceder a las instalaciones de WEKA, llamado Explorer WEKA. Vamos a trabajar con WEKA 3.6 (aunque casi todo es lo mismo con otras versiones), y suponemos que se ha instalado en su sistema. Invocar WEKA desde el men INICIO de Winu dows (en Linux o Mac, haga doble clic en [Link] o [Link]). Esto pone en marcha el GUI Chooser WEKA. Haga clic en el Explorer botn o para entrar en el WEKA Explorer. Slo en caso de que usted se est preguntando o a sobre el resto de botones en la GUI Chooser: Experimenter es una interfaz de usuario para comparar el rendimiento predictivo de algoritmos de aprendizaje; KnowledgeFlow es una interfaz basada en componentes que tiene una funcionalidad similar a la de Explorer; y Simple CLI se abre un comando-l nea de interfaz que emula una terminal y le permite interactuar con WEKA de esta manera.

This tutorial introduces the main graphical user interface for accessing WEKAs facilities, called the WEKA Explorer. We will work with WEKA 3.6 (although almost everything is the same with other versions), and we assume that it is installed on your system. Invoke WEKA from the Windows START menu (on Linux or the Mac, double-click [Link] or [Link]). This starts up the WEKA GUI Chooser. Click the Explorer button to enter the WEKA Explorer. Just in case you are wondering about the other buttons in the GUI Chooser: Experimenter is a user interface for comparing the predictive performance of learning algorithms; KnowledgeFlow is a component-based interface that has a similar functionality as the Explorer; and Simple CLI opens a command-line interface that emulates a terminal and lets you interact with WEKA in this fashion.

The panels in the Explorer


La interfaz de usuario de la Explorer se compone de seis paneles, invocadas por las etiquetas en la parte superior de la ventana. El panel de Preprocess es la que est abierta cuando la Explorer por a primera vez. Este tutorial le introducir a otros a dos, as Classify y Visualize. (Los otros tres : paneles se explican en tutoriales ms tarde.) He a aqu una breve descripcin de las funciones que es o tos tres grupos de realizar. Preprocess es donde puedes cargar los datos y preproceso. Una vez que un conjunto de datos se ha cargado, el panel muestra infor` macin sobre Al. El conjunto de datos puede o ser modicado, ya sea mediante la edicin o de forma manual o mediante la aplicacin de o un ltro, y la versin modicada se puede o guardar. Como alternativa a la carga de un conjunto de datos pre-existentes, una articial se pueden crear mediante el uso de un generador. Tambin es posible cargar datos e desde una URL o desde una base de datos.

The user interface to the Explorer consists of six panels, invoked by the tabs at the top of the window. The Preprocess panel is the one that is open when the Explorer is rst started. This tutorial will introduce you to two others as well: Classify and Visualize. (The remaining three panels are explained in later tutorials.) Heres a brief description of the functions that these three panels perform. Preprocess is where you to load and preprocess data. Once a dataset has been loaded, the panel displays information about it. The dataset can be modied, either by editing it manually or by applying a lter, and the modied version can be saved. As an alternative to loading a pre-existing dataset, an articial one can be created by using a generator. It is also possible to load data from a URL or from a database.

Classify is where you invoke the classication methods in WEKA. Several options for the classication process can be set, and the result of the classication can be viewed. The training dataset used for classication is the one loaded (or generated) in the Preprocess panel.

Classify es donde se invoca a los mtodos de clasie cacin en WEKA. Varias opciones para el o proceso de clasicacin se puede establecer, o y el resultado de la clasicacin se puede ver. o El conjunto de datos de entrenamiento utilizados para la clasicacin es la carga (o geno erada) en el panel de Preprocess.

Visualize is where you can visualize the dataset loaded in the Preprocess panel as twodimensional scatter plots. You can select the attributes for the x and y axes.

Visualize es donde se puede visualizar el conjunto de datos cargados en el panel de Preprocess como diagramas de dispersin de dos dimeno siones. Puede seleccionar los atributos de los x y y ejes.

The Preprocess panel


Preprocess es el panel que se abre cuando el Explorer WEKA se ha iniciado.

Preprocess is the panel that opens when the WEKA Explorer is started.

3.1

Loading a dataset
Antes de cambiar a cualquier otro panel, el Explorer debe tener un conjunto de datos para trabajar. Para cargar una, haga clic en el botn de o Open le... en la esquina superior izquierda del panel. Mire a su alrededor para la carpeta que contiene los conjuntos de datos y busque un archivo llamado [Link] (este archivo est a en el carpeta de data que se suministra cuando WEKA se instala). Este contiene la versin nomio nal de la norma tiempo conjunto de datos. Abrir archivo. Ahora la pantalla se ver como la Figa ure 1.

Before changing to any other panel, the Explorer must have a dataset to work with. To load one up, click the Open le... button in the top left corner of the panel. Look around for the folder containing datasets, and locate a le named [Link] (this le is in the data folder that is supplied when WEKA is installed). This contains the nominal version of the standard weather dataset. Open this le. Now your screen will look like Figure 1.

The weather data is a small dataset with only 14 examples for learning. Because each row is an independent example, the rows/examples are called instances. The instances of the weather dataset have 5 attributes, with names outlook, temperature, humidity, windy and play. If you click on the name of an attribute in the left sub-panel, information about the selected attribute will be shown on the right. You can see the values of the attribute and how many times an instance in the dataset has a particular value. This information is also shown in the form of a histogram.

Los datos de clima es un conjunto de datos pequeo con slo 14 ejemplos para el aprendizaje. n o Debido a que cada la es un ejemplo independiente, las las/ejemplos son llamados casos. Los casos del conjunto de datos meteorolgicos tienen o 5 atributos, con perspectivas nombres , la temperatura, humedad, jugar con mucho viento y. Si hace clic en el nombre de un atributo en el sub-panel de la izquierda, la informacin acerca o del atributo seleccionado se muestra a la derecha. Usted puede ver los valores de los atributos y las veces que una instancia del conjunto de datos tiene un valor particular. Esta informacin se muestra o tambin en la forma de un histograma. e

Figure 1: The Explorers Preprocess panel. All attributes in this dataset are nominal, i.e. they have a predened nite set of values. Each instance describes a weather forecast for a particular day and whether to play a certain game on that day. It is not really clear what the game is, but let us assume that it is golf. The last attribute play is the class attributeit classies the instance. Its value can be yes or no. Yes means that the weather conditions are OK for playing golf, and no means they are not OK. Todos los atributos de este conjunto de datos son nominales, es decir, tienen un conjunto nito de valores predenidos. Cada instancia se describe un pronstico del tiempo para un d en particular o a y si a jugar un cierto juego en ese d No est a. a muy claro lo que el juego es, pero supongamos que es el golf. Jugar el ultimo atributo es el atrib uto classque clasica la instancia. Su valor puede ser si o no. S signica que las condi ciones climticas estn bien para jugar al golf, y a a no signica que no estn bien. a

3.2

Exercises
Para familiarizarse con las funciones discutido hasta ahora, por favor, los dos ejercicios siguientes. Las soluciones a estos y otros ejercicios de este tutorial se dan al nal. Ex. 1: Cules son los valores que la temperatura a el atributo puede tener?

To familiarize yourself with the functions discussed so far, please do the following two exercises. The solutions to these and other exercises in this tutorial are given at the end. Ex. 1: What are the values that the attribute temperature can have?

Ex. 2: Load a new dataset. Press the Open le button and select the le [Link]. How many instances does this dataset have? How many attributes? What is the range of possible values of the attribute petallength ?

Ex. 2: Carga un nuevo conjunto de datos. Pulse el botn Abrir el archivo y seleccione el o archivo [Link]. Cuntos casos se han a esta base de datos? Cmo muchos atribuo tos? Cul es el rango de valores posibles de a petallength el atributo?

3.3

The dataset editor


Es posible ver y editar un conjunto de datos desde el interior de WEKA. Para experimentar con esto, cargar el archivo [Link] nuevo. Haga clic en el botn de Edit... de la la de o botones en la parte superior del panel de Preprocess. Esto abre una nueva ventana llamada Viewer, que enumera todas las instancias de los datos meteorolgicos (vase la Figure 2). o e

It is possible to view and edit an entire dataset from within WEKA. To experiment with this, load the le [Link] again. Click the Edit... button from the row of buttons at the top of the Preprocess panel. This opens a new window called Viewer, which lists all instances of the weather data (see Figure 2).

3.3.1

Exercises

Ex. 3: What is the function of the rst column in the Viewer?

Ex. 3: Cul es la funcin de la primera columna a o de la Viewer?

Ex. 4: Considering the weather data, what is the class value of instance number 8?

Ex. 4: Teniendo en cuenta los datos meteorolgicos, cul es el valor de la clase de o a nmero de instancia 8? u

Ex. 5: Load the iris data and open it in the editor. How many numeric and how many nominal attributes does this dataset have?

Ex. 5: Carga los datos de iris y abrirlo en el editor. Cmo los atributos nominales muchas o numrico y el nmero de este conjunto de e u datos se tienen?

3.4

Applying a lter
En WEKA, ltros son mtodos que se pueden e utilizar para modicar bases de datos de manera sistemticaes decir, son datos del proceso prea vio herramientas. WEKA tiene varios ltros para diferentes tareas. Actualizar el [Link] conjunto de datos, y vamos a eliminar un atributo de ella. El ltro adecuado se llama Remove, su nombre completo es:

In WEKA, lters are methods that can be used to modify datasets in a systematic fashionthat is, they are data preprocessing tools. WEKA has several lters for dierent tasks. Reload the [Link] dataset, and lets remove an attribute from it. The appropriate lter is called Remove; its full name is:

[Link]

Figure 2: The data viewer. Examine this name carefully. Filters are organized into a hierarchical structure whose root is weka. Those in the unsupervised category dont require a class attribute to be set; those in the supervised category do. Filters are further divided into ones that operate primarily on attributes/columns (the attribute category) and ones that operate primarily on instances/rows (the instance category). Examine cuidadosamente este nombre. Los ltros estn organizados en una estructura jerrquica, a a cuya ra es weka. Los que estn en la categor de z a a unsupervised no requieren un atributo de clase que se establece, los de la categor supervised a hacer. Los ltros se dividen en los que operan principalmente en los atributos/columnas (la categor a attribute) y los que operan principalmente en casos/las (la categor instance). a Si hace clic en el botn Choose en el panel de o Preprocess, se abre un editor jerrquico en el que a se selecciona un ltro, siguiendo la ruta de acceso correspondiente a su nombre completo. Utilice la ruta dada en por encima del nombre completo para seleccionar el ltro de Remove. Una vez que se selecciona, el texto Eliminar aparecer en el campo a situado junto al botn de Choose. o

If you click the Choose button in the Preprocess panel, a hierarchical editor opens in which you select a lter by following the path corresponding to its full name. Use the path given in the full name above to select the Remove lter. Once it is selected, the text Remove will appear in the eld next to the Choose button.

Click on the eld containing this text. A window opens called the GenericObjectEditor, which is used throughout WEKA to set parameter values for all of the tools. It contains a short explanation of the Remove lterclick More to get a fuller description. Underneath there are two elds in which the options of the lter can be set. The rst option is a list of attribute numbers. The second optionInvertSelectionis a switch. If it is false, the specied attributes are removed; if it is true, these attributes are NOT removed.

Haga clic en el campo que contiene este texto. Se abre una ventana denominada GenericObjectEditor, que se utiliza en todo WEKA para establecer valores de los parmetros de todas las hera ramientas. Contiene una breve explicacin del lo tro de Removehaga clic More para obtener una descripcin ms completa. Debajo hay dos campos o a en los que las opciones del ltro se puede establecer. La primera opcin es una lista de nmeros de o u atributo. La segunda opcinInvertSelection o es un interruptor. Si se trata de falsos, los atributos especicados se quitan, si es verdadero, estos atributos no se quitan. Ingrese 3 en el campo attributeIndices y haga clic en el botn de OK. La ventana con las opo ciones de ltro se cierra. Ahora haga clic en el botn de Apply a la derecha, es decir, los datos a o travs del ltro. El ltro elimina el atributo con el e ndice 3 del conjunto de datos, y se puede ver que el conjunto de atributos se ha reducido. Este cambio no afecta al conjunto de datos en el archivo, slo se o aplica a los datos recogidos en la memoria. El conjunto de datos modicado se puede guardar en un archivo ARFF nuevo pulsando el botn de Save... o y entrar en un nombre de archivo. La accin del lo tro se puede deshacer pulsando el botn de Undo. o Una vez ms, esto se aplica a la versin de los datos a o contenidos en la memoria. Lo que hemos descrito se muestra cmo los ltros o en WEKA se aplican a los datos. Sin embargo, en el caso particular de Remove, hay una manera ms sencilla de lograr el mismo efecto. En lua gar de invocar el Remove ltro, los atributos se pueden seleccionar con los cuadros pequeos en la n Attributes sub-panel y eliminar con el botn de o Remove que aparece en la parte inferior, debajo de la lista de atributos.

Enter 3 into the attributeIndices eld and click the OK button. The window with the lter options closes. Now click the Apply button on the right, which runs the data through the lter. The lter removes the attribute with index 3 from the dataset, and you can see that the set of attributes has been reduced. This change does not aect the dataset in the le; it only applies to the data held in memory. The changed dataset can be saved to a new ARFF le by pressing the Save... button and entering a le name. The action of the lter can be undone by pressing the Undo button. Again, this applies to the version of the data held in memory.

What we have described illustrates how lters in WEKA are applied to data. However, in the particular case of Remove, there is a simpler way of achieving the same eect. Instead of invoking the Remove lter, attributes can be selected using the small boxes in the Attributes sub-panel and removed using the Remove button that appears at the bottom, below the list of attributes.

3.4.1

Exercises

Ex. 6: Ensure that the [Link] Ex. dataset is loaded. Use the lter [Link] to remove all instances in which the humidity attribute has the value high. To do this, rst make the eld next to the Choose button show the text RemoveWithValues. Then click on it to get the GenericObjectEditor window and gure out how to change the lter settings appropriately.

6: Asegrese de que el [Link] u conjunto de datos se carga. Utilice el ltro [Link] para eliminar todos los casos en los que el atributo humedad tiene el valor alto. Para ello, en primer lugar que el campo situado junto al botn de Choose mostrar el o a texto RemoveWithValues, a continuacin, o haga clic en ella para mostrar la ventana de GenericObjectEditor y encontrar la manera de cambiar la conguracin del ltro o adecuadamente.

Ex. 7: Undo the change to the dataset that you just performed, and verify that the data is back in its original state.

Ex. 7: Deshacer el cambio en el conjunto de datos que acaba de realizar, y vericar que los datos vuelve a su estado original.

The Visualize panel


Ahora eche un vistazo a las instalaciones de WEKA de visualizacin de datos. Estos funcioo nan mejor con datos numricos, por lo que utilizar e los datos del iris. En primer lugar, la carga [Link]. Estos datos contienen mediciones de ores. Cada caso se clasica como uno de tres tipos: setosa iris, iris versicolor y virginica iris. El conjunto de datos cuenta con 50 ejemplos de cada tipo: 150 casos en total. Haga clic en la cha Visualize para que aparezca el panel de visualizacin. Muestra una cuadr o cula que contiene 25 grcos de dispersin de dos dia o mensiones, con todas las combinaciones posibles de los cinco atributos de los datos del iris en los x y y ejes. Al hacer clic en la primera parcela en la segunda la se abre una ventana que muestra una trama ampliada con los ejes seleccionados. Las instancias se muestran como pequeas cruces cuyo n color depende de la clase de cruz de la instancia. El eje x muestra el atributo sepallength, y petalwidth muestra el y eje. Al hacer clic en una de las cruces se abre una ventana de Instance Info, que enumera los valores de todos los atributos de la instancia seleccionada. Cierre la ventana de Instance Info de nuevo. Los campos de seleccin en la parte superior de o la ventana que contiene el diagrama de dispersin o se puede utilizar para cambiar los atributos utilizados por los x y y ejes. Pruebe a cambiar el eje x a petalwidth y el y eje petallength. El campo muestra Color: clase (Num)se puede utilizar para cambiar el cdigo de colores. o Cada una de las parcelas de colores poco como la barra a la derecha de la ventana del grco de a dispersin representa un unico atributo. Haciendo o clic en un bar que utiliza atributos para los x eje del diagrama de dispersin. Derecho clic en un bar o hace lo mismo con los y eje. Trate de cambiar los x y y ejes de nuevo a sepallength y petalwidth utilizando estas barras.

We now take a look at WEKAs data visualization facilities. These work best with numeric data, so we use the iris data.

First, load [Link]. This data contains ower measurements. Each instance is classied as one of three types: iris-setosa, iris-versicolor and irisvirginica. The dataset has 50 examples of each type: 150 instances in all. Click the Visualize tab to bring up the visualization panel. It shows a grid containing 25 twodimensional scatter plots, with every possible combination of the ve attributes of the iris data on the x and y axes. Clicking the rst plot in the second row opens up a window showing an enlarged plot using the selected axes. Instances are shown as little crosses whose color cross depends on the instances class. The x axis shows the sepallength attribute, and the y axis shows petalwidth.

Clicking on one of the crosses opens up an Instance Info window, which lists the values of all attributes for the selected instance. Close the Instance Info window again. The selection elds at the top of the window that contains the scatter plot can be used to change the attributes used for the x and y axes. Try changing the x axis to petalwidth and the y axis to petallength. The eld showing Colour: class (Num) can be used to change the colour coding.

Each of the colorful little bar-like plots to the right of the scatter plot window represents a single attribute. Clicking a bar uses that attribute for the x axis of the scatter plot. Right-clicking a bar does the same for the y axis. Try to change the x and y axes back to sepallength and petalwidth using these bars.

The Jitter slider displaces the cross for each instance randomly from its true position, and can reveal situations where instances lie on top of one another. Experiment a little by moving the slider.

El control deslizante Jitter desplaza la cruz por cada instancia al azar de su verdadera posicin, y o puede revelar las situaciones en que casos se encuentran en la parte superior de uno al otro. Experimente un poco moviendo la barra deslizante. El botn de Select Instance y Reset, Clear, y o Save los botones le permiten cambiar el conjunto de datos. Algunos casos se pueden seleccionar y eliminar los dems. Pruebe la opcin Rectangle: a o seleccionar un rea por la izquierda haciendo clic a y arrastrando el ratn. El Reset botn ahora se o o transforma en un botn de Submit. Haga clic en o l, y todos los casos fuera del rectngulo se elime a inan. Usted podr utilizar Save para guardar el a conjunto de datos modicados en un archivo, mientras que Reset restaura el conjunto de datos original.

The Select Instance button and the Reset, Clear and Save buttons let you change the dataset. Certain instances can be selected and the others removed. Try the Rectangle option: select an area by left-clicking and dragging the mouse. The Reset button now changes into a Submit button. Click it, and all instances outside the rectangle are deleted. You could use Save to save the modied dataset to a le, while Reset restores the original dataset.

The Classify panel


Ahora usted sabe cmo cargar un conjunto de o datos de un archivo y visualizarlo como parcelas de dos dimensiones. En esta seccin se aplica o un algoritmo de clasicacindenominado clasio cador en WEKAa los datos. El clasicador se basa (aprende) un modelo de clasicacin de los o datos. En WEKA, todos los esquemas para predecir el valor de un atributo unico, basado en los valores de algunos atributos de otros se llaman clasicadores, incluso si se utilizan para predecir un objetivo numricomientras que otras pere sonas a menudo describen situaciones tales como numrica prediccin o regresin. La razn es e o o o que, en el contexto de aprendizaje de mquina, a la prediccin numrica histricamente ha sido llao e o mada la clasicacin con clases continuas. o Antes de empezar, carga la informacin del o tiempo nuevo. Ir al panel de Preprocess, haga clic en el botn de Open le, y seleco cione [Link] desde el directorio de datos. Luego cambiar a la mesa de clasicacin, o haga clic en la cha Classify en la parte superior de la ventana. El resultado se muestra en la Figura 3.

Now you know how to load a dataset from a le and visualize it as two-dimensional plots. In this section we apply a classication algorithmcalled a classier in WEKAto the data. The classier builds (learns) a classication model from the data.

In WEKA, all schemes for predicting the value of a single attribute based on the values of some other attributes are called classiers, even if they are used to predict a numeric targetwhereas other people often describe such situations as numeric prediction or regression. The reason is that, in the context of machine learning, numeric prediction has historically been called classication with continuous classes.

Before getting started, load the weather data again. Go to the Preprocess panel, click the Open le button, and select [Link] from the data directory. Then switch to the classication panel by clicking the Classify tab at the top of the window. The result is shown in Figure 3.

Figure 3: The Classify panel.

5.1

Using the C4.5 classier


Una mquina popular mtodo de aprendizaje para a e la miner de datos se denomina el algoritmo C4.5, a y construye rboles de decisin. En WEKA, se a o implementa en un clasicador llamado J48. Seleccione el clasicador J48 haciendo clic en el botn o de Choose en la parte superior de la cha Classier. Una ventana de dilogo aparece mostrando a los diferentes tipos de clasicadores. Haga clic en la entrada trees a revelar sus subentradas, y haga clic en J48 elegir el clasicador J48. Tenga en cuenta que los clasicadores, como los ltros, estn a organizados en una jerarqu J48 tiene el nombre a: completo [Link].J48.

A popular machine learning method for data mining is called the C4.5 algorithm, and builds decision trees. In WEKA, it is implemented in a classier called J48. Choose the J48 classier by clicking the Choose button near the top of the Classier tab. A dialogue window appears showing various types of classier. Click the trees entry to reveal its subentries, and click J48 to choose the J48 classier. Note that classiers, like lters, are organized in a hierarchy: J48 has the full name [Link].J48.

The classier is shown in the text box next to the Choose button: it now reads J48 C 0.25 M 2. The text after J48 gives the default parameter settings for this classier. We can ignore these, because they rarely require changing to obtain good performance from C4.5.

El clasicador se muestra en el cuadro de texto junto al botn Choose: J48 C 0.25 M 2 se o sustituir por el texto. El texto despus de J48 a e da la conguracin de los parmetros por defecto o a para este clasicador. Podemos ignorar esto, ya que rara vez se requieren cambios para obtener un buen rendimiento de C4.5.

Decision trees are a special type of classication model. Ideally, models should be able to predict the class values of new, previously unseen instances with high accuracy. In classication tasks, accuracy is often measured as the percentage of correctly classied instances. Once a model has been learned, we should test it to see how accurate it is when classifying instances.

Los rboles de decisin son un tipo especial de a o modelo de clasicacin. Idealmente, los modelos o deben ser capaces de predecir los valores de la clase de nuevo, no visto previamente casos con gran precisin. En las tareas de clasicacin, la precisin o o o se mide como el porcentaje de casos clasicados correctamente. Una vez que un modelo que se ha aprendido, hay que probarlo para ver cmo es exo acto es la hora de clasicar los casos. Una opcin en WEKA es evaluar el rendimiento o en el conjunto de entrenamientolos datos que se utiliz para construir el clasicador. Esto no o es generalmente una buena idea porque conduce a las estimaciones de rendimiento irrealmente optimista. Usted puede obtener el 100% de precisin o en los datos de entrenamiento por el aprendizaje de memoria sencillo, pero esto no nos dice nada sobre el rendimiento de los nuevos datos que se pueden encontrar cuando el modelo se aplica en la prctica. No obstante, a t a tulo ilustrativo es instructivo considerar el rendimiento de los datos de entrenamiento. En WEKA, los datos que se carga mediante el panel de Preprocess es el datos de entrenamiento. Para evaluar el conjunto de entrenamiento, elegir Use training set desde el panel de Test options en el panel Classify. Una vez que la estrategia de prueba se ha establecido, el clasicador se construye y se evalu con el botn o o Start. Este proceso conjunto de entrenamiento utilizando el algoritmo seleccionado aprendizaje, C4.5 en este caso. Luego se clasica a todas las instancias en los datos de entrenamientoporque esta es la opcin de evaluacin que se ha elegido o o y estad sticas de resultados de desempeo. Estos n se muestran en la Figure 4.

One option in WEKA is to evaluate performance on the training setthe data that was used to build the classier. This is NOT generally a good idea because it leads to unrealistically optimistic performance estimates. You can easily get 100% accuracy on the training data by simple rote learning, but this tells us nothing about performance on new data that might be encountered when the model is applied in practice. Nevertheless, for illustrative purposes it is instructive to consider performance on the training data.

In WEKA, the data that is loaded using the Preprocess panel is the training data. To evaluate on the training set, choose Use training set from the Test options panel in the Classify panel. Once the test strategy has been set, the classier is built and evaluated by pressing the Start button. This processes the training set using the currently selected learning algorithm, C4.5 in this case. Then it classies all the instances in the training databecause this is the evaluation option that has been chosenand outputs performance statistics. These are shown in Figure 4.

5.2

Interpreting the output


El resultado de la formacin y la prueba aparece o en el cuadro de Classier output a la derecha. Puede desplazarse por el texto para examinarla. En primer lugar, busque en la parte que describe el rbol de decisin que se ha generado: a o

The outcome of training and testing appears in the Classier output box on the right. You can scroll through the text to examine it. First, look at the part that describes the decision tree that was generated: J48 pruned tree -----------------outlook = sunny | humidity = high: no (3.0) | humidity = normal: yes (2.0) outlook = overcast: yes (4.0) outlook = rainy | windy = TRUE: no (2.0) | windy = FALSE: yes (3.0) 10

Figure 4: Output after building and testing the classier.

Number of Leaves Size of the tree :

: 8

This represents the decision tree that was built, including the number of instances that fall under each leaf. The textual representation is clumsy to interpret, but WEKA can generate an equivalent graphical representation. You may have noticed that each time the Start button is pressed and a new classier is built and evaluated, a new entry appears in the Result List panel in the lower left corner of Figure 4. To see the tree, right-click on the trees.J48 entry that has just been added to the result list, and choose Visualize tree. A window pops up that shows the decision tree in the form illustrated in Figure 5. Right-click a blank spot in this window to bring up a new menu enabling you to auto-scale the view, or force the tree to t into view. You can pan around by dragging the mouse.

Esto representa el rbol de decisin que fue cona o struido, incluyendo el nmero de casos que correu sponden a cada hoja. La representacin textual es o torpe de interpretar, pero WEKA puede generar una representacin grca equivalente. Puede o a haber notado que cada vez que el botn se pulsa o Start y un clasicador de nueva construccin y se o evalu, una nueva entrada aparece en el panel de o Result List en la esquina inferior izquierda de la Figure 4. Para ver el rbol, haga clic en la entrada a trees.J48 que acaba de ser aadido a la lista de ren sultados, y elija Visualize tree. Aparece una ventana que muestra el rbol de decisin en la forma a o ilustrada en la Figure 5. Haga clic en un punto en blanco en esta ventana para que aparezca un nuevo men que le permite auto-escala de la vista, o la u fuerza del rbol para ajustarse a la vista. Puede a desplazarse por arrastrando el ratn. o

11

Figure 5: The decision tree that has been built. This tree is used to classify test instances. The rst condition is the one in the so-called root node at the top. In this case, the outlook attribute is tested at the root node and, depending on the outcome, testing continues down one of the three branches. If the value is overcast, testing ends and the predicted class is yes. The rectangular nodes are called leaf nodes, and give the class that is to be predicted. Returning to the root node, if the outlook attribute has value sunny, the humidity attribute is tested, and if outlook has value rainy, the windy attribute is tested. No paths through this particular tree have more than two tests. Now let us consider the remainder of the information in the Classier output area. The next two parts of the output report on the quality of the classication model based on the testing option we have chosen. The following states how many and what proportion of test instances have been correctly classied: Este rbol se utiliza para clasicar los casos de a prueba. La primera condicin es la de la llamada o ra del nodo en la parte superior. En este caso, z el atributo perspectivas se prueba en el nodo ra z y, dependiendo del resultado, la prueba contina u por una de las tres ramas. Si el valor es cubierto, naliza las pruebas y la clase predicha es s Los . nodos rectangulares se denominan hojas nodos, y dar la clase que se predijo. Volviendo al nodo ra si el atributo perspectivas tiene un valor z, sol, el atributo humedad se prueba, y si perspectivas tiene un valor de lluvias, el atributo viento se prueba. No hay caminos a travs de e este rbol en particular tiene ms de dos pruebas. a a Consideremos ahora el resto de la informacin en o el rea de Classier output. Las dos siguientes a partes del informe de salida en la calidad del modelo de clasicacin basado en la opcin de prueba o o que hemos elegido. Los siguientes estados cuntos y qu proporcin de a e o casos de prueba han sido correctamente clasicados: 100%

Correctly Classified Instances

14

12

This is the accuracy of the model on the data used for testing. It is completely accurate (100%), which is often the case when the training set is used for testing. There are some other performance measures in the text output area, which we wont discuss here. At the bottom of the output is the confusion matrix: === Confusion Matrix === a b <-- classified as 9 0 | a = yes 0 5 | b = no Each element in the matrix is a count of instances. Rows represent the true classes, and columns represent the predicted classes. As you can see, all 9 yes instances have been predicted as yes, and all 5 no instances as no.

Esta es la precisin del modelo sobre los datos o utilizados para la prueba. Es totalmente preciso (100%), que es a menudo el caso cuando el conjunto de entrenamiento se utiliza para la prueba. Hay algunas medidas de desempeo en la zona de n salida de texto, que no vamos a discutir aqu . En la parte inferior de la salida es la matriz de confusin: o

Cada elemento de la matriz es un recuento de los casos. Las las representan las clases de verdad, y las columnas representan las clases previsto. Como puede ver, todos los 9 s casos se han previsto como s y los 5 no casos como no. ,

5.2.1

Exercise

Ex 8: How would the following instance be classied using the decision tree? outlook = sunny, temperature = cool, humidity = high, windy = TRUE

Ex. 8: Cmo ser la siguiente instancia se clasio a carn con el rbol de decisin? a a o perspectivas = soleado, temperatura = fria, humedad = viento, alta = TRUE

5.3

Setting the testing method


Cuando el botn se pulsa Start, el algoritmo de o aprendizaje seleccionadas se inicia y el conjunto de datos que se carg en el panel de Preprocess o se utiliza para entrenar a un modelo. Un modelo construido a partir del conjunto de entrenamiento completo se imprime en el rea de Classier outa put: esto puede implicar que ejecuta el algoritmo de aprendizaje por ultima vez. El resto de la produccin en el rea de Classier o a output depende del protocolo de prueba que fue elegido con Test options. El cuadro de Test options da varias posibilidades para la evaluacin de o los clasicadores:

When the Start button is pressed, the selected learning algorithm is started and the dataset that was loaded in the Preprocess panel is used to train a model. A model built from the full training set is then printed into the Classier output area: this may involve running the learning algorithm one nal time.

The remainder of the output in the Classier output area depends on the test protocol that was chosen using Test options. The Test options box gives several possibilities for evaluating classiers:

13

Use training set Uses the same dataset that was used for training (the one that was loaded in the Preprocess panel). This is the option we used above. It is generally NOT recommended because it gives over-optimistic performance estimates.

Usar el conjunto de la formacion Utiliza el mismo conjunto de datos que se utiliz para o la formacin (la que se carg en el panel o o de Preprocess). Esta es la opcin que o usamos anteriormente. Por lo general, no se recomienda porque da estimaciones de rendimiento demasiado optimistas.

Supplied test set Lets you select a le containing a separate dataset that is used exclusively for testing.

prueba suministrados conjunto Permite seleccionar un archivo que contiene un conjunto de datos independiente que se utiliza exclusivamente para la prueba.

Cross-validation This is the default option, and the most commonly-used one. It rst splits the training set into disjoint subsets called folds. The number of subsets can be entered in the Folds eld. Ten is the default, and in general gives better estimates than other choices. Once the data has been split into folds of (approximately) equal size, all but one of the folds are used for training and the remaining, left-out, one is used for testing. This involves building a new model from scratch from the corresponding subset of data and evaluating it on the letout fold. Once this has been done for the rst test fold, a new fold is selected for testing and the remaining folds used for training. This is repeated until all folds have been used for testing. In this way each instance in the full dataset is used for testing exactly once, and an instance is only used for testing when it is not used for training. WEKAs cross-validation is a stratied cross-validation, which means that the class proportions are preserved when dividing the data into folds: each class is represented by roughly the same number of instances in each fold. This gives slightly improved performance estimates compared to unstratied cross-validation.

La validacion cruzada Esta es la opcin por deo fecto, y el ms comnmente utilizado. En a u primer lugar, se divide el conjunto de entrenamiento en subconjuntos disjuntos llamados pliegues. El nmero de subconjunu tos se pueden introducir en el campo Folds. Diez es el valor predeterminado, y en general proporciona mejores estimaciones que otras opciones. Una vez que los datos se ha dividido en los pliegues de (aproximadamente) igual tamao, todos menos uno de n los pliegues se utilizan para la formacin y el o restante a cabo, a la izquierda-, uno se utiliza para la prueba. Esto implica la construccin o de un nuevo modelo a partir de cero desde el subconjunto de datos correspondientes y la evaluacin que sobre la que-a veces. Una vez o que esto se ha hecho para la primera prueba doble, una nueva tapa est seleccionado para a las pruebas y los pliegues restante utilizado para el entrenamiento. Esto se repite hasta que todos los pliegues se han utilizado para la prueba. De esta manera, cada instancia del conjunto de datos completo se utiliza para probar una sola vez, y una instancia slo se utiliza para la prueba cuando no se o utiliza para el entrenamiento. WEKA cruz de la validacin es una stratied crosso validation, lo que signica que las proporciones de clase se conservan al dividir los datos en los pliegues: cada clase est repa resentada por aproximadamente el mismo nmero de casos en cada pliegue. Esto u proporciona un rendimiento mejorado ligeramente en comparacin con las estimaciones o sin estraticar la validacin cruzada. o

14

Percentage split Shues the data randomly and then splits it into a training and a test set according to the proportion specied. In practice, this is a good alternative to crossvalidation if the size of the dataset makes cross-validation too slow.

Shues Porcentaje dividir los datos al azar y luego se divide en un entrenamiento y un conjunto de pruebas de acuerdo a la proporcin especicada. En la prctica, esta es o a una buena alternativa a la validacin cruzada o si el tamao del conjunto de datos hace que n la validacin cruzada demasiado lento. o Los dos primeros mtodos de prueba, la evaluacin e o en el conjunto de entrenamiento y el uso de una unidad de prueba suministrada, implicar la cona struccin de un modelo de una sola vez. La valo idacin cruzada consiste en la construccin de un o o modelo de N + 1 veces, donde N es el nmero u elegido de los pliegues. Los primeros N veces, una fraccin (N 1)/N (90% de diez veces la valio dacin cruzada) de los datos se utiliza para el eno trenamiento y el tiempo nal del conjunto de datos completo se utiliza. El mtodo de dividir el pore centaje implica la construccin del modelo en dos o ocasiones, una vez en el conjunto de datos reducidos y de nuevo en el conjunto de datos completo.

The rst two testing methods, evaluation on the training set and using a supplied test set, involve building a model only once. Cross-validation involves building a model N +1 times, where N is the chosen number of folds. The rst N times, a fraction (N 1)/N (90% for ten-fold cross-validation) of the data is used for training, and the nal time the full dataset is used. The percentage split method involves building the model twice, once on the reduced dataset and again on the full dataset.

5.3.1

Exercise

Ex 9: Load the iris data using the Preprocess panel. Evaluate C4.5 on this data using (a) the training set and (b) cross-validation. What is the estimated percentage of correct classications for (a) and (b)? Which estimate is more realistic?

Ex. 9 carga los datos del iris mediante el panel de Preprocess. Evaluar C4.5 en estos datos utilizando (a) el conjunto de entrenamiento y (b) la validacin cruzada. Cul es el poro a centaje estimado de clasicaciones correctas para (a) y (b)? Que estiman es ms realista? a

5.4

Visualizing classication errors


Panel de WEKA de Classify proporciona una manera de visualizar los errores de clasicacin. o Para ello, haga clic en la entrada trees.J48 en la lista de resultados y elegir Visualize classier errors. Una ventana grca de dispersin a o aparece. Casos que han sido clasicados correctamente marcadas por pequeas cruces, mientras n que los que han sido clasicados incorrectamente estn marcados por pequeos cuadrados. a n

WEKAs Classify panel provides a way of visualizing classication errors. To do this, right-click the trees.J48 entry in the result list and choose Visualize classier errors. A scatter plot window pops up. Instances that have been classied correctly are marked by little crosses; whereas ones that have been classied incorrectly are marked by little squares.

5.4.1

Exercise

15

Ex 10: Use the Visualize classier errors function to nd the wrongly classied test instances for the cross-validation performed in Exercise 9. What can you say about the location of the errors?

Ex. 10: Utilice la funcin de Visualize classio er errors para encontrar las instancias de prueba de mal clasicadas para la validacin o cruzada realizada en el ejercicio 9. Qu e puede decir acerca de la ubicacin de los ero rores?

16

Answers To Exercises

1. Hot, mild and cool.

1. caliente, suave y fresco.

2. The iris dataset has 150 instances and 5 attributes. So far we have only seen nominal values, but the attribute petallength is a numeric attribute and contains numeric values. In this dataset the values for this attribute lie between 1.0 and 6.9 (see Minimum and Maximum in the right panel).

2. El conjunto de datos del iris tiene 150 casos y atributos 5. Hasta ahora slo hemos visto o los valores de nominal, pero petallength el atributo es un atributo de numeric y contiene valores numricos. En este conjunto e de datos los valores de este atributo se encuentran entre 1.0 y 6.9 (vase Minimum e Maximum y en el panel derecho).

3. The rst column is the number given to an instance when it is loaded from the ARFF le. It corresponds to the order of the instances in the le.

3. La primera columna es el nmero dado en una u instancia cuando se carga desde el archivo ARFF. Se corresponde con el orden de las instancias en el archivo.

4. The class value of this instance is no. The row with the number 8 in the rst column is the instance with instance number 8.

4. El valor de la clase de esta instancia es no. La la con el nmero 8 en la primera columna u es la instancia con el nmero de instancia u

5. This can be easily seen in the Viewer window. The iris dataset has four numeric and one nominal attribute. The nominal attribute is the class attribute.

5. Esto puede verse fcilmente en la ventana de a Viewer. El conjunto de datos del iris tiene cuatro numrico y un atributo nominal. El e atributo nominal es el atributo de clase.

6. Select the RemoveWithValues lter after clicking the Choose button. Click on the eld that is located next to the Choose button and set the eld attributeIndex to 3 and the eld nominalIndices to 1. Press OK and Apply.

6. Seleccione el RemoveWithValues ltro despus de hacer clic en el botn de Choose. e o Haga clic en el campo que se encuentra al lado del botn de Choose y establezca o el campo attributeIndex a 3 y el campo nominalIndices a 1. Pulse OK y Apply.

7. Click the Undo button.

7. Haga clic en el botn de Undo. o

8. The test instance would be classied as no.

8. La instancia de prueba ser clasicado como a no.

17

9. Percent correct on the training data is 98%. Percent correct under cross-validation is 96%. The cross-validation estimate is more realistic.

9. porcentaje correcto en los datos de entrenamiento es de 98%. Porcentaje de respuestas correctas en la validacin cruzada es del o 96%. La estimacin de la validacin cruzada o o es ms realista. a

10. The errors are located at the class boundaries.

10. Los errores se encuentran en los l mites de clase.

18

Practical Data Mining Tutorial 2: Nearest Neighbor Learning and Decision Trees

Eibe Frank and Ian H. Witten May 5, 2011


c 2006-2012 University of Waikato

Introduction
En este tutorial podrs experimentar con la clasia cacin ms cercano vecino y rbol de decisin o a a o aprendizaje. Para la mayor de los que usamos a un mundo real forenses conjunto de datos de clasicacin de vidrio. o Empezamos por echar un vistazo preliminar a esta base de datos. A continuacin, examinamos el o efecto de la seleccin de atributos diferentes para o la clasicacin del vecino ms cercano. A contino a uacin se estudia el ruido de clase y su impacto o en el rendimiento predictivo del mtodo del vee cino ms cercano. Despus de que variar el tamao a e n del conjunto de la formacin, tanto para la clasio cacin del vecino ms cercano y el rbol de decisin o a a o aprendizaje. Por ultimo, se le pide para construir de forma interactiva un rbol de decisin para un a o conjunto de datos de segmentacin de la imagen. o Antes de continuar con este tutorial es necesario que revise en su mente algunos aspectos de la tarea de clasicacin: o Cmo es la precisin de un clasicador de o o medir?

In this tutorial you will experiment with nearest neighbor classication and decision tree learning. For most of it we use a real-world forensic glass classication dataset.

We begin by taking a preliminary look at this dataset. Then we examine the eect of selecting dierent attributes for nearest neighbor classication. Next we study class noise and its impact on predictive performance for the nearest neighbor method. Following that we vary the training set size, both for nearest neighbor classication and decision tree learning. Finally, you are asked to interactively construct a decision tree for an image segmentation dataset.

Before continuing with this tutorial you should review in your mind some aspects of the classication task: How is the accuracy of a classier measured?

What are irrelevant attributes in a data set, and can additional attributes be harmful?

Cules son los atributos irrelevantes en un a conjunto de datos y atributos adicionales pueden ser perjudiciales?

What is class noise, and how would you measure its eect on learning?

Cul es el ruido de clase, y cmo medir su a o efecto en el aprendizaje?

What is a learning curve?

Qu es una curva de aprendizaje? e

If you, personally, had to invent a decision tree classier for a particular dataset, how would you go about it?

Si usted, personalmente, ten que inventar a un clasicador de rbol de decisin para un a o conjunto de datos particular, cmo hacerlo? o

The glass dataset


El conjunto de datos de cristal [Link] de los [Link]. Servicio de Ciencias Forenses contiene datos sobre los seis tipos de vidrio. El vidrio es descrito por su ndice de refraccin y los elementos o qu micos que contiene, y el objetivo es clasicar los diferentes tipos de vidrio sobre la base de estas caracter sticas. Este conjunto de datos se ha tomado de los conjuntos de datos de la UCI, que han sido recogidos por la Universidad de California en Irvine y estn disponibles libremente en la a World Wide Web. A menudo se utilizan como referencia para comparar los algoritmos de miner a de datos. Encontrar el conjunto de datos [Link] y cargarlo en la Explorer WEKA. Para su propia informacin, conteste las siguientes preguntas, que o el material objeto de examen en el Tutorial 1. Ex. 1: Cmo los atributos con los que cuenta el o conjunto de datos de cristal? Cules son sus a nombres? Cul es el atributo de la clase? a Ejecutar el algoritmo de clasicacin IBK o ([Link]). Utilice la validacin cruzada para probar su funcionamiento, deo jando el nmero de pliegues en el valor predeteru minado de 10. Recuerde que usted puede examinar las opciones del clasicador en la ventana de GenericObjectEditor que aparece al hacer clic en el texto junto al botn Choose. El valor por o defecto del campo KNN es una: este establece el nmero de casos de vecinos a utilizar en la clasiu cacin. o Ex. 2: Qu es la exactitud de IBk (que guran e en el cuadro de Classier output)? Ejecutar IBK otra vez, pero aumentar el nmero u de casos de vecinos a k = 5 por entrar en este valor en el campo KNN. Aqu ya lo largo de este tuto rial, seguir utilizando la validacin cruzada como o el mtodo de evaluacin. e o Ex. 3: Qu es la exactitud de IBk con 5 casos de e vecinos (k = 5)?

The glass dataset [Link] from the US Forensic Science Service contains data on six types of glass. Glass is described by its refractive index and the chemical elements it contains, and the aim is to classify dierent types of glass based on these features. This dataset is taken from the UCI data sets, which have been collected by the University of California at Irvine and are freely available on the World Wide Web. They are often used as a benchmark for comparing data mining algorithms.

Find the dataset [Link] and load it into the WEKA Explorer. For your own information, answer the following questions, which review material covered in Tutorial 1. Ex. 1: How many attributes are there in the glass dataset? What are their names? What is the class attribute? Run the classication algorithm IBk ([Link]). Use crossvalidation to test its performance, leaving the number of folds at the default value of 10. Recall that you can examine the classier options in the GenericObjectEditor window that pops up when you click the text beside the Choose button. The default value of the KNN eld is 1: this sets the number of neighboring instances to use when classifying.

Ex. 2: What is the accuracy of IBk (given in the Classier output box)? Run IBk again, but increase the number of neighboring instances to k = 5 by entering this value in the KNN eld. Here and throughout this tutorial, continue to use cross-validation as the evaluation method. Ex. 3: What is the accuracy of IBk with 5 neighboring instances (k = 5)?

Attribute selection for glass classication


Ahora nos encontramos con lo subconjunto de los atributos produce la exactitud de la clasicacin o mejor validacin cruzada para el algoritmo de veo cino ms cercano IBk con k = 1 en el conjunto a de datos de vidrio. WEKA contiene automatizado instalaciones para la seleccin de atributos, que se o examinan ms adelante en un tutorial, pero es ina structivo para hacerlo manualmente. Realizacin de una bsqueda exhaustiva sobre too u dos los posibles subconjuntos de los atributos no es factible (por qu?), por lo que aplicar un procede imiento llamado al revs de seleccin. Para ello, e o en primer lugar considerar abandonar cada atributo individual del conjunto de datos completa que consiste en nueve atributos (adems de la clase), y a ejecutar una validacin cruzada para cada versin o o reducida. Una vez que haya determinado el conjunto de datos ms de 8 atributo, repita el proceda imiento con este conjunto de datos reduce a encontrar el mejor conjunto de datos 7-atributo, y as sucesivamente. Ex. 4: Registro en la Table 1 el mejor conjunto de atributos y la mayor precisin obtenida o en cada iteracin. o

Now we nd what subset of attributes produces the best cross-validated classication accuracy for the IBk nearest neighbor algorithm with k = 1 on the glass dataset. WEKA contains automated attribute selection facilities, which we examine in a later tutorial, but it is instructive to do this manually.

Performing an exhaustive search over all possible subsets of the attributes is infeasible (why?), so we apply a procedure called backwards selection. To do this, rst consider dropping each attribute individually from the full dataset consisting of nine attributes (plus the class), and run a cross-validation for each reduced version. Once you have determined the best 8-attribute dataset, repeat the procedure with this reduced dataset to nd the best 7-attribute dataset, and so on.

Ex. 4: Record in Table 1 the best attribute set and the greatest accuracy obtained in each iteration.

Table 1: Accuracy obtained using IBk, for dierent attribute subsets Subset size 9 attributes 8 attributes 7 attributes 6 attributes 5 attributes 4 attributes 3 attributes 2 attributes 1 attribute 0 attributes Attributes in best subset Classication accuracy

The best accuracy obtained in this process is quite a bit higher than the accuracy obtained on the full dataset. Ex. 5: Is this best accuracy an unbiased estimate of accuracy on future data? Be sure to explain your answer.

La mejor precisin obtenida en este proceso es un o poco mayor que la precisin obtenida en el cono junto de datos completo. Ex. 5: Es esto mejor precisin una estimacin no o o sesgada de precisin en los datos de futuro? o Asegrese de explicar su respuesta. u

(Hint: to obtain an unbiased estimate of accuracy on future data, we must not look at the test data at all when producing the classication model for which we want to obtain the estimate.)

(Sugerencia: para obtener una estimacin objetiva o de la exactitud en los datos de futuro, no debemos mirar el at all datos de prueba cuando se produce el modelo de clasicacin para la que quero emos obtener la estimacin.) o

Class noise and nearest-neighbor learning


Aprendizaje ms cercana al vecino, al igual que a otras tcnicas, es sensible al ruido en los datos de e entrenamiento. En esta seccin se inyectan cantio dades variables de class noise en los datos de entrenamiento y observar el efecto en el rendimiento de la clasicacin. o Puede invertir un cierto porcentaje de las etiquetas de clase en los datos a un valor escogido de forma aleatoria otras mediante un atributo sin supervisin ltro llamado AddNoise, o en [Link]. Sin embargo, para nuestro experimento es importante que los datos de prueba no se ve afectado por el ruido de la clase. Filtrado de los datos de entrenamiento sin ltrar los datos de prueba es un requisito comn, y u se realiza con un meta clasicador denominado FilteredClassier, en [Link]. Este clasicador meta debe estar congurado para utilizar como IBk AddNoise el clasicador y el ltro. El FilteredClassier se aplica el ltro a los datos antes de ejecutar el algoritmo de aprendizaje. Esto se hace en dos tandas: en primer lugar los datos de entrenamiento y, a continuacin los o datos de prueba. El AddNoise ltro slo hac o a que el primer lote de datos que encuentra, lo que signica que los datos de prueba pasa a travs de e cambios.

Nearest-neighbor learning, like other techniques, is sensitive to noise in the training data. In this section we inject varying amounts of class noise into the training data and observe the eect on classication performance.

You can ip a certain percentage of class labels in the data to a randomly chosen other value using an unsupervised attribute lter called AddNoise, in [Link]. However, for our experiment it is important that the test data remains unaected by class noise.

Filtering the training data without ltering the test data is a common requirement, and is achieved using a meta classier called FilteredClassier, in [Link]. This meta classier should be congured to use IBk as the classier and AddNoise as the lter. The FilteredClassier applies the lter to the data before running the learning algorithm. This is done in two batches: rst the training data and then the test data. The AddNoise lter only adds noise to the rst batch of data it encounters, which means that the test data passes through unchanged.

Table 2: Eect of class noise on IBk, for dierent neighborhood sizes Percent noise 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% k=1 k=3 k=5

Ex. 6: Reload the original glass dataset, and record in Table 2 the cross-validated accuracy estimate of IBk for 10 dierent percentages of class noise and neighborhood sizes k = 1, k = 3, k = 5 (determined by the value of k in the k-nearest-neighbor classier).

Ex. 6: Actualizar el conjunto de datos de vidrio original, y registrar en la Table 2 la exactitud validacin cruzada estimacin de IBk por 10 o o diferentes porcentajes de ruido de la clase y el barrio tamaos k = 1, k = 3, k = 5 (den terminado por el valor de k en el clasicador k vecino ms cercano). a

Ex. 7: What is the eect of increasing the amount of class noise?

Ex. 7: Cul es el efecto de aumentar la cantidad a de ruido de clase?

Ex. 8: What is the eect of altering the value of k?

Ex. 8: Qu elemento es el efecto de modicar el e valor de k?

Varying the amount of training data


En esta seccin tenemos en cuenta las curvas de o aprendizaje, que muestran el efecto de aumentar gradualmente la cantidad de datos de entrenamiento. Una vez ms se utilizan los datos de a vidrio, pero esta vez con dos IBk y la decisin C4.5 o alumno rbol, implementado en WEKA como J48. a Para obtener las curvas de aprendizaje, el uso de la FilteredClassier, esta vez en relacin con el o [Link], que extrae un porcentaje especicado de un conjunto de datos y devuelve el conjunto de datos reducidos.2 Una vez ms esto se hace slo para el a o primer grupo al que se aplica el ltro, por lo que los datos de prueba pasa sin modicar a travs e de la FilteredClassier antes que alcanza el clasicador.

In this section we consider learning curves, which show the eect of gradually increasing the amount of training data. Again we use the glass data, but this time with both IBk and the C4.5 decision tree learner, implemented in WEKA as J48. To obtain learning curves, use the FilteredClassier again, this time in conjunction with [Link], which extracts a certain specied percentage of a given dataset and returns the reduced dataset.1 Again this is done only for the rst batch to which the lter is applied, so the test data passes unmodied through the FilteredClassier before it reaches the classier.

Ex. 9: Record in Table 3 the data for learning curves for both the one-nearest-neighbor classier (i.e., IBk with k = 1) and J48.

Ex. 9: Registro en la Table 3 los datos de las curvas de aprendizaje tanto para el unoclasicador del vecino ms cercano (es decir, a IBk con k = 1) y J48.

lter performs sampling with replacement, rather than sampling without replacement, but the eect is minor and we will ignore it here. 2 Este ltro realiza el muestreo con reemplazo, en lugar de muestreo sin reemplazo, pero el efecto es menor y se lo ignora aqu .

1 This

Table 3: Eect of training set size on IBk and J48 Percentage of training set 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% IBk J48

Ex. 10: What is the eect of increasing the amount of training data?

Ex. 10: Cul es el efecto de aumentar la cantidad a de datos de entrenamiento?

Ex. 11: Is this eect more pronounced for IBk or J48?

Ex. 11: Es este tema efecto ms pronunciado para a IBk o J48?

Interactive decision tree construction


Uno de los clasicadores WEKA es interactiva: permite que el usuarioes decir, queconstruir su propio clasicador. Aqu hay una competen cia: a ver quin puede construir un clasicador e con mayor precisin de prediccin! o o Cargar el archivo [Link] (en la carpeta de datos que viene con la distribucin o de WEKA). Este conjunto de datos cuenta con 20 atributos y las clases 7. Se trata de un problema de segmentacin de la imagen, y la tarea consiste o en clasicar las imgenes en siete grupos diferentes a basados en las propiedades de los p xeles. Ajuste el clasicador a UserClassier, en el [Link] paquete. Vamos a utilizar una unidad de prueba suministrada (realizar la validacin cruzada con el clasicador de usuario o es muy aburrido!). En el cuadro de Test options, seleccione la opcin de Supplied test set o y haga clic en el botn de Set.... Aparecer una o a pequea ventana en la que usted elija el equipo n de prueba. Haga clic en Open le... y busque el archivo [Link] (tambin en la care peta de datos de la distribucin de WEKA). Al o hacer clic en Open, las actualizaciones pequea n ventana para mostrar el nmero de casos (810) y u atributos (20), cirrelo. e

One of WEKAs classiers is interactive: it lets the useri.e., you!construct your own classier. Heres a competition: lets see who can build a classier with the highest predictive accuracy!

Load the le [Link] (in the data folder that comes with the WEKA distribution). This dataset has 20 attributes and 7 classes. It is an image segmentation problem, and the task is to classify images into seven dierent groups based on properties of the pixels.

Set the classier to UserClassier, in the [Link] package. We will use a supplied test set (performing cross-validation with the user classier is incredibly tedious!). In the Test options box, choose the Supplied test set option and click the Set... button. A small window appears in which you choose the test set. Click Open le... and browse to the le [Link] (also in the WEKA distributions data folder). On clicking Open, the small window updates to show the number of instances (810) and attributes (20); close it.

Click Start. The behaviour of UserClassier differs from all other classiers. A special window appears and WEKA waits for you to use it to build your own classier. The tabs at the top of the window switch between two views of the classier. The Tree visualizer view shows the current state of your tree, and the nodes give the number of class values there. The aim is to come up with a tree where the leaf nodes are as pure as possible. To begin with, the tree has just one nodethe root nodecontaining all the data. More nodes will appear when you proceed to split the data in the Data visualizer view.

Haga clic en Start. El comportamiento de UserClassier se diferencia de todos los otros clasicadores. Una ventana especial aparece y WEKA espera a que se utilizar para construir su propio clasicador. Las pestaas en la parte superior del n interruptor de la ventana entre dos puntos de vista del clasicador. El punto de vista Tree visualizer muestra el estado actual de su rbol, y los a nodos dar el nmero de valores de clase all El u . objetivo es llegar a un rbol donde los nodos hoja a son tan puros como sea posible. Para empezar, el a rbol tiene un solo nodoel nodo ra zque contiene todos los datos. Ms nodos aparecer cuando a a se procede a dividir los datos en la vista de Data visualizer. Haga clic en la cha Data visualizer para ver un grco 2D en el que los puntos de datos estn coda a icados por colores segn la clase. Puede cambiar u los atributos utilizados para los ejes, ya sea con la X e Y mens desplegables en la parte superior, o u presionando el botn izquierdo (para X) o el botn o o derecho del ratn (para Y) las tiras horizontales a o la derecha del rea de trazado . Estas tiras muesa tran la propagacin de casos a lo largo de cada o atributo en particular. Tendr que probar diferentes combinaciones de a ejes X e Y para obtener la ms clara la separacin a o que se encuentran entre los colores. Cuando exista una buena separacin, a continuacin, deber seo o a leccionar una regin en la trama: esto crear una o a rama en el rbol. Aqu est una sugerencia para a a comenzar: parcela region-centroid-row en el eje X y intensity-media en el eje. Usted ver que la a clase de color rojo (cielo) est muy bien separado a del resto de las clases en la parte superior de la parcela. Existen tres herramientas para la seleccin de las o regiones en el grco, elegidos mediante el men a u desplegable debajo del selector de eje: 1. Rectangle le permite seleccionar los puntos arrastrando un rectngulo alrededor de ellos. a

Click the Data visualizer tab to see a 2D plot in which the data points are colour coded by class. You can change the attributes used for the axes either with the X and Y drop-down menus at the top, or by left-clicking (for X) or right-clicking (for Y) the horizontal strips to the right of the plot area. These strips show the spread of instances along each particular attribute.

You need to try dierent combinations of X and Y axes to get the clearest separation you can nd between the colours. Having found a good separation, you then need to select a region in the plot: this will create a branch in your tree. Here is a hint to get you started: plot region-centroid-row on the X-axis and intensity-mean on the Y-axis. You will see that the red class (sky) is nicely separated from the rest of the classes at the top of the plot.

There are three tools for selecting regions in the graph, chosen using the drop-down menu below the Y-axis selector: 1. Rectangle allows you to select points by dragging a rectangle around them.

2. Polygon allows you to select points by drawing a free-form polygon. Left-click to add vertices; right-click to complete the polygon. The polygon will be closed o by connecting the rst and last points.

2. Polygon le permite seleccionar los puntos dibujando un pol gono de forma libre. Haga clic izquierdo para aadir vrtices, haga clic n e para completar el pol gono. El pol gono se cierran mediante la conexin de los puntos o primero y el ultimo.

3. Polyline allows you to select points by drawing a free-form polyline. Left-click to add vertices; right-click to complete the shape. The resulting shape is open, as opposed to the polygon which is closed.

3. Polyline le permite seleccionar los puntos dibujando una polil nea de forma libre. Haga clic izquierdo para aadir vrtices, haga clic n e para completar la forma. La forma resultante es abierto, en comparacin con el o pol gono que est cerrado. a Cuando haya seleccionado un rea usando a cualquiera de estas herramientas, que se vuelve gris. Al hacer clic en el botn Clear cancela la o seleccin sin afectar el clasicador. Cuando usted o est satisfecho con la seleccin, haga clic en Suba o mit. Esto crea dos nuevos nodos en el rbol, a una celebracin de todos los casos cubiertos por o la seleccin y el otro posee la totalidad de los cao sos restantes. Estos nodos se corresponden a una divisin binaria que realiza la prueba geomtrica o e elegida. Cambie de nuevo a la vista de Tree visualizer para examinar el cambio en el rbol. Al hacer clic a en los nodos diferentes altera el subconjunto de los datos que se muestra en la seccin de Data visuo alizer. Contine aadiendo nodos hasta obtener u n una buena separacin de las claseses decir, los o nodos hoja en el rbol son en su mayor puro. a a Sin embargo, recuerde que usted no desea sobreajuste de los datos, ya que el rbol ser evaluado en a a un conjunto de prueba independiente. Cuando est satisfecho con el rbol, haga clic en e a cualquier espacio en blanco en la vista Tree visualizer y elija Accept The Tree. WEKA evala el u a rbol contra el equipo de prueba y las estad sticas de resultados que muestran lo bien que hizo. Usted est compitiendo por la mejor puntuacin a o de exactitud de una mano-construido UserClassier conjunto de datos producidos en el segmentchallenge y de prueba en el set del segment-test. Trate tantas veces como quieras. Un buen resultado es algo cercano a 90% de aciertos o mejor. Ejecutar J48 en los datos para ver qu tan bien e un estudiante de rbol de decisin automtica rea o a aliza la tarea. Ex. 12: Cuando usted piensa que tiene un buen puntaje, haga clic en la entrada correspondiente en la Result list, guardar el resultado con Save result buer, y copiarlo en su respuesta para este tutorial.

When you have selected an area using any of these tools, it turns gray. Clicking the Clear button cancels the selection without aecting the classier. When you are happy with the selection, click Submit. This creates two new nodes in the tree, one holding all the instances covered by the selection and the other holding all remaining instances. These nodes correspond to a binary split that performs the chosen geometric test.

Switch back to the Tree visualizer view to examine the change in the tree. Clicking on dierent nodes alters the subset of data that is shown in the Data visualizer section. Continue adding nodes until you obtain a good separation of the classes that is, the leaf nodes in the tree are mostly pure. Remember, however, that you do not want to overt the data, because your tree will be evaluated on a separate test set.

When you are satised with the tree, right-click any blank space in the Tree visualizer view and choose Accept The Tree. WEKA evaluates your tree against the test set and outputs statistics that show how well you did. You are competing for the best accuracy score of a hand-built UserClassier produced on the segment-challenge dataset and tested on the segment-test set. Try as many times as you like. A good score is anything close to 90% correct or better. Run J48 on the data to see how well an automatic decision tree learner performs on the task.

Ex. 12: When you think you have a good score, right-click the corresponding entry in the Result list, save the output using Save result buer, and copy it into your answer for this tutorial.

Practical Data Mining Tutorial 3: Classication Boundaries

Eibe Frank and Ian H .Witten May 5, 2011


c 2008-2012 University of Waikato

Introduction
En este tutorial se ver en los l a mites de clasicacin que son producidas por diferentes tipos de o modelos. Para ello, utilizamos BoundaryVisualizer de WEKA. Esto es no parte del Explorador de WEKA que hemos estado utilizando hasta ahora. Poner en marcha el GUI Chooser WEKA como de costumbre en el men INICIO de Windows u (en Linux o Mac, haga doble clic en [Link] o [Link]). En el men Visualization en la parte u superior, seleccione BoundaryVisualizer. El visualizador muestra los l mites parcelas de dos dimensiones de los datos, y es ms adecuado para a conjuntos de datos con dos atributos numricos. e Vamos a utilizar una versin de los datos del iris, o sin los dos primeros atributos. Para crear esta partir de los datos del iris estndar, la puesta en mara cha del Explorer, la carga [Link] usando el botn de Open le y quite los dos primeros atribo utos (sepallength y sepalwidth), seleccionando y haciendo clic en el botn que Remove aparece en o la parte inferior. A continuacin, guarde el cono junto de datos modicados en un archivo (usando Save) llamado, por ejemplo, [Link]. Ahora deja el Explorer y abrir este archivo para la visualizacin mediante el visualizador de Fronteras o botn Open File.... Inicialmente, la trama slo o o muestra los datos en el conjunto de datos.2

In this tutorial you will look at the classication boundaries that are produced by dierent types of models. To do this, we use WEKAs BoundaryVisualizer. This is not part of the WEKA Explorer that we have been using so far. Start up the WEKA GUI Chooser as usual from the Windows START menu (on Linux or the Mac, double-click [Link] or [Link]). From the Visualization menu at the top, select BoundaryVisualizer.

The boundary visualizer shows two-dimensional plots of the data, and is most appropriate for datasets with two numeric attributes. We will use a version of the iris data without the rst two attributes. To create this from the standard iris data, start up the Explorer, load [Link] using the Open le button and remove the rst two attributes (sepallength and sepalwidth) by selecting them and clicking the Remove button that appears at the bottom. Then save the modied dataset to a le (using Save) called, say, [Link].

Now leave the Explorer and open this le for visualization using the boundary visualizers Open File... button. Initially, the plot just shows the data in the dataset.1

Visualizing 1R
Slo gracar los datos no es nada nuevo. El vero dadero propsito del visualizador l o mite es mostrar la predicciones de un modelo determinado para cada lugar en el espacio. Los puntos que representan los datos estn codicados por colores basados a en la prediccin del modelo genera. Vamos a utio lizar esta funcionalidad para investigar los l mites de la decisin que los clasicadores diferentes para o generar el conjunto de datos del iris reducida.

Just plotting the data is nothing new. The real purpose of the boundary visualizer is to show the predictions of a given model for each location in space. The points representing the data are color coded based on the prediction the model generates. We will use this functionality to investigate the decision boundaries that dierent classiers generate for the reduced iris dataset.

is a bug in the initial visualization. To get a true plot of the data, select a dierent attribute for either the x or y axis by clicking the appropriate button. 2 No es un error en la visualizacin inicial. Para obtener una verdadera trama de los datos, seleccione un atributo o diferente, ya sea para los x o y eje haciendo clic en el botn correspondiente. o

1 There

We start with the 1R rule learner. Use the Choose button of the boundary visualizer to select [Link] . Make sure you tick Plot training data, otherwise only the predictions will be plotted. Then hit the Start button. The program starts plotting predictions in successive scan lines. Hit the Stop button once the plot has stabilizedas soon as you like, in this caseand the training data will be superimposed on the boundary visualization.

Empezamos con el aprendiz regla 1R. Utilice el botn de Choose del visualizador l o mite para seleccionar [Link]. Asegrese de que usted marque Plot training u data, de lo contrario slo las predicciones se o trazan. A continuacin, pulse el botn Start. o o El programa comienza a las predicciones de conspirar en las sucesivas l neas de exploracin. Pulse o el botn de Stop, una vez la trama se ha o estabilizadotan pronto como quiera, en este casoy los datos de entrenamiento se superpone a la visualizacin de frontera. o Ex. 1: Explicar el argumento basado en lo que sabe sobre 1R. (Sugerencia: usar el Explorer a mirar el conjunto de reglas que 1R genera para estos datos.)

Ex. 1: Explain the plot based on what you know about 1R. (Hint: use the Explorer to look at the rule set that 1R generates for this data.)

Ex. 2: Study the eect of the minBucketSize parameter on the classier by regenerating the plot with values of 1, and then 20, and then some critical values in between. Describe what you see, and explain it. (Hint: you could speed things up by using the Explorer to look at the rule sets.)

Ex. 2: Estudiar el efecto del parmetro mina BucketSize en el clasicador por la regeneracin de la parcela con valores de 1, y luego o 20 y, a continuacin algunos valores cr o ticos en el medio. Describe lo que ves, y explicarlo. (Sugerencia: puede acelerar las cosas mediante el Explorer a ver algunos de los conjuntos de reglas.)

Visualizing nearest-neighbor learning


Ahora nos jamos en los l mites de clasicacin creado por el mtodo del vecino ms cero e a cano. Utilice el botn de visualizador l o mite de Choose... para seleccionar el clasicador IBk ([Link]) y la trama de sus l mites de decisin para reducir los datos del iris. o

Now we look at the classication boundaries created by the nearest neighbor method. Use the boundary visualizers Choose... button to select the IBk classier ([Link]) and plot its decision boundaries for the reduced iris data.

In WEKA, OneRs predictions are categorical: for each instance they predict one of the three classes. In contrast, IBk outputs probability estimates for each class, and these are used to mix the colors red, green, and blue that correspond to the three classes. IBk estimates class probabilities by counting the number of instances of each class in the set of nearest neighbors of a test case and uses the resulting relative frequencies as probability estimates. With k = 1, which is the default value, you might expect there to be only one instance in the set of nearest neighbors of each test case (i.e. pixel location). Looking at the plot, this is indeed almost always the case, because the estimated probability is one for almost all pixels, resulting in a pure color. There is no mixing of colors because one class gets probability one and the others probability zero.

En WEKA, las predicciones OneR son categricos: para cada instancia que predio cen una de las tres clases. Por el contrario, las salidas IBk estimaciones de probabilidad para cada clase, y estas se utilizan para mezclar los colores rojo, verde y azul, que corresponden a las tres clases. IBk estimaciones de probabilidades de clase contando el nmero de casos de cada clase u en el conjunto de los vecinos ms cercanos de un a caso de prueba y utiliza las frecuencias resultantes relativa como las estimaciones de probabilidad. Con k = 1, que es el valor por defecto, es de esperar que haya una sola instancia en el conjunto de vecinos ms cercanos de cada caso de prueba a (es decir, lugar de p xeles). En cuanto a la trama, esto es de hecho casi siempre el caso, ya que la probabilidad estimada es uno de casi todos los p xeles, dando como resultado un color puro. No hay mezcla de colores, porque una clase recibe una probabilidad y la probabilidad de los dems a cero. Ex. 3: Sin embargo, hay una pequea rea de la n a parcela en la que dos colores son en realidad mixta. Explique esto. (Sugerencia: mirar cuidadosamente los datos mediante el panel Visualizar en el Explorer.)

Ex. 3: Nevertheless, there is a small area in the plot where two colors are in fact mixed. Explain this. (Hint: look carefully at the data using the Visualize panel in the Explorer.)

Ex. 4: Experiment with dierent values for k, say 5 and 10. Describe what happens as k increases.

Ex. 4: Experimente con diferentes valores de k, por ejemplo 5 y 10. Describir lo que sucede cuando aumenta k.

Visualizing naive Bayes


Paso ahora a los ingenuos clasicador de Bayes. Esto supone que los atributos son condicionalmente independientes dado un valor de clase especial. Esto signica que la probabilidad de clase global se obtiene simplemente multiplicando por el atributo de probabilidades condicionales juntos. En otras palabras, con dos atributos, no s si las e probabilidades de clase a lo largo del eje X ya lo largo del eje, se puede calcular el valor de cualquier punto del espacio multiplicando juntos. Esto es ms fcil de entender si la visualizan como una a a parcela de contorno.

Turn now to the naive Bayes classier. This assumes that attributes are conditionally independent given a particular class value. This means that the overall class probability is obtained by simply multiplying the per-attribute conditional probabilities together. In other words, with two attributes, if you know the class probabilities along the x-axis and along the y-axis, you can calculate the value for any point in space by multiplying them together. This is easier to understand if you visualize it as a boundary plot.

Plot the predictions of naive Bayes. But rst, you need to discretize the attribute values. By default, NaiveBayes assumes that the attributes are normally distributed given the class (i.e., they follow a bell-shaped distribution). You should override this by setting useSupervisedDiscretization to true using the GenericObjectEditor. This will cause NaiveBayes to discretize the numeric attributes in the data using a supervised discretization technique.3

Parcela las predicciones de Bayes ingenuo. Pero primero, tiene que discretizar los valores de atributo. De forma predeterminada, NaiveBayes asume que los atributos tienen una distribucin o normal habida cuenta de la clase (es decir, que siguen una distribucin en forma de campana). o Usted debe cambiar este ajuste de useSupervisedDiscretization a true utilizando el GenericObjectEditor. Esto har que NaiveBayes a para discretizar los atributos numricos de los e datos mediante una tcnica de discretizacin sue o pervisado.4 En casi todas las aplicaciones prcticas de la a NaiveBayes, discretizacin supervisado es ms o a ecaz que el mtodo por defecto, y es por eso que e lo consideramos aqu Tambin produce una visu. e alizacin ms comprensible. o a Ex. 5: La trama que se genera mediante la visualizacin de las probabilidades de clase preo visto de Bayes ingenuo para cada posicin de o p es muy diferente de todo lo que hemos xel visto hasta ahora. Explicar los patrones en ella.

In almost all practical applications of NaiveBayes, supervised discretization works better than the default method, and that is why we consider it here. It also produces a more comprehensible visualization. Ex. 5: The plot that is generated by visualizing the predicted class probabilities of naive Bayes for each pixel location is quite dierent from anything we have seen so far. Explain the patterns in it.

Visualizing decision trees and rule sets


Los rboles de decisin y conjuntos de reglas son a o similares a los del vecino ms prximo de aprena o dizaje en el sentido de que son tambin casi unie versal: en principio, se puede aproximar cualquier l mite de la decisin arbitraria de cerca. En esta o seccin, nos jamos en los l o mites generados por JRip y J48. Generar una parcela de JRip, con las opciones predeterminadas. Ex. 6: Qu ves? La trama a la salida de las nore mas que se obtiene al procesar los datos en la Explorer.

Decision trees and rule sets are similar to nearestneighbor learning in the sense that they are also quasi-universal: in principle, they can approximate any decision boundary arbitrarily closely. In this section, we look at the boundaries generated by JRip and J48.

Generate a plot for JRip, with default options.

Ex. 6: What do you see? Relate the plot to the output of the rules that you get by processing the data in the Explorer.

Ex. 7: The JRip output assumes that the rules will be executed in the correct sequence. Write down an equivalent set of rules that achieves the same eect regardless of the order in which they are executed.
3 The

Ex. 7: La salida JRip asume que las normas se ejecutar en el orden correcto. Escriba un a conjunto equivalente de las normas que logra el mismo efecto sin importar el orden en que se ejecutan.

technique used is supervised because it takes the class labels of the instances into account to nd good split points for the discretization intervals. 4 La tcnica utilizada es supervisada, porque tiene las etiquetas de clase de las instancias en cuenta para encontrar e buenos puntos de partido para los intervalos de discretizacin. o

Generate a plot for J48, with default options.

Generar una parcela de J48, con las opciones predeterminadas. Ex. 8: Qu ves? La trama a la salida del rbol e a que se obtiene al procesar los datos en la Explorer. Una forma de controlar la cantidad de poda J48 realiza antes de que los resultados de su rbol es a para ajustar el nmero m u nimo de casos necesarios en una hoja, minNumbObj. Ex. 9: Supongamos que desea generar rboles a con 3, 2 y 1 respectivamente nodos de la hoja. Cules son los rangos de los valores exactos a de minNumObj que lograr este objetivo, los valores por defecto para todos los otros parmetros? a

Ex. 8: What do you see? Relate the plot to the output of the tree that you get by processing the data in the Explorer. One way to control how much pruning J48 performs before it outputs its tree is to adjust the minimum number of instances required in a leaf, minNumbObj. Ex. 9: Suppose you want to generate trees with 3, 2, and 1 leaf nodes respectively. What are the exact ranges of values for minNumObj that achieve this, given default values for all other parameters?

Messing with the data


Con el BoundaryVisualizer se pueden modicar los datos, aadiendo o quitando puntos. n Ex. 10: Introducir algunos ruidos en los datos y estudiar el efecto sobre los algoritmos de aprendizaje que vimos anteriormente. Qu e tipo de comportamiento no se observa para cada algoritmo como introducir ms ruido? a

With the BoundaryVisualizer you can modify the data by adding or removing points. Ex. 10: Introduce some noise into the data and study the eect on the learning algorithms we looked at above. What kind of behavior do you observe for each algorithm as you introduce more noise?

1R revisited
Volver al alumno regla 1R en el iris reducido conjunto de datos utilizado en la Seccin 2 (no la o versin ruidosa que acaba de crear). Las siguo ientes preguntas le exigir que pensar en el funa cionamiento interno de 1R. (Sugerencia: es probable que sea ms rpido utilizar el Explorer a ver a a algunos de los conjuntos de reglas.) Ex. 11: Se vio en la Seccin 2 que la trama siemo pre tiene tres regiones. Pero por qu no hay e ms para las dimensiones de cubo pequeo a n (por ejemplo, 1)? Usa lo que sabes sobre 1R para explicar esta aparente anomal a.

Return to the 1R rule learner on the reduced iris dataset used in Section 2 (not the noisy version you just created). The following questions will require you to think about the internal workings of 1R. (Hint: it will probably be fastest to use the Explorer to look at the rule sets.)

Ex. 11: You saw in Section 2 that the plot always has three regions. But why arent there more for small bucket sizes (e.g., 1)? Use what you know about 1R to explain this apparent anomaly.

Ex. 12: Can you set minBucketSize to a value that results in less than three regions? What is the smallest possible number of regions? What is the smallest value for minBucketSize that gives you this number of regions? Explain the result based on what you know about the iris data.

Ex. 12: Se puede congurar minBucketSize a un valor que los resultados en menos de tres regiones? Cul es el menor nmero posible a u de regiones? Cul es el valor ms pequeo a a n de minBucketSize que le da este nmero u de regiones? Explicar el resultado sobre la base de lo que sabe acerca de los datos del iris.

Practical Data Mining Tutorial 4: Preprocessing and Parameter Tuning

Eibe Frank and Ian H. Witten May 5, 2011


c 2008-2012 University of Waikato

Introduction
Preprocesamiento de datos es a menudo necesario para obtener los datos listos para el aprendizaje. Tambin puede mejorar el resultado del proceso de e aprendizaje y dar lugar a modelos ms precisos y a concisos. Lo mismo es cierto para los mtodos de e ajuste de parmetros. En este tutorial vamos a a ver algunas de las tcnicas de preprocesamiento e util, que se aplican como ltros de WEKA, as como un mtodo para el ajuste automtico de los e a parmetros. a

Data preprocessing is often necessary to get data ready for learning. It may also improve the outcome of the learning process and lead to more accurate and concise models. The same is true for parameter tuning methods. In this tutorial we will look at some useful preprocessing techniques, which are implemented as WEKA lters, as well as a method for automatic parameter tuning.

Discretization
los atributos numricos se pueden convertir en los e discretos mediante el fraccionamiento de sus reas a de distribucin en intervalos numricos, un proo e ceso conocido como discretizacin. Hay dos tipos o de tcnicas de discretizacin: sin supervisin los e o o que son de clase ciego, y una supervisin, que o tienen el valor de clase de las instancias en cuenta al crear intervalos. El objetivo con las tcnicas de e supervisin es la creacin de intervalos que sean o o tan coherentes como sea posible con respecto a las etiquetas de clase. El principal tcnica unsupervisada para dise cretizar los atributos numricos en WEKA e es [Link]. Discretize. Se implementa dos mtodos sencile los: la igualdad de ancho y discretizacin de igual o frecuencia. El primero, simplemente se divide el rango numrico en intervalos iguales. El segundo e opta por la amplitud de los intervalos para que los mismos contienen (aproximadamente) el mismo nmero de casos. El valor por defecto es usar la u misma anchura. Encontrar el conjunto de datos de cristal [Link] y cargarlo en la Explorer. Aplicar el ltro de discretizacin sin supervisin en las dos o o modalidades anteriormente expuestas. Ex. 1: Qu observa al comparar los histogramas e obtenidos? Por qu es la discretizacin de e o la igualdad de frecuencia muy sesgada de algunos atributos?

Numeric attributes can be converted into discrete ones by splitting their ranges into numeric intervals, a process known as discretization. There are two types of discretization techniques: unsupervised ones, which are class blind., and supervised one, which take the class value of the instances into account when creating intervals. The aim with supervised techniques is to create intervals that are as consistent as possible with respect to the class labels.

The main unsupervised technique for discretizing numeric attributes in WEKA is [Link]. Discretize. It implements two straightforward methods: equal-width and equal-frequency discretization. The rst simply splits the numeric range into equal intervals. The second chooses the width of the intervals so that they contain (approximately) the same number of instances. The default is to use equal width.

Find the glass dataset [Link] and load it into the Explorer. Apply the unsupervised discretization lter in the two dierent modes discussed above. Ex. 1: What do you observe when you compare the histograms obtained? Why is the one for equal-frequency discretization quite skewed for some attributes?

The main supervised technique for discretizing numeric attributes in WEKA is [Link]. Discretize. Locate the iris data, load it in, apply the supervised discretization scheme, and look at the histograms obtained. Supervised discretization attempts to create intervals such that the class distributions dier between intervals but are consistent within intervals.

El principal supervisado tcnica para dise cretizar los atributos numricos en WEKA e es [Link]. Discretize. Busque los datos del iris, se carga en, aplicar el esquema de discretizacin o supervisado, y ver los histogramas obtenidos. Encuadramiento intentos de discretizacin para crear o intervalos de tal manera que las distribuciones dieren entre los intervalos de clase, pero son coherentes dentro de los intervalos. Ex. 2: Con base en los histogramas obtenidos, que de los atributos discretizados se tiene en cuenta los ms predictivo? a Actualizar los datos de vidrio y aplicar discretizacin supervisada a la misma. o Ex. 3: Slo hay una sola barra en los histogramas o de algunos de los atributos. Qu signica e eso? Atributos discretizado normalmente codicados como atributos nominales, con un valor por rango. Sin embargo, debido a los rangos estn ordenados, a un atributo discretizado es en realidad en una escala ordinal. Ambos ltros tambin tienen la cae pacidad de crear los atributos binarios en lugar de los mltiples valores, mediante el establecimiento u de la makeBinary opcin de verdad. o Ex. 4: Elegir un de los ltros y aplicarlo para crear atributos binarios. Compare con el resultado generado cuando makeBinary es falsa. Qu signican los atributos binarios e representan?

Ex. 2: Based on the histograms obtained, which of the discretized attributes would you consider the most predictive ones? Reload the glass data and apply supervised discretization to it. Ex. 3: There is only a single bar in the histograms for some of the attributes. What does that mean? Discretized attributes are normally coded as nominal attributes, with one value per range. However, because the ranges are ordered, a discretized attribute is actually on an ordinal scale. Both lters also have the ability to create binary attributes rather than multi-valued ones, by setting the option makeBinary to true.

Ex. 4: Choose one of the lters and apply it to create binary attributes. Compare to the output generated when makeBinary is false. What do the binary attributes represent?

More on Discretization
Aqu se examina el efecto de la discretizacin en o la construccin de un rbol de decisin J48 para o a o los datos de [Link]. Este conjunto de datos contiene informacin acerca de las seales o n de radar de regresar de la ionosfera. Bueno son las muestras que presenten indicios de algn tipo u de estructura de la ionosfera, mientras que para los malos las seales pasan directamente a travs de n e la ionosfera. Para obtener ms informacin, visita a o los comentarios en el archivo ARFF. Comience con discretizacin sin supervisin. o o

Here we examine the eect of discretization when building a J48 decision tree for the data in [Link]. This dataset contains information about radar signals returned from the ionosphere. Good samples are those showing evidence of some type of structure in the ionosphere, while for bad ones the signals pass directly through the ionosphere. For more details, take a look the comments in the ARFF le. Begin with unsupervised discretization.

Ex. 5: Compare the cross-validated accuracy of J48 and the size of the trees generated for (a) the raw data, (b) data discretized by the unsupervised discretization method in default mode, (c) data discretized by the same method with binary attributes.

Ex. 5: Comparacin de la precisin validacin o o o cruzada de J48 y el tamao de los rboles n a generados por (a) los datos en bruto, (b) los datos discretizados por el mtodo de dise cretizacin sin supervisin en el modo por deo o fecto, (c) los datos discretizados por el mismo mtodo con atributos binarios. e Ahora pasa a la discretizacin supervisado. Aqu o surge una cuestin sutil. Si nos limitamos a repeo tir el ejercicio anterior utilizando un mtodo de e discretizacin supervisado, el resultado ser deo a masiado optimista. En efecto, ya que la validacin o cruzada se utiliza para la evaluacin, los datos en o el conjunto de pruebas se ha tenido en cuenta para determinar los intervalos de discretizacin. Esto o no da una estimacin razonable de rendimiento en o nuevos datos. Para evaluar discretizacin supervisado de mano era justa, se utiliza el FilteredClassier de meta de WEKA-clasicadores. Esto se basa el modelo de ltro de los datos de entrenamiento solamente, antes de evaluar que en los datos de prueba mediante los intervalos de discretizacin calculados para o los datos de entrenamiento. Despus de todo, que e es como se tendr que procesar los datos frescos a en la prctica. a Ex. 6: Comparacin de la precisin validacin o o o cruzada y el tamao de los rboles generan a dos con el FilteredClassier y J48 para (d) discretizacin supervisado en su modo noro mal, (e) discretizacin de supervisin de los o o atributos binarios.

Now turn to supervised discretization. Here a subtle issue arises. If we simply repeated the previous exercise using a supervised discretization method, the result would be over-optimistic. In eect, since cross-validation is used for evaluation, the data in the test set has been taken into account when determining the discretization intervals. This does not give a fair estimate of performance on fresh data.

To evaluate supervised discretization in a fair fashion, we use the FilteredClassier from WEKAs meta-classiers. This builds the lter model from the training data only, before evaluating it on the test data using the discretization intervals computed for the training data. After all, that is how you would have to process fresh data in practice.

Ex. 6: Compare the cross-validated accuracy and the size of the trees generated using the FilteredClassier and J48 for (d) supervised discretization in default mode, (e) supervised discretization with binary attributes.

Ex. 7: Compare these with the results for the raw data ((a) above). Can you think of a reason of why decision trees generated from discretized data can potentially be more accurate predictors than those built from raw numeric data?

Ex. 7: Compare estos datos con los resultados de los datos en bruto ((a) anterior). Puedes pensar en una razn de por qu los rboles de o e a decisin generados a partir de datos discretos o pueden ser potencialmente predictores ms a ables que las construye a partir de datos numricos en bruto? e

Automatic Attribute Selection


En la mayor de las aplicaciones prcticas de a a aprendizaje supervisado, no todos los atributos son igualmente utiles para predecir el destino. De pendiendo de la actividad de aprendizaje empleados, redundantes y/o atributos irrelevantes pueden dar lugar a modelos menos precisos generando. La tarea de identicar manualmente los atributos utiles en un conjunto de datos puede ser tedioso, ya que hemos visto en el segundo tutorialpero hay mtodos automticos de seleccin de atributos que e a o se pueden aplicar. Pueden dividirse en aquellos que se clasican los atributos individuales (por ejemplo, sobre la base de su ganancia de informacin) y los de bsqueda o u que para un subconjunto de los atributos de buena considerando el efecto combinado de los atributos en el subconjunto. Estos mtodos se pueden die vidir en los llamados ltro y contenedor mtodos. e mtodos de aplicar un ltro eciente computae cionalmente heur stica para medir la calidad de un subconjunto de los atributos. mtodos Wrapper e medir la calidad de un subconjunto de atributos mediante la construccin y evaluacin de un modo o elo de clasicacin real de ella, generalmente se o basa en la validacin cruzada. Esto es ms caro, o a pero a menudo ofrece un rendimiento superior. En el Explorer WEKA, puede utilizar el panel de Select attributes de aplicar un mtodo de e seleccin de atributos en un conjunto de datos. o El valor predeterminado es CfsSubsetEval. Sin embargo, si queremos clasicar los atributos individuales, tenemos que recurrir a un evaluador de atributos en vez de un subgrupo evaluador, por ejemplo, la InfoGainAttributeEval. evaluadores de atributos deben ser aplicados con un especial de bsqueda mtodo, a saber, la Ranker. u e Ex. 8: Aplicar esta tcnica para las negociaciones e laborales de datos en [Link]. Cules a son los cuatro atributos ms importantes a basadas en el aumento de la informacin?2 o

In most practical applications of supervised learning not all attributes are equally useful for predicting the target. Depending on the learning scheme employed, redundant and/or irrelevant attributes can result in less accurate models being generated. The task of manually identifying useful attributes in a dataset can be tedious, as you have seen in the second tutorialbut there are automatic attribute selection methods that can be applied.

They can be broadly divided into those that rank individual attributes (e.g., based on their information gain) and those that search for a good subset of attributes by considering the combined eect of the attributes in the subset. The latter methods can be further divided into so-called lter and wrapper methods. Filter methods apply a computationally ecient heuristic to measure the quality of a subset of attributes. Wrapper methods measure the quality of an attribute subset by building and evaluating an actual classication model from it, usually based on cross-validation. This is more expensive, but often delivers superior performance.

In the WEKA Explorer, you can use the Select attributes panel to apply an attribute selection method on a dataset. The default is CfsSubsetEval. However, if we want to rank individual attributes, we need to use an attribute evaluator rather than a subset evaluator, e.g., the InfoGainAttributeEval. Attribute evaluators need to be applied with a special search method, namely the Ranker.

Ex. 8: Apply this technique to the labour negotiations data in [Link]. What are the four most important attributes based on information gain?1

1 Note that most attribute evaluators, including InfoGainAttributeEval, discretize numeric attributes using WEKAs supervised discretization method before they are evaluated. This is also the case for CfsSubsetEval. 2 Nota que la mayor de los evaluadores de atributos, incluyendo InfoGainAttributeEval, discretizar los atributos a numricos mediante el mtodo de discretizacin supervisado WEKA antes de que se evalan. Este es tambin el caso de e e o u e CfsSubsetEval.

WEKAs default attribute selection method, CfsSubsetEval, uses a heuristic attribute subset evaluator in a lter search method. It aims to identify a subset of attributes that are highly correlated with the target while not being strongly correlated with each other. By default, it searches through the space of possible attribute subsets for the best one using the BestFirst search method.3 You can choose others, like a genetic algorithm or even an exhaustive search. In fact, choosing GreedyStepwise and setting searchBackwards to true gives backwards selection, the search method you used manually in the second tutorial.

WEKA atributo por defecto el mtodo de see leccin, CfsSubsetEval, utiliza un subconjunto o de atributos evaluador heur stica en un mtodo de e ltro de bsqueda. Su objetivo es identicar un u subconjunto de los atributos que estn muy cora relacionados con el objetivo sin ser fuertemente correlacionados entre s De forma predetermi. nada, se busca a travs del espacio de subcone juntos de atributos posibles para el mejor con el mtodo de bsqueda BestFirst.4 Usted puede e u elegir otros, como un algoritmo gentico o incluso e una exhaustiva bsqueda. De hecho, la eleccin u o de GreedyStepwise searchBackwards y el establecimiento de verdad da al revs de seleccin, e o el mtodo de bsqueda que usa manualmente en el e u segundo tutorial. Para utilizar el mtodo de envoltura en vez de un e mtodo de ltro como CfsSubsetEval, es necee sario seleccionar WrapperSubsetEval. Puede congurar esta eligiendo un algoritmo de aprendizaje de aplicar. Tambin puede establecer el e nmero de pliegues para la validacin cruzada que u o se utiliza para evaluar el modelo en cada subconjunto de atributos. Ex. 9: En los mismos datos, CfsSubsetEval correr para la seleccin basada en la correlacin, o o mediante la bsqueda de BestFirst. A conu tinuacin, ejecute el mtodo de envoltura con o e J48 como el aprendiz de base, utilizando de nuevo la bsqueda BestFirst. Examinar u los subconjuntos de atributos que se emiten. Qu atributos son seleccionados por ambos e mtodos? Cmo se relacionan con el resule o tado generado por el aumento de clasicacin o de informacin utiliza? o

To use the wrapper method rather than a lter method like CfsSubsetEval, you need to select WrapperSubsetEval. You can congure this by choosing a learning algorithm to apply. You can also set the number of folds for the cross-validation that is used to evaluate the model on each subset of attributes.

Ex. 9: On the same data, run CfsSubsetEval for correlation-based selection, using BestFirst search. Then run the wrapper method with J48 as the base learner, again using BestFirst search. Examine the attribute subsets that are output. Which attributes are selected by both methods? How do they relate to the output generated by ranking using information gain?

More on Automatic Attribute Selection


El panel de Select attribute nos permite profundizar en un conjunto de datos mediante la aplicacin de mtodos de seleccin de atributos de un o e o conjunto de datos. Sin embargo, utilizar esta informacin para reducir un conjunto de datos se o convierte en un problema si utilizamos algunos de los datos reducidos para probar el modelo (como en la validacin cruzada). o

The Select attribute panel allows us to gain insight into a dataset by applying attribute selection methods to a dataset. However, using this information to reduce a dataset becomes problematic if we use some of the reduced data for testing the model (as in cross-validation).

3 This 4 Este

is a standard search method from AI. es un mtodo de bsqueda estndar de la inuenza aviar. e u a

The reason is that, as with supervised discretization, we have actually looked at the class labels in the test data while selecting attributesthe best attributes were chosen by peeking at the test data. As we already know (see Tutorial 2), using the test data to inuence the construction of a model biases the accuracy estimates obtained: measured accuracy is likely to be greater than what will be obtained when the model is deployed on fresh data. To avoid this, we can manually divide the data into training and test sets and apply the attribute selection panel to the training set only.

La razn es que, al igual que con discretizacin suo o pervisado, que se han mirado en las etiquetas de clase en los datos de prueba, mientras que la seleccin de los atributosla mejor los atributos o fueron elegidos por espiar a los datos de prueba. Como ya sabemos (ver Tutorial 2), utilizando los datos de prueba para inuir en la construccin de o un modelo de los sesgos de la exactitud estimaciones obtenidas: La precisin de medida es probo able que sea mayor de lo que se obtiene cuando el modelo se implementa en nuevos datos. Para evitar esto, se puede dividir manualmente los datos en conjuntos de entrenamiento y de prueba y aplicar el comit de seleccin de atributos al conjunto de e o entrenamiento solamente. Un mtodo ms conveniente es utilizar el e a AttributeSelectedClassifer, uno de los metaclasicadores de WEKA. Esto nos permite especicar un mtodo de seleccin de atributos y un ale o goritmo de aprendizaje como parte de un esquema de clasicacin. El AttributeSelectedClassier o asegura que el conjunto seleccionado de atributos se selecciona basndose en los datos de entrea namiento solamente, a n de dar estimaciones insesgadas precisin. o Ahora ponemos a prueba los mtodos de see leccin de atributos diferentes probado anterioro mente en relacin con NaiveBayes. Bayesiano o asume (condicional) la independencia de los atributos, por lo que puede verse afectado si los atributos son redundantes, y la seleccin de atributos o puede ser muy util. Usted puede ver el efecto de los atributos redundantes en Bayes ingenuo mediante la adicin de o copias de un atributo existente a un conjunto de datos utilizando la clase de ltro sin supervisin o [Link] en el panel de Preprocess. Cada copia es, obviamente, una correlacin perfecta con el o original. Ex. 10: carga los datos de clasicacin de la diao betes [Link] y comenzar a agregar copias de la primera cualidad de los datos, medir el rendimiento de Bayes naive (con useSupervisedDiscretization encendido) con validacin cruzada despus de haber o e agregado cada copia. Qu observa? e Vamos ahora a comprobar si los tres mtodos e de seleccin de atributos de arriba, se utio liza junto con AttributeSelectedClassier y NaiveBayes, con xito eliminar los atributos ree dundantes. Los mtodos son: e

A more convenient method is to use the AttributeSelectedClassifer, one of WEKAs meta-classiers. This allows us to specify an attribute selection method and a learning algorithm as part of a classication scheme. The AttributeSelectedClassier ensures that the chosen set of attributes is selected based on the training data only, in order to give unbiased accuracy estimates.

Now we test the various attribute selection methods tested above in conjunction with NaiveBayes. Naive Bayes assumes (conditional) independence of attributes, so it can be aected if attributes are redundant, and attribute selection can be very helpful.

You can see the eect of redundant attributes on naive Bayes by adding copies of an existing attribute to a dataset using the unsupervised lter class [Link] in the Preprocess panel. Each copy is obviously perfectly correlated with the original.

Ex. 10: Load the diabetes classication data in [Link] and start adding copies of the rst attribute in the data, measuring the performance of naive Bayes (with useSupervisedDiscretization turned on) using cross-validation after you have added each copy. What do you observe? Let us now check whether the three attribute selection methods from above, used in conjunction with AttributeSelectedClassier and NaiveBayes, successfully eliminate the redundant attributes. The methods are:

InfoGainAttributeEval with Ranker (8 attributes)

InfoGainAttributeEval con Ranker (8 atributos)

CfsSubsetEval with BestFirst

CfsSubsetEval con BestFirst

WrapperSubsetEval with NaiveBayes and BestFirst. Run each method from within AttributeSelectedClassier to see the eect on cross-validated accuracy and check the attribute subset selected by each method. Note that you need to specify the number of ranked attributes to use for the Ranker method. Set this to eight, because the original diabetes data contains eight attributes (excluding the class). Note also that you should specify NaiveBayes as the classier to be used inside the wrapper method, because this is the classier that we want to select a subset for.

WrapperSubsetEval con NaiveBayes y BestFirst. Ejecutar cada mtodo dentro de AttributeSee lectedClassier para ver el efecto en la cruzvalidado la exactitud y vericar el subconjunto de atributos seleccionados por cada mtodo. Tenga e en cuenta que es necesario especicar el nmero u de atributos clasic a utilizar para el mtodo de o e Ranker. Ponga esto a ocho, porque los datos de la diabetes original contiene ocho atributos (con exclusin de la clase). Tenga en cuenta tambin o e que debe especicar NaiveBayes como el clasicador para ser utilizado en el mtodo de envoltura, e porque este es el clasicador que desea seleccionar un subconjunto de. Ex. 11: Qu puede decir respecto al rendimiento e de los tres mtodos de seleccin de atribue o tos? No tienen xito en la eliminacin de las e o copias redundantes? Si no, por qu no? e

Ex. 11: What can you say regarding the performance of the three attribute selection methods? Do they succeed in eliminating redundant copies? If not, why not?

Automatic parameter tuning


Muchos algoritmos de aprendizaje tienen parmetros que pueden afectar los resultados a del aprendizaje. Por ejemplo, el rbol de dea cisin C4.5 alumno (J48 en WEKA) tiene dos o parmetros que inuyen en la cantidad de la a poda que hace (hemos visto a uno, el nmero u m nimo de casos necesarios en una hoja, en el ultimo tutorial). El k -clasicador del vecino ms a prximo IBk tiene uno que establece el tamao de o n la vecindad. Pero manualmente modicando los ajustes de parmetros es tedioso, al igual que los a atributos seleccionar manualmente, y presenta el mismo problema: los datos de prueba no debe ser utilizado cuando los parmetros de seleccinlo a o contrario las estimaciones de rendimiento se har a con preferencia.

Many learning algorithms have parameters that can aect the outcome of learning. For example, the decision tree learner C4.5 (J48 in WEKA) has two parameters that inuence the amount of pruning that it does (we saw one, the minimum number of instances required in a leaf, in the last tutorial). The k-nearest-neighbor classier IBk has one that sets the neighborhood size. But manually tweaking parameter settings is tedious, just like manually selecting attributes, and presents the same problem: the test data must not be used when selecting parametersotherwise the performance estimates will be biased.

WEKA has a meta classier, CVParameterSelection, that automatically searches for the best parameter settings by optimizing cross-validated accuracy on the training data. By default, each setting is evaluated using 10-fold cross-validation. The parameters to optimize re specied using the CVParameters eld in the GenericObjectEditor. For each one, we need to give (a) a string that names it using its letter code, (b) a numeric range of values to evaluate, and (c) the number of steps to try in this range (Note that the parameter is assumed to be numeric.) Click on the More button in the GenericObjectEditor for more information, and an example.

WEKA tiene una meta clasicador, CVParameterSelection, que busca automticamente los mejores valores de los a parmetros mediante la optimizacin de cruza o validado la exactitud de los datos de entrenamiento. De forma predeterminada, cada ajuste se evalu utilizando 10 veces la validacin o o cruzada. Los parmetros para volver a optimizar a el uso especicado en el campo CVParameters GenericObjectEditor. Para cada uno de ellos, tenemos que dar (a) una cadena que le asigna el nombre utilizando su cdigo de letras, (b) una o serie de valores numricos para evaluar, y (c) el e nmero de medidas para tratar en este rango de u (Tenga en cuenta que el parmetro se supone que a es numrico.) Haga clic en el botn de More e o en la GenericObjectEditor para obtener ms a informacin, y un ejemplo. o Para los datos de la diabetes utilizados en la seccin anterior, el uso CVParameterSelection o IBk en conjunto con el n de seleccionar la mejor valor para el tamao de la vecindad, que n van desde 1 a 10 en diez pasos. El cdigo de leo tras para el tamao de esta zona: K. La precisin n o de validacin cruzada de la versin parmetro ao o a nado de IBk es directamente comparable con la precisin con la conguracin predeterminada, ya o o que ajuste se realiza mediante la aplicacin de ino terior validacin cruzada se ejecuta para encontrar o el mejor ajuste de parmetros para cada conjunto a de entrenamiento se producen en el exterior validacin cruzaday los rendimientos de este ultimo o la estimacin nal de ejecucin. o o Ex. 12: Qu precisin se obtiene en cada caso? e o Qu valor se selecciona para la versin e o parmetro anado sobre la base de la vala idacin cruzada en el conjunto de entreo namiento completo? (Nota: este valor es la produccin en el rea de texto Classier de o a salida.) Ahora considere ajuste de parmetros de J48. a Podemos utilizar CVParameterSelection para realizar una bsqueda de la rejilla en ambos u parmetros al mismo tiempo de poda mediante a la adicin de varias cadenas de parmetros en el o a campo CVParameters. El cdigo de letras para o el parmetro de la conanza de la poda es de C, a y usted debe evaluar los valores de 0,1 a 0,5 en cinco pasos. El cdigo de letras para el parmetro o a de hoja de tamao m n nimo es de M , y se deben evaluar los valores de 1 a 10 en diez pasos.

For the diabetes data used in the previous section, use CVParameterSelection in conjunction with IBk to select the best value for the neighborhood size, ranging from 1 to 10 in ten steps. The letter code for the neighborhood size is K. The cross-validated accuracy of the parameter-tuned version of IBk is directly comparable with its accuracy using default settings, because tuning is performed by applying inner cross-validation runs to nd the best parameter setting for each training set occuring in the outer cross-validationand the latter yields the nal performance estimate.

Ex. 12: What accuracy is obtained in each case? What value is selected for the parametertuned version based on cross-validation on the full training set? (Note: this value is output in the Classier output text area.)

Now consider parameter tuning for J48. We can use CVParameterSelection to perform a grid search on both pruning parameters simultaneously by adding multiple parameter strings in the CVParameters eld. The letter code for the pruning condence parameter is C, and you should evaluate values from 0.1 to 0.5 in ve steps. The letter code for the minimum leaf size parameter is M , and you should evaluate values from 1 to 10 in ten steps.

Ex. 13: Run CVParameterSelection to nd the best parameter values in the resulting grid. Compare the output you get to that obtained from J48 with default parameters. Has accuracy changed? What about tree size? What parameter values were selected by CVParameterSelection for the model built from the full training set?

Ex. 13: Ejecutar CVParameterSelection para encontrar los mejores valores de parmetros a en la red resultante. Comparar la salida se llega a la obtenida de J48 con los parmetros a por defecto. Tiene una precisin cambiado? o Qu pasa con el tamao del rbol? Qu vale n a e ores de los parmetros han sido seleccionados a por CVParameterSelection para el modelo construido a partir del conjunto de entrenamiento completo?

Practical Data Mining Tutorial 5: Document Classication

Eibe Frank and Ian H. Witten May 5, 2011


c 2008-2012 University of Waikato

Introduction
Clasicacin de texto es una aplicacin popular de o o aprendizaje automtico. Puede que incluso lo han a utilizado: los ltros de spam de correo electrnico o son los clasicadores que dividen a los mensajes de correo electrnico, que son documentos poco o menos, en dos grupos: basura y no deseado. Los llamados Bayesiano ltros de spam son entrenados en los mensajes que han sido etiquetados de forma manual, tal vez por su puesta en carpetas correspondientes (por ejemplo, jamn vs o spam). En este tutorial vamos a ver cmo llevar a cabo la o clasicacin de documentos usando herramientas o en WEKA. Los datos en bruto es de texto, pero la mayor de algoritmos de aprendizaje automtico a a esperar ejemplos que se describen mediante un conjunto jo de atributos. Por lo tanto, primero convertir los datos de texto en una forma adecuada para el aprendizaje. Esto suele hacerse mediante la creacin de un diccionario de trminos de todos o e los documentos en el corpus de entrenamiento y haciendo un atributo numrico de cada trmino. Ene e tonces, para un documento particular, el valor de cada atributo se basa en la frecuencia del trmino e correspondiente en el documento. tambin existe e el atributo de clase, lo que da la etiqueta del documento.

Text classication is a popular application of machine learning. You may even have used it: email spam lters are classiers that divide email messages, which are just short documents, into two groups: junk and not junk. So-called Bayesian spam lters are trained on messages that have been manually labeled, perhaps by putting them into appropriate folders (e.g. ham vs spam).

In this tutorial we look at how to perform document classication using tools in WEKA. The raw data is text, but most machine learning algorithms expect examples that are described by a xed set of attributes. Hence we rst convert the text data into a form suitable for learning. This is usually done by creating a dictionary of terms from all the documents in the training corpus and making a numeric attribute for each term. Then, for a particular document, the value of each attribute is based on the frequency of the corresponding term in the document. There is also the class attribute, which gives the documents label.

Data with string attributes


Atributo sin supervisin WEKA el ltro o StringToWordVector se puede utilizar para convertir el texto en bruto en los atributos plazo basado en la frecuencia. El ltro se supone que el texto de los documentos se almacena en un atributo de tipo String, que es un atributo nominal sin un conjunto previamente especicado de valores. En los datos ltrados, este atributo de cadena se sustituye por un conjunto jo de atributos numricos, y el atributo de la clase se e pone al principio, como el primer atributo. Para realizar la clasicacin de documentos, o primero tenemos que crear un archivo de ARFF con un atributo de cadena que contiene texto de los documentosdeclarado en el encabezado del archivo ARFF mediante @attribute document string, donde document es el nombre del atributo. tambin necesitamos e un atributo nominal que contiene la clasicacin o del documento.

WEKAs unsupervised attribute lter StringToWordVector can be used to convert raw text into term-frequency-based attributes. The lter assumes that the text of the documents is stored in an attribute of type String, which is a nominal attribute without a pre-specied set of values. In the ltered data, this string attribute is replaced by a xed set of numeric attributes, and the class attribute is put at the beginning, as the rst attribute.

To perform document classication, we rst need to create an ARFF le with a string attribute that holds the documents text declared in the header of the ARFF le using @attribute document string, where document is the name of the attribute. We also need a nominal attribute that holds the documents classication.

Document text The price of crude oil has increased signicantly Demand of crude oil outstrips supply Some people do not like the avor of olive oil The food was very oily Crude oil is in short supply Use a bit of cooking oil in the frying pan Table 1: Training documents. Document text Oil platforms extract crude oil Canola oil is supposed to be healthy Iraq has signicant oil reserves There are dierent types of cooking oil Table 2: Test documents.

Classication yes yes no no yes no

Classication Unknown Unknown Unknown Unknown

Ex. 1: To get a feeling for how this works, make an ARFF le from the labeled minidocuments in Table 1 and run StringToWordVector with default options on this data. How many attributes are generated? Now change the value of the option minTermFreq to 2. What attributes are generated now?

Ex. 1: Para tener una idea de cmo funciona o esto, hacer un archivo ARFF de la etiqueta mini documentos en la Table 1 y ejecutar StringToWordVector con las opciones predeterminadas en estos datos. Cmo se o generan muchos atributos? Ahora cambia el valor de la opcin de minTermFreq 2. o Quatributos se generan ahora? e

Ex. 2: Build a J48 decision tree from the last version of the data you generated. Give the tree in textual form. Usually, the purpose of a classier is to classify new documents. Lets classify the ones given in Table 2, based on the decision tree generated from the documents in Table 1. To apply the same lter to both training and test documents, we can use the FilteredClassier, specifying the StringToWordVector lter and the base classier that we want to apply (i.e., J48).

Ex. 2: Construir un rbol de decisin J48 de la a o ultima versin de los datos que generan. Dar o el rbol en forma textual. a Por lo general, el objetivo de un clasicador para clasicar los documentos nuevos. Vamos a clasicar a las dadas en la Table 2, basado en el rbol de a decisin de los documentos generados en la Table 1. o Para aplicar el mismo ltro a los dos documentos de entrenamiento y prueba, podemos usar el FilteredClassier, especicando el ltro StringToWordVector y el clasicador base que queremos aplicar (es decir, J48). Ex. 3: Crear un archivo de ARFF de la Table 2, con signos de interrogacin para las etiqueo tas de clase perdido. Congurar el FilteredClassier utilizando las opciones predeterminadas para StringToWordVector y J48, y especicar el archivo ARFF nuevo el equipo de prueba. Asegrese de que selecu ciona Output predictions en More options... Classify en el panel. Mira el modelo y las predicciones que genera, y vericar que sean compatibles. Cules son las predica ciones (en el orden en que los documentos son enumerados en la Table 2)?

Ex. 3: Create an ARFF le from Table 2, using question marks for the missing class labels. Congure the FilteredClassier using default options for StringToWordVector and J48, and specify your new ARFF le as the test set. Make sure that you select Output predictions under More options... in the Classify panel. Look at the model and the predictions it generates, and verify that they are consistent. What are the predictions (in the order in which the documents are listed in Table 2)?

Classifying actual short text documents


No es una coleccin estndar de los art o a culos agencia de noticias que es ampliamente utilizado para la evaluacin de los clasicadores o de documentos. [Link] y [Link] son conjuntos de datos de aprendizaje derivados de esta coleccin; o [Link] y [Link] son correspondientes unidades de prueba. Los documentos reales en los datos de ma y el grano son las mismas, z slo las etiquetas son diferentes. En el primer o conjunto de datos, art culos que hablan de temas relacionados con el ma tiene un valor de la clase z de 1 y el resto a 0, el objetivo es construir un clasicador que se puede utilizar para identicar los art culos que hablan de ma En el segundo, z. el etiquetado similar se realiza con respecto a cuestiones relacionadas con granos, y el objetivo es identicar estos art culos en el equipo de prueba. Ex. 4: Construir clasicadores de documentos para los dos conjuntos de formacin medio ante la aplicacin de la FilteredClassier o StringToWordVector con el uso (a) J48 y (b) NaiveBayesMultinomial, en cada caso a la evaluacin en el sistema de la prueba o correspondiente. Qu porcentaje de clasie caciones correctas se obtiene en los cuatro escenarios? Con base en sus resultados, que clasicador elegir as? El porcentaje de clasicaciones correctas no es la mtrica de evaluacin utilizado para la clasicacin e o o de documentos. WEKA incluye varias otras estad sticas de evaluacin por cada clase que se utio lizan con frecuencia para evaluar los sistemas de recuperacin de informacin como los motores de o o bsqueda. Estos son tabulados en Detailed Acu curacy By Class en el rea de texto Classier a output. Se basan en el nmero de verdaderos posu itivos (VP), el nmero de falsos positivos (FP), el u nmero de verdaderos negativos (VN), y el nmero u u de falsos negativos (FN) en los datos de prueba. A positivos true es un ejemplo de prueba que est a clasicado correctamente como pertenecientes a la clase de destino en cuestin, mientras que un falo sos positivos es un ejemplo (negativo) que est mal a asignado a la clase de destino. FN y TN se dene de manera similar. La salida de las estad sticas por WEKA se calculan de la siguiente manera: TP Precio: TP / (TP + FN)

There is a standard collection of newswire articles that is widely used for evaluating document classiers. [Link] and [Link] are sets of training data derived from this collection; [Link] and [Link] are corresponding test sets. The actual documents in the corn and grain data are the same; just the labels dier. In the rst dataset, articles that talk about corn-related issues have a class value of 1 and the others have 0; the aim is to build a classier that can be used to identify articles that talk about corn. In the second, the analogous labeling is performed with respect to grain-related issues, and the aim is to identify these articles in the test set.

Ex. 4: Build document classiers for the two training sets by applying the FilteredClassier with StringToWordVector using (a) J48 and (b) NaiveBayesMultinomial, in each case evaluating them on the corresponding test set. What percentage of correct classications is obtained in the four scenarios? Based on your results, which classier would you choose?

The percentage of correct classications is not the only evaluation metric used for document classication. WEKA includes several other per-class evaluation statistics that are often used to evaluate information retrieval systems like search engines. These are tabulated under Detailed Accuracy By Class in the Classier output text area. They are based on the number of true positives (TP), number of false positives (FP), number of true negatives (TN), and number of false negatives (FN) in the test data. A true positive is a test instance that is classied correctly as belonging to the target class concerned, while a false positive is a (negative) instance that is incorrectly assigned to the target class. FN and TN are dened analogously. The statistics output by WEKA are computed as follows:

TP Rate: TP / (TP + FN)

FP Rate: FP / (FP + TN)

FP Precio: FP / (FP + TN)

Precision: TP / (TP + FP)

Precisin: TP / (TP + FP) o

Recall: TP / (TP + FN)

Recuperacin: TP / (TP + FN) o

F-Measure: the harmonic mean of precision and recall (2/F = 1/precision + 1/recall).

F-Medida: la media armnica de precisin y o o recuperacin o (2/F = 1/precisin +1/recuperacin). o o

Ex. 5: Based on the formulas, what are the best possible values for each of the statistics in this list? Describe in English when these values are attained. The Classier Output table also gives the ROC area, which diers from the other statistics because it is based on ranking the examples in the test data according to how likely they are to belong to the positive class. The likelihood is given by the class probability that the classier predicts. (Most classiers in WEKA can produce probabilities in addition to actual classications.) The ROC area (which is also known as AUC) is the probability that a randomly chosen positive instance in the test data is ranked above a randomly chosen negative instance, based on the ranking produced by the classier.

Ex. 5: Con base en las frmulas, Cules son los o a mejores valores posibles para cada una de las estad sticas en esta lista? Describa en Ingls e cuando estos valores se alcanzan. En la tabla Classier Output tambin da la e ROC area, que diere de las estad sticas de otros porque se basa en el ranking de los ejemplos de los datos de prueba de acuerdo a la probabilidad que existe de pertenecer a la positivo clase. La posibilidad est dada por la probabilidad de clase a que el clasicador predice. (La mayor de los a clasicadores en WEKA pueden producir probabilidades, adems de las clasicaciones actuales.) a La zona de la Repblica de China (que tambin u e se conoce como AUC) es la probabilidad de que un ejemplo elegido al azar positivo en los datos de prueba se clasica por encima de un ejemplo elegido al azar negativas, sobre la base de la clasicacin producido por el clasicador. o El mejor resultado es que todos los ejemplos positivos se sita por encima de todos los ejemplos u negativos. En ese caso las AUC es uno. En el peor de los casos es cero. En el caso de que la clasicacin es esencialmente al azar, las AUC es de o 0,5. Por lo tanto queremos una AUC, que es al menos 0,5, de lo contrario nuestro clasicador no ha aprendido nada de los datos de entrenamiento. Ex. 6: Cul de los dos clasicadores utilizados a anterior produce los mejores AUC para los dos conjuntos de datos de Reuters? Compare esto con los resultados de porcentaje de respuestas correctas. Qusignican los difere entes resultados?

The best outcome is that all positive examples are ranked above all negative examples. In that case the AUC is one. In the worst case it is zero. In the case where the ranking is essentially random, the AUC is 0.5. Hence we want an AUC that is at least 0.5, otherwise our classier has not learned anything from the training data.

Ex. 6: Which of the two classiers used above produces the best AUC for the two Reuters datasets? Compare this to the outcome for percent correct. What do the dierent outcomes mean?

Ex. 7: Interpret in your own words the dierence between the confusion matrices for the two classiers. There is a close relationship between ROC Area and the ratio TP Rate/FP Rate. Rather than just obtaining a single pair of values for the true and false positive rates, a whole range of value pairs can be obtained by imposing dierent classication thresholds on the probabilities predicted by the classier. By default, an instance is classied as positive if the predicted probability for the positive class is greater than 0.5; otherwise it is classied as negative. (This is because an instance is more likely to be positive than negative if the predicted probability for the positive class is greater than 0.5.) Suppose we change this threshold from 0.5 to some other value between 0 and 1, and recompute the ratio TP Rate/FP Rate. Repeating this with different thresholds produces what is called an ROC curve. You can show it in WEKA by right-clicking on an entry in the result list and selecting Visualize threshold curve.

Ex. 7: Interpretar en sus propias palabras la diferencia entre las matrices de confusin o para los dos clasicadores. Existe una relacin estrecha entre ROC Area y la o relacin de TP Rate/FP Rate. En lugar de simo plemente obtener un solo par de valores para las tasas de positivos verdaderos y falsos, toda una serie de pares de valores se puede obtener mediante la imposicin de diferentes umbrales de clasicacin o o de las probabilidades predichas por el clasicador. De forma predeterminada, una instancia se clasica como positivo si la probabilidad predicha para la clase positivo es superior a 0,5, de lo contrario se clasica como negativa. (Esto se debe a un caso es ms probable que sea positivo que a negativo si la probabilidad predicha para la clase positivo es superior a 0.5.) Supongamos que el cambio de este umbral de 0,5 a algn otro valor u entre 0 y 1, y volver a calcular la proporcin de o TP Rate/FP Rate. Repetir esto con diferentes umbrales produce lo que se llama ROC curve. Se puede mostrar en WEKA haciendo clic derecho sobre una entrada en la lista de resultados y la seleccin de Visualize threshold curve. o Al hacer esto, se obtiene una parcela con FP Rate en el eje x y TP Rate en el y eje. En funcin del o clasicador que usa, esta parcela puede ser muy suave, o puede ser bastante discretos. Lo interesante es que si se conecta los puntos de muestra en el grco por las l a neas, y calcular el rea bajo la a curva resultante, se obtiene el ROC Area discutido arriba! Ah es donde la AUC acrnimo de la Area de la ROC viene de: Area bajo la curva. Ex. 8: Para el conjunto de datos producidos a Reuters que la diferencia ms extrema en el a ejercicio 6 anterior, visita las curvas ROC para la clase 1. Hacer una estimacin muy o aproximada del rea debajo de cada curva, y a explicarlo con palabras.

When you do this, you get a plot with FP Rate on the x axis and TP Rate on the y axis. Depending on the classier you use, this plot can be quite smooth, or it can be fairly discrete. The interesting thing is that if you connect the dots shown in the plot by lines, and you compute the area under the resulting curve, you get the ROC Area discussed above! That is where the acronym AUC for the ROC Area comes from: Area Under the Curve. Ex. 8: For the Reuters dataset that produced the most extreme dierence in Exercise 6 above, look at the ROC curves for class 1. Make a very rough estimate of the area under each curve, and explain it in words.

Ex. 9: What does the ideal ROC curve corresponding to perfect performance look like (a rough sketch, or a description in words, is sucient)?

Ex. 9: Quhace el ideal de la curva ROC corree spondiente a buscar un rendimiento perfecto como (un boceto o una descripcin verbal, es o suciente)?

Using the threshold curve GUI, you can also plot other types of curves, e.g. a precision/recall curve, with Recall on the x axis and Precision on the y axis. This plots precision against recall for each probability threshold evaluated.

Utilizando la curva de umbral de interfaz grca a de usuario, tambin puede trazar otros tipos de e curvas, por ejemplo, una precisin/recuperacin o o curva, con Recall en el eje x y Precision en el y eje. Este grco de precisin contra el recuerdo a o de cada umbral de probabilidad evaluada. Ex. 10: Cambiar los ejes para obtener una precisin/recuperacin curva. Quforma tiene o o e la ideal precisin/recuperacin curva que o o corresponde a un rendimiento perfecto que (de nuevo un croquis o descripcin verbal es o suciente)?

Ex. 10: Change the axes to obtain a precision/recall curve. What shape does the ideal precision/recall curve corresponding to perfect performance have (again a rough sketch or verbal description is sucient)?

Exploring the StringToWordVector lter


De forma predeterminada, el ltro de StringToWordVector, simplemente hace que el valor del atributo en el conjunto de datos transformados 1 o 0 para todos los trminos primas de una e sola palabra, dependiendo de si la palabra aparece en el documento o no. Sin embargo, hay muchas opciones que se pueden cambiar, por ejemplo: outputWordCounts causas palabra real cuenta de la salida.

By default, the StringToWordVector lter simply makes the attribute value in the transformed dataset 1 or 0 for all raw single-word terms, depending on whether the word appears in the document or not. However, there are many options that can be changed, e.g:

outputWordCounts causes actual word counts to be output.

IDFTransform and TFTransform: when both are set to true, term frequencies are transformed into so-called T F IDF values that are popular for representing documents in information retrieval applications.

IDFTransform y TFTransform: cuando ambos se ponen a true, las frecuencias plazo se transforman en los llamados T F F DI valores que son populares para la representacin de documentos en aplicaciones de o recuperacin de informacin. o o

stemmer allows you to choose from dierent word stemming algorithms that attempt to reduce words to their stems.

stemmer le permite elegir entre diferentes palabras derivadas algoritmos que tratan de reducir las palabras a sus tallos.

useStopList allows you determine whether or not stop words are deleted. Stop words are uninformative common words (e.g. a, the).

useStopList le permite determinar si se detiene se suprimirn las palabras. Las pala abras vac son poco informativos palabras as comunes (por ejemplo, a, la).

tokenizer allows you to choose a dierent tokenizer for generating terms, e.g. one that produces word n-grams instead of single words.

tokenizer le permite elegir un analizador de trminos diferentes para generar, por ejeme plo, que produce la palabra n-gramos en lugar de palabras sueltas.

There are several other useful options. For more information, click on More in the GenericObjectEditor. Ex. 11: Experiment with the options that are available. What options give you a good AUC value for the two datasets above, using NaiveBayesMultinomial as the classier? (Note: an exhaustive search is not required.)

Hay varias opciones utiles. Para obtener ms in a formacin, haga clic en More en la GenericObo jectEditor. Ex. 11: Experimento con las opciones que estn a disponibles. Quopciones le dan un buen e valor de AUC para los dos conjuntos de datos anterior, con NaiveBayesMultinomial en el clasicador? (Nota: una bsqueda exhausu tiva no es necesario.) A menudo, no todos los atributos (es decir, trminos) son importantes para la clasicacin e o de documentos, ya que muchas palabras pueden ser irrelevantes para determinar el tema de un art culo. Podemos utilizar AttributeSelectedClassier WEKA, utilizando ranking con InfoGainAttributeEval Ranker y la bsqueda, para u tratar de eliminar los atributos que no son tan utiles. Al igual que antes tenemos que utilizar el FilteredClassier para transformar los datos antes de que se pasa al AttributeSelectedClassier. Ex. 12: Experimento con esta puesta en marcha, utilizando las opciones predeterminadas para StringToWordVector y NaiveBayesMultinomial en el clasicador. Variar el nmero de los atributos ms informativo u a que se seleccionan de la clasicacin de o informacin de ganancia basado en cambiar o el valor del campo en el numToSelect Ranker. Registre los valores del AUC de obtener. Qunmero de atributos que ofrece e u la mejor AUC para los dos conjuntos de datos anteriores? Quvalores AUC son los e mejores que logran obtener? (De nuevo, una bsqueda exhaustiva no es necesario.) u

Often, not all attributes (i.e., terms) are important when classifying documents, because many words may be irrelevant for determining the topic of an article. We can use WEKAs AttributeSelectedClassier, using ranking with InfoGainAttributeEval and the Ranker search, to try and eliminate attributes that are not so useful. As before we need to use the FilteredClassier to transform the data before it is passed to the AttributeSelectedClassier.

Ex. 12: Experiment with this set-up, using default options for StringToWordVector and NaiveBayesMultinomial as the classier. Vary the number of most-informative attributes that are selected from the infogain-based ranking by changing the value of the numToSelect eld in the Ranker. Record the AUC values you obtain. What number of attributes gives you the best AUC for the two datasets above? What AUC values are the best you manage to obtain? (Again, an exhaustive search is not required.)

Practical Data Mining Tutorial 6: Mining Association Rules

Eibe Frank and Ian H. Witten May 5, 2011


c 2008-2012 University of Waikato

Introduction
La miner de reglas de asociacin es una de las a o tcnicas de miner de datos ms destacados. En e a a este tutorial, vamos a trabajar con Apriorila regla de asociacin algoritmo de miner de datos o a que lo empez todo. Como se ver, no es fcil de o a a extraer informacin util con la miner de reglas o a de asociacin. o

Association rule mining is one of the most prominent data mining techniques. In this tutorial, we will work with Apriorithe association rule mining algorithm that started it all. As you will see, it is not straightforward to extract useful information using association rule mining.

Association rule mining in WEKA


En Explorer WEKA, tcnicas para la extraccin e o de reglas de asociacin se accede mediante el panel o de Associate. Debido a que esta es una tcnica de e miner de datos puramente exploratoria, no hay a opciones de evaluacin, y la estructura del panel o es simple. El mtodo predeterminado es Apriori, e que utilizamos en este tutorial. WEKA contiene un par de otras tcnicas para el aprendizaje de las e asociaciones de los datos, pero son probablemente ms interesante para los investigadores de los proa fesionales. Para tener una idea de cmo aplicar Apriori, o empezamos por las normas de la miner de la a [Link] datos que se utiliz en el o Tutorial 1. Tenga en cuenta que este algoritmo espera de datos que es puramente nominal: los atributos numricos deben ser discretos en primer lugar. e Despus de cargar los datos en el panel de Preproe cess, pulsa el botn Start en el panel de Assoo ciate para ejecutar Apriori con las opciones predeterminadas. Hace salir diez reglas, ordenadas de acuerdo a la medida de conanza entre parntesis e despus de cada uno. El nmero siguiente ane u tecedente de una regla se muestra cmo muchos o casos cumplen el antecedente, el nmero despus u e de la conclusin muestra cuntas instancias satiso a facer toda la regla (esta es la regla de apoyo). Debido a que ambos nmeros son iguales para tou das las diez reglas, la conanza de cada regla es exactamente uno.

In WEKAs Explorer, techniques for association rule mining are accessed using the Associate panel. Because this is a purely exploratory data mining technique, there are no evaluation options, and the structure of the panel is simple. The default method is Apriori, which we use in this tutorial. WEKA contains a couple of other techniques for learning associations from data, but they are probably more interesting to researchers than practitioners.

To get a feel for how to apply Apriori, we start by mining rules from the [Link] data that we used in Tutorial 1. Note that this algorithm expects data that is purely nominal: numeric attributes must be discretized rst. After loading the data in the Preprocess panel, hit the Start button in the Associate panel to run Apriori with default options. It outputs ten rules, ranked according to the condence measure given in parentheses after each one. The number following a rules antecedent shows how many instances satisfy the antecedent; the number following the conclusion shows how many instances satisfy the entire rule (this is the rules support). Because both numbers are equal for all ten rules, the condence of every rule is exactly one.

In practice, it is tedious to nd minimum support and condence values that give satisfactory results. Consequently WEKAs Apriori runs the basic algorithm several times. It uses same userspecied minimum condence value throughout, given by the minMetric parameter. The support level is expressed as a proportion of the total number of instances (14 in the case of the weather data), as a ratio between 0 and 1. The minimum support level starts at a certain value (upperBoundMinSupport, which should invariably be left at 1.0 to include the entire set of instances). In each iteration the support is decreased by a xed amount (delta, default 0.05, 5% of the instances) until either a certain number of rules has been generated (numRules, default 10 rules) or the support reaches a certain minimum minimum level (lowerBoundMinSupport, default 0.1typically rules are uninteresting if they apply to only 10% of the dataset or less). These four values can all be specied by the user.

En la prctica, es tedioso para encontrar un apoyo a m nimo y los valores de la conanza que dan resultados satisfactorios. En consecuencia WEKAs Apriori corre el algoritmo bsico en varias ocaa siones. Utiliza el mismo valor m nimo especicado por el usuario a travs de la conanza, dado por e el parmetro minMetric. El nivel de soporte se a expresa como un porcentaje del nmero total de u casos (14 en el caso de los datos meteorolgicos), o como una relacin entre 0 y 1. El nivel m o nimo de apoyo se inicia en un determinado valor (upperBoundMinSupport, que invariablemente se debe dejar en 1.0 para incluir todo el conjunto de casos). En cada iteracin el apoyo se reduce o en una cantidad ja (delta, por defecto 0.05, 5% de los casos) hasta que un cierto nmero de reu glas se ha generado (numRules, por defecto 10 normas) o el apoyo llega a un cierto m nimo m nimo nivel (lowerBoundMinSupport, por defecto 0.1normalmente reglas son poco interesantes si se aplican a slo el 10% del conjunto de o datos o menos). Estos cuatro valores pueden ser especicados por el usuario. Esto suena bastante complicado, as que vamos a examinar lo que sucede en los datos meteorolgicos. Desde la salida en el rea de texto o a Associator output, vemos que el algoritmo de gestin para generar diez reglas. Esto se basa en o un nivel de conanza m nimo de 0.9, que es el predeterminado, y tambin se muestra en la salida. e El Number of cycles performed, que se muestra como 17, nos dice que Apriori era en realidad ejecuta 17 veces para generar estas normas, con 17 valores diferentes de la ayuda m nima. El coste nal, que corresponde a la salida que se ha generado, es de 0,15 (que corresponde a 0.15 14 2 instances). Al mirar las opciones de la GenericObjectEditor, podemos ver que el valor inicial de la ayuda m nima (upperBoundMinSupport) es 1 por defecto, y que delta es de 0,05. Ahora, 1170.05 = 0, 15, as que esto explica por qu un valor m e nimo de apoyo de 0,15 que se lleg despus de 17 iterao e ciones. Tenga en cuenta que upperBoundMinSupport delta es disminuido por antes de la base Apriori algoritmo se ejecuta por primera vez.

This sounds pretty complicated, so let us examine what happens on the weather data. From the output in the Associator output text area, we see that the algorithm managed to generate ten rules. This is based on a minimum condence level of 0.9, which is the default, and is also shown in the output. The Number of cycles performed, which is shown as 17, tells us that Apriori was actually run 17 times to generate these rules, with 17 different values for the minimum support. The nal value, which corresponds to the output that was generated, is 0.15 (corresponding to 0.15 14 2 instances).

By looking at the options in the GenericObjectEditor, we can see that the initial value for the minimum support (upperBoundMinSupport) is 1 by default, and that delta is 0.05. Now, 1 17 0.05 = 0.15, so this explains why a minimum support value of 0.15 is reached after 17 iterations. Note that upperBoundMinSupport is decreased by delta before the basic Apriori algorithm is run for the rst time.

Minimum condence 0.9 0.9 0.9 0.8 0.8 0.8 0.7 0.7 0.7

Minimum support 0.3 0.2 0.1 0.3 0.2 0.1 0.3 0.2 0.1

Number of rules

Table 1: Total number of rules for dierent values of minimum condence and support The Associator output text area also shows the number of frequent item sets that were found, based on the last value of the minimum support that was tried (i.e. 0.15 in this example). We can see that, given a minimum support of two instances, there are 12 item sets of size one, 47 item sets of size two, 39 item sets of size three, and 6 item sets of size four. By setting outputItemSets to true before running the algorithm, all those different item sets and the number of instances that support them are shown. Try this. El rea de texto Associator output tambin a e muestra el nmero de conjuntos de u tems frecuentes que se encontraron, con base en el ultimo valor de la ayuda m nima que fue juzgado (es decir, 0.15 en este ejemplo). Podemos ver que, dado un apoyo m nimo de dos casos, hay 12 conjuntos de punto del tamao de una, 47 conjuntos de n punto del tamao de dos, 39 conjuntos de punto n del tamao de tres, y seis conjuntos de punto del n tamao de cuatro. Al establecer outputItemSets n a true antes de ejecutar el algoritmo, todos los conjuntos de tems diferentes y el nmero de casos u que los apoyan se muestran. Pruebe esto. Ex. 1: Sobre la base de la salida, lo que es el soporte del tema conjunto perspectivas=lluvias humedad=normal ventoso=FALSO jugar=s` ?

Ex. 1: Based on the output, what is the support of the item set outlook=rainy humidity=normal windy=FALSE play=yes?

Ex. 2: Suppose we want to generate all rules with a certain condence and minimum support. This can be done by choosing appropriate values for minMetric, lowerBoundMinSupport, and numRules. What is the total number of possible rules for the weather data for each combination of values in Table 1?

Ex. 2: Supongamos que desea generar todas las reglas con cierta conanza y el apoyo m nimo. Esto se puede hacer eligiendo valores adecuados para minMetric, lowerBoundMinSupport, y numRules. Cul a es el nmero total de posibles reglas para los u datos del tiempo para cada combinacin de o valores de la Table 1?

Apriori has some further parameters. If significanceLevel is set to a value between zero and one, the association rules are ltered based on a 2 test with the chosen signicance level. However, applying a signicance test in this context is problematic because of the so-called multiple comparison problem: if we perform a test hundreds of times for hundreds of association rules, it is likely that a signicant eect will be found just by chance (i.e., an association seems to be statistically signicant when really it is not). Also, the 2 test is inaccurate for small sample sizes (in this context, small support values).

Apriori tiene algunos parmetros ms. Si signifa a icanceLevel se establece en un valor entre cero y uno, las reglas de asociacin se ltran sobre la o base de un 2 la prueba con el nivel de signicacin o elegido. Sin embargo, la aplicacin de una prueba o de signicacin en este contexto es problemtico o a debido a los llamados problemas de comparacin o mltiple: si realizamos una prueba cientos de veu ces por cientos de reglas de asociacin, es probable o que un efecto signicativo se encuentran slo por o casualidad (es decir, una asociacin parece ser eso tad sticamente signicativa, cuando en realidad no lo es). Adems, el 2 la prueba es inexacto para a pequeos tamaos de muestra (en este contexto, n n los valores de apoyar a los pequeos). n Hay medidas alternativas para las reglas de clasicacin. Adems de Condence, Apriori Lift o a apoya, Leverage y Conviction. Estos pueden ser seleccionados con metricType. Ms informacin a o est disponible haciendo clic More en el Generia cObjectEditor. Ex. 3: Ejecutar Apriori en la informacin del o tiempo con cada uno de los cuatro indicadores regla de clasicacin, y la conguo racin por defecto de otra manera. Cul es o a la primera regla de clasicacin que se emite o para cada mtrica? e

There are alternative measures for ranking rules. As well as Condence, Apriori supports Lift, Leverage, and Conviction. These can be selected using metricType. More information is available by clicking More in the GenericObjectEditor. Ex. 3: Run Apriori on the weather data with each of the four rule ranking metrics, and default settings otherwise. What is the topranked rule that is output for each metric?

Mining a real-world dataset


Consideremos ahora un conjunto de datos del mundo real, [Link], lo que da los votos de 435 congresistas [Link]. el 16 de cuestiones clave se reunieron a mediados de los aos 80, y tambin inn e cluye su aliacin a un partido como un atributo o binario. Se trata de un conjunto de datos puramente nominal con algunos valores que faltan (de hecho, abstenciones). Normalmente se trata como un problema de clasicacin, la tarea que para preo decir aliacin a un partido basado en los patrones o de voto. Sin embargo, tambin podemos aplicar e la miner de reglas de asociacin a estos datos y a o buscar asociaciones interesantes. Ms informacin a o sobre los datos aparecen en los comentarios en el archivo ARFF. Ex. 4: Ejecutar Apriori en estos datos con la conguracin predeterminada. Opina sobre o las reglas que se generan. Varios de ellos son bastante similares. Cmo son su apoyo o y conanza de los valores asociados?

Now consider a real-world dataset, [Link], which gives the votes of 435 U.S. congressmen on 16 key issues gathered in the mid-80s, and also includes their party aliation as a binary attribute. This is a purely nominal dataset with some missing values (actually, abstentions). It is normally treated as a classication problem, the task being to predict party aliation based on voting patterns. However, we can also apply association rule mining to this data and seek interesting associations. More information on the data appears in the comments in the ARFF le.

Ex. 4: Run Apriori on this data with default settings. Comment on the rules that are generated. Several of them are quite similar. How are their support and condence values related?

Ex. 5: It is interesting to see that none of the rules in the default output involve Class=republican. Why do you think that is?

Ex. 5: Es interesante ver que ninguna de las reglas en la salida predeterminada implican Clase=republicana. Por qu crees que es? e

Market basket analysis


Una aplicacin popular de la miner de reglas o a de asociacin es el anlisis de la cestaanalizar o a los hbitos de compra de los clientes mediante a la bsqueda de asociaciones en los productos que u compran al visitar una tienda. Para hacer anlisis a de la cesta de WEKA, cada transaccin se codio ca como una instancia cuyos atributos representan los art culos de la tienda. Cada atributo tiene un unico valor: si una transaccin en particular o no lo contiene (es decir, el cliente no comprar ese art culo en particular), esto se codica como un valor que falta. Su trabajo consiste en extraer datos supermercado para las asociaciones. Los datos de [Link] se obtuvo de un verdadero supermercado de Nueva Zelanda. Echa un vistazo a este archivo utilizando un editor de texto para comprobar que entender la estructura. El punto principal de este ejercicio es mostrar lo dif que cil es encontrar cualquier patrones interesantes en este tipo de datos! Ex. 6: Experimente con Apriori e investigar el efecto de la diversos parmetros discutidos anteriormente. Escriba un breve informe en su investigacin y las conclusiones principales.

A popular application of association rule mining is market basket analysisanalyzing customer purchasing habits by seeking associations in the items they buy when visiting a store. To do market basket analysis in WEKA, each transaction is coded as an instance whose attributes represent the items in the store. Each attribute has only one value: if a particular transaction does not contain it (i.e., the customer did not buy that particular item), this is coded as a missing value.

Your job is to mine supermarket checkout data for associations. The data in [Link] was collected from an actual New Zealand supermarket. Take a look at this le using a text editor to verify that you understand the structure. The main point of this exercise is to show you how difcult it is to nd any interesting patterns in this type of data!

Ex. 6: Experiment with Apriori and investigate the eect of the various parameters discussed above. Write a brief report on your investigation and the main ndings.

También podría gustarte