MetaTrader 5 - Trading Machine Learning: come Support Vector Machines può essere utilizzato in Trading Che cosa è una macchina Support Vector Una macchina supporto vettore è un metodo di apprendimento automatico che cerca di prendere i dati di ingresso e di classificarli in una delle due categorie. Affinché un Macchine a vettori di supporto per essere efficace, è necessario utilizzare prima un set di dati di ingresso e di uscita di formazione per costruire il modello di macchina supporto vettore che può essere utilizzato per classificare i nuovi dati. Una macchina Support Vector sviluppa questo modello prendendo ingressi formazione, associandole nello spazio multidimensionale, quindi utilizzando la regressione di trovare un iperpiano (un iperpiano è una superficie nello spazio n-dimensionale che separa lo spazio in due spazi mezzo) che meglio separa le due classi di ingressi. Una volta che la macchina supporto vettore è stato preparato, è in grado di valutare nuovi ingressi rispetto al iperpiano separa e classificare in una delle due categorie. Una macchina di supporto vettore è essenzialmente una macchina InputOutput. Un utente è in grado di mettere in un ingresso, e sulla base del modello sviluppato attraverso la formazione, restituirà un output. Il numero di ingressi per un dato Macchine a vettori di supporto varia teoricamente da uno all'infinito, ma in termini pratici potenza di calcolo fa limite come possono essere utilizzati molti input. Se, per esempio, N ingressi sono utilizzati per una macchina vettoriale particolare supporto (il valore intero di N può variare da uno a infinito), la macchina di supporto vettore deve mappare ciascuna serie di ingressi nello spazio N-dimensionale e trovare una (N-1 ) iperpiano dimensionale che meglio si separa i dati di allenamento. Figura 1. Support Vector Machines sono InputOutput macchine Il modo migliore per concettualizzare come funziona una macchina Support Vector è prendendo in considerazione i due casi dimensionale. Supponiamo vogliamo creare una macchina vettoriale supporto che ha due ingressi e restituisce una singola uscita che classifica il punto dati come appartenente ad una delle due categorie. Possiamo visualizzare questo tracciando su un grafico a 2 dimensioni, come la tabella qui sotto. Figura 2. Sinistra: Supporto ingressi Vector Machine mappati a un grafico 2D. I cerchi rossi e croci blu sono utilizzati per indicare le due classi di ingressi. Figura 3. A destra: Supporto ingressi Vector Machine mappati a un grafico 2D. I cerchi rossi e croci blu sono utilizzati per indicare le due classi di ingressi con una linea nera indica l'iperpiano di separazione. In questo esempio, le croci blu indicano i punti di dati che appartengono alla categoria 1 ei cerchi rossi che rappresentano i punti di dati che appartengono alla categoria 2. Ciascuno dei singoli punti dati ha un particolare valore di ingresso 1 (rappresentata dalla loro posizione sulla ascisse ) e un unico valore di ingresso 2 (rappresentato dal loro posizione sul asse y) e tutti questi punti sono stati mappati allo spazio 2-dimensionale. Una macchina supporto vettore è in grado di classificare i dati creando un modello di questi punti in 2 spazio tridimensionale. La macchina Support Vector osserva i dati in 2 spazio tridimensionale, e utilizza un algoritmo di regressione per trovare un 1 iperpiano dimensionale (linea aka) che separano la maggior precisione i dati nei suoi due categorie. Questa linea di separazione viene quindi utilizzato dalla macchina vettore supporto per classificare i nuovi punti di dati in uno di categoria 1 o 2. L'animazione seguente illustra il processo di formazione di una nuova macchina Support Vector. L'algoritmo inizia facendo una supposizione casuale trovare un iperpiano separatore, quindi iterativamente migliorare la precisione della iperpiano. Come si può vedere l'algoritmo inizia abbastanza aggressivo, ma poi rallenta come si comincia ad avvicinarsi alla soluzione desideri. Figura 4. Un'animazione che mostra una formazione di supporto Vector Machine. L'iperpiano converge progressivamente sulla geometria ideale per separare le due classi di dati Lo scenario 2-dimensional presentato sopra ci permette di visualizzare il processo di una macchina di supporto vettoriale, tuttavia è solo in grado di classificare un punto dati utilizzando due ingressi. E se vogliamo usare più ingressi Per fortuna, l'algoritmo di Vector Machine sostegno ci permette di fare lo stesso in dimensioni superiori, anche se lo fa diventare molto più difficile da concettualizzare. Considerate questo, si desidera creare Vector Machine supporto che prende 20 ingressi e può classificare qualsiasi punto dati utilizzando questi ingressi in nessuna delle due di categoria 1 o 2. Per fare questo, la macchina Support Vector ha bisogno di modellare i dati in 20 spazio tridimensionale e utilizzare un algoritmo di regressione per trovare un iperpiano dimensionale 19 che separa i punti di dati in due categorie. Questo diventa estremamente difficile da visualizzare come è difficile per noi comprendere qualsiasi cosa sopra 3-dimensioni, ma tutto quello che dovete sapere è che è funziona esattamente allo stesso modo in cui avviene per il caso 2-dimensionale. Come Support Vector Machines lavoro Esempio: è un Schnick Immaginate questo scenario ipotetico, si è un ricercatore indaga su un animale raro si trova solo nelle profondità dell'Artico chiamati Shnicks. Data la lontananza di questi animali, solo una piccola manciata sono mai stati trovati (diciamo intorno al 5000). Come ricercatore, si è bloccato con la domanda. come posso identificare un Schnick Tutto quello che avete a vostra disposizione sono i documenti di ricerca pubblicati in precedenza da parte del gruppo di ricercatori che hanno visto uno. In questi documenti di ricerca, gli autori descrivono alcune caratteristiche relative ai Schnicks hanno trovato, cioè altezza, peso, numero di gambe, ecc ma tutte queste caratteristiche variano tra i lavori di ricerca con alcuna regola certa. Come possiamo utilizzare questi dati per identificare un nuovo animale come un schnick Una possibile soluzione al nostro problema è quello di utilizzare una macchina di supporto vettore per identificare i modelli nei dati e creare un quadro che può essere utilizzato per classificare gli animali sia come schnick o non un schnick. Il primo passo è quello di creare un set di dati che può essere utilizzato per addestrare la macchina vettore supporto per identificare schnicks. I dati formazione è un insieme di ingressi e uscite corrispondenti per la macchina vettore supporto per analizzare ed estrarre un modello da. Pertanto, dobbiamo decidere che cosa gli ingressi verranno utilizzati e quanti. Teoricamente, siamo in grado di avere il maggior numero di ingressi come vogliamo, ma questo può spesso portare a rallentare la formazione (i più ingressi si ha più il tempo che ci vuole la macchina Support Vector per estrarre modelli). Inoltre, si vuole scegliere i valori input che tenderà ad essere relativamente coerente in tutti i schnicks. Ad esempio, l'altezza o il peso dell'animale sarebbe un buon esempio di un ingresso, perché ci si aspetta che questo sarebbe relativamente coerente in tutti i schnicks. Tuttavia, l'età media di un animale sarebbe una scelta sbagliata di ingresso in quanto ci si aspetterebbe l'età degli animali identificati sarebbero tutti variare considerevolmente. Per questo motivo, sono stati scelti i seguenti ingressi: Altezza Peso Il numero delle gambe Il numero di occhi La lunghezza degli animali bracci Gli animali velocità media La frequenza degli animali accoppiamento chiamata Con gli ingressi scelti, possiamo cominciare a compilare il nostro dati di allenamento . dati formazione efficace per una macchina di supporto vettore deve soddisfare determinati requisiti: i dati devono avere esempi di animali che sono schnicks I dati devono avere esempi di animali che non sono schnicks In questo caso abbiamo i documenti di ricerca di scienziati che hanno identificato con successo un schnick ed elencati le loro proprietà. Quindi possiamo leggere questi articoli di ricerca ed estrarre i dati in ciascuno degli ingressi e allocare una potenza di vero o falso a ciascuno degli esempi. I dati di allenamento, in questo caso possono sembrare simili alla seguente tabella. Tabella 1. Tabella Esempio di osservazioni Schnick Una volta che abbiamo raccolto i dati per tutti i nostri ingressi e le uscite di allenamento, possiamo usarlo per addestrare la nostra macchina di supporto vettoriale. Durante il processo di formazione, la macchina Support Vector creerà un modello in sette spazio tridimensionale che può essere utilizzata per ordinare ciascuno degli esempi di addestramento in vera o falsa. La macchina vettore supporto continuerà a farlo fino a quando non ha un modello che corrisponde alle dati di allenamento (entro la tolleranza di errore specificato). Una volta che la formazione è completa, questo modello può essere utilizzato per classificare i nuovi punti di dati come true o false. Ha il Support Vector Machine realmente funzionano utilizzando lo scenario Schnick, ho scritto uno script che mette alla prova quanto bene una macchina di supporto vettore può effettivamente individuare nuove schnicks. Per fare questo, ho usato la funzione di biblioteca Support Vector Machine strumento di apprendimento che può essere scaricato dal mercato. Per modellare questo scenario in modo efficace, dobbiamo decidere prima quali sono le proprietà reali di un Schnick. Le proprietà che hanno assunto in questo caso sono stati elencati nella tabella sottostante. Se un animale soddisfa tutti i criteri, allora è un Schnick. Tabella 2. Sintesi dei parametri che definiscono un schnick Ora che abbiamo definito il nostro Schnick, possiamo usare questa definizione di sperimentare con support vector machines. Il primo passo è creare una funzione che è in grado di prendere le sette ingressi per ogni animale e restituire la classificazione effettiva dell'animale come schnick o meno. Questa funzione sarà utilizzata per generare dati formazione per la Macchine a vettori di supporto e valutare le prestazioni di esso alla fine. Questo può essere fatto utilizzando la funzione qui sotto Il passo successivo nel processo è quello di creare una funzione che può generare gli ingressi e le uscite di formazione. Ingressi in questo caso saranno generati creando numeri casuali entro un intervallo fissato per ciascuno dei sette valori di ingresso. Poi per ciascuno dei gruppi di ingressi casuali generati, la funzione isItASchnick () di cui sopra sarà utilizzato per generare l'uscita desiderata corrispondente. Questo è fatto in funzione qui sotto: Ora abbiamo una serie di ingressi e uscite di allenamento, è giunto il momento di creare le nostre macchine support vector utilizzando il Support Vector Machine Learning strumento disponibile nel mercato. Una volta creata una nuova macchina supporto vettoriale, è necessario passare gli ingressi e le uscite di formazione ad esso ed eseguire la formazione. Ora abbiamo una macchina di vettore di supporto che è stato addestrato con successo nell'identificazione Scnhicks. Per verificare questo, siamo in grado di testare la macchina finale Support Vector, chiedendogli di classificare i nuovi punti di dati. Questo viene fatto prima generazione input casuali, quindi utilizzando la funzione isItASchnick () per determinare se questi ingressi corrispondono a una Schnick vero e proprio, quindi utilizzare la macchina Support Vector di classificare gli ingressi e determinare se il risultato previsto corrisponde al risultato effettivo. Questo viene fatto in funzione qui sotto: vi consiglio di giocare con i valori all'interno delle funzioni di cui sopra per vedere come la macchina Support Vector svolge in condizioni diverse. Perché Support Vector Machine così utile Il vantaggio di utilizzare una macchina vector supporto per estrarre modello complesso dai dati è che non è necessario un preliminare comprensione del comportamento dei dati. Una macchina di supporto vettore è in grado di analizzare i dati ed estrarre il suo solo intuizioni e le relazioni. In questo modo, funziona simile ad una scatola nera che riceve un input e generando un'uscita che può rivelarsi molto utile nella ricerca di modelli di dati che sono troppo complesse e non ovvio. Una delle migliori caratteristiche di support vector machines è che sono in grado di affrontare gli errori e rumore nei dati molto bene. Essi sono spesso in grado di vedere il modello di base all'interno dei dati e filtrare i valori anomali di dati e altre complessità. Si consideri il seguente scenario, in esecuzione la vostra ricerca sul Schnicks, ci si imbatte in molteplici documenti di ricerca che descrivono Schnicks con caratteristiche diverse in maniera massiccia (ad esempio un schnick che è 200kg ed è 15 mila millimetri di altezza). Errori come questo può portare a distorsioni vostro modello di ciò che un Schnick è, che potrebbe potenzialmente causare a fare un errore per la classificazione di nuove scoperte Schnick. Il vantaggio della macchina supporto vettore è che svilupperà un modello che concorda con lo schema sottostante contrapposizione ad un modello che si adatta tutti i punti di dati di addestramento. Questo viene fatto consentendo un certo livello di errore nel modello per attivare la macchina Support Vector trascurare eventuali errori nei dati. Nel caso della macchina vettore supporto Schnick, se permettiamo una tolleranza di errore del 5, quindi la formazione sarà solo cercare di sviluppare un modello che è d'accordo con 95 dei dati di addestramento. Questo può essere utile perché permette la formazione di ignorare la piccola percentuale di valori anomali. Siamo in grado di indagare su questa proprietà della macchina Support Vector ulteriormente modificando il nostro script Schnick. La funzione di seguito è stato aggiunto per introdurre errori casuali deliberate nel nostro insieme di dati di addestramento. Questa funzione selezionare i punti di formazione in modo casuale e sostituire gli input e di output corrispondente con variabili aleatorie. Questa funzione ci permette di introdurre errori intenzionali nei nostri dati di allenamento. Utilizzando questi dati errore pieno, siamo in grado di creare e formare una nuova macchina di supporto vettoriale e confrontare le prestazioni con quella originale. Quando lo script viene eseguito, produce i seguenti risultati nella Expert Log. Nel giro di dati di training set con 5000 punti di formazione, siamo stati in grado di introdurre 500 errori casuali. Quando si confrontano le prestazioni di questo errore riempita macchina Support Vector con quella originale, la prestazione viene ridotta solo da LT1. Questo perché la macchina di supporto vettore è in grado di trascurare i valori anomali nel set di dati durante l'allenamento ed è ancora in grado di produrre un modello straordinariamente accurata dei dati veri. Ciò suggerisce che support vector machines potrebbe essere potenzialmente uno strumento più utile per estrarre modelli complessi e approfondimenti da insiemi di dati rumorosi. Figura 5. Il registro esperto risultante a seguito della esecuzione dello script Schnick nelle MetaTrader 5. Versioni Demo Una versione completa del codice di cui sopra può essere scaricato dal codice di base, ma questo script può essere eseguito solo nel terminale se avete acquistato un la versione completa dello strumento Support Vector Machine Learning dal mercato. Se avete solo una versione demo di questo strumento scaricato, sarà limitata a utilizzare lo strumento tramite il tester strategia. Per consentire il test del codice Schnick utilizzare la versione demo dello strumento, ho riscritto una copia dello script in un Expert Advisor che può essere distribuito usando il tester strategia. Entrambe queste versioni di codice possono essere scaricati seguendo i link qui sotto: la versione completa - Utilizzo di uno script che viene distribuito nel terminale MetaTrader 5 (richiede una versione acquistata del Support Vector Machine Learning Tool) Demo Version - L'utilizzo di un consulente esperto che è schierato nella strategia tester MetaTrader 5 (richiede solo una versione demo del Support Vector Machine Learning Tool) Come può Support Vector Machines essere utilizzato nella Certo mercato, l'esempio Schnick discusso sopra è abbastanza semplice, tuttavia ci sono un bel paio di similitudini che può essere tracciata tra questo esempio e utilizzando le support vector machines per l'analisi tecnica del mercato. L'analisi tecnica è fondamentalmente sull'utilizzo di dati storici di mercato per prevedere i movimenti futuri dei prezzi. Allo stesso modo entro l'esempio schnick, siamo stati utilizzando le osservazioni fatte dagli scienziati del passato per prevedere se un nuovo animale è un schnick o meno. Inoltre, il mercato è afflitto con il rumore, gli errori ei valori erratici statistici che rendono l'utilizzo di una macchina Support Vector un concetto interessante. La base per un numero significativo di approcci di analisi commerciali tecnici comporta le seguenti fasi: monitoraggio di diversi indicatori Identificare le condizioni di quello che per ciascun indicatore è correlato con un commercio potenzialmente di successo Guarda ciascuno degli indicatori e valutare quando tutti (o quasi) stanno segnalando un commercio E è possibile adottare un approccio simile per utilizzare macchine di supporto per segnalare nuovi traffici in modo simile. Lo strumento di apprendimento automatico supporto vettoriale è stato sviluppato con questo in mente. Una descrizione completa di come usare questo strumento può essere trovato nel mercato, così ho solo dare una rapida panoramica. Il processo per l'utilizzo di questo strumento è la seguente: Figura 6. Lo schema a blocchi che mostra il processo di attuazione della macchina utensile Support Vector in un Expert Advisor Prima di poter utilizzare lo strumento di apprendimento Support Vector Machine, è importante prima capire come la formazione ingressi e le uscite vengono generati. Come si allena ingressi generata Così, gli indicatori che si desidera utilizzare come ingressi sono stati già stati inizializzati come pure la vostra nuova macchina supporto vettore. Il passo successivo è quello di passare l'indicatore di maniglie per la nuova macchina Support Vector e istruire su come generare i dati di allenamento. Questo viene fatto chiamando i setIndicatorHandles funzione (). Questa funzione consente di passare le maniglie di indicatori inizializzate nella macchina di supporto vettore. Questo viene fatto passare e matrice intera contenente le maniglie. Gli altri due ingressi per questa funzione è il valore di offset e il numero di punti di dati. Il valore di offset indica la compensazione tra la barra corrente e la barra di partenza da utilizzare nella generazione degli ingressi di formazione e il numero di punti di formazione (indicato con N) imposta la dimensione i dati di allenamento. Il diagramma seguente illustra come utilizzare questi valori. Un valore di offset di 4 e un valore N di 6 dirà la macchina Support Vector di utilizzare solo le barre catturati nel quadrato bianco per generare ingressi e le uscite di allenamento. Allo stesso modo, un valore di offset di 8 e un valore N di 8 dirà la macchina Support Vector di utilizzare solo le barre catturati nel quadrato blu per generare ingressi e le uscite di allenamento. Una volta che i setIndicatorHandles function () è stato chiamato, è possibile chiamare la genInputs funzione (). Questa funzione utilizza l'indicatore maniglie per passata per generare una matrice di dati di ingresso da utilizzare per la formazione. Figura 7. grafico Candela che illustra i valori di offset e N come sono uscite di formazione generata uscite di formazione sono generati mediante la simulazione di ipotetici traffici sulla base di dati sui prezzi storici e stabilire se un tale commercio avrebbe avuto successo o insuccesso. Per fare questo, ci sono alcuni parametri che vengono utilizzati per istruire lo strumento di apprendimento automatico Support Vector come valutare un commercio ipotetica come sia successo o insuccesso. La prima variabile è OPTRADE. Il valore di questo può essere sia acquistare o vendere e sarà conforme a uno ipotetico acquisto o di vendita compravendite. Se il valore di questo è BUY, poi quando si generano le uscite sarà solo guardare il potenziale successo di ipotetici buy compravendite. In alternativa, se il valore di questo è vendita, poi quando si generano le uscite apparirà solo il potenziale successo di ipotetici traffici vendita. I prossimi valori utilizzati è la Stop Loss e Take Profit per questi ipotetici traffici. I valori sono impostati in pips e sarà impostare i livelli di stop e limite per ciascuna delle ipotetiche compravendite. Il parametro finale è la durata del commercio. Questa variabile è misurato in ore e farà in modo che solo i mestieri che sono complete all'interno di questa durata massima sarà considerato di successo. La ragione per includere questa variabile è quello di evitare la macchina Support Vector segnalazione mestieri in un lento movimento laterale del mercato. Considerazioni da fare quando si sceglie Ingressi E 'importante mettere qualche pensiero nella selezione degli ingressi in sede di attuazione support vector machines nel tuo trading. Simile l'esempio Schnick, è importante scegliere un ingresso che ci si aspetterebbe di avere simili tra incidenza di differenza. Ad esempio, si potrebbe essere tentati di utilizzare una media mobile come ingresso, tuttavia, poiché il prezzo medio lungo termine tende a cambiare drammaticamente nel corso del tempo, una media mobile di isolamento non può essere la migliore in ingresso da utilizzare. Questo è perché ci non sarà alcuna somiglianza significativa tra il valore di media mobile oggi ei valori medi in movimento sei mesi fa. Assumiamo stiamo trading EURUSD e utilizzando una macchina di supporto vettoriale con un ingresso di media mobile a segnale di acquisto compravendite. Dicono che il prezzo corrente è 1,10, tuttavia sta generando i dati di formazione di sei mesi fa, quando il prezzo era 0,55. Quando la formazione della macchina vettore di sostegno, il modello che trova può solo portare ad un commercio di essere segnalato, quando il prezzo è di circa 0.55, poiché questo è l'unico dato che conosce. Pertanto, la macchina di supporto vettore non può mai segnalare un commercio fino a quando il prezzo scende giù a 0,55. Invece, un ingresso meglio utilizzare per la macchina vettore di supporto può essere un MACD o un oscillatore simile perché il valore del MACD è indipendente dal livello di prezzo medio e segnala solo movimento relativo. Vi consiglio di sperimentare con questo per vedere ciò che produce i risultati migliori per voi. Un'altra considerazione da fare quando gli ingressi scelta è garantire che la macchina Support Vector ha un adeguato un'istantanea di un indicatore per segnalare un nuovo mestiere. Si possono trovare nella vostra esperienza di trading che un MACD è utile solo quando si hanno degli ultimi cinque bar a guardare, in modo da mostrare una tendenza. Una singola barra del MACD può essere inutile in isolamento a meno che non si può dire se si sta dirigendo verso l'alto o verso il basso. Pertanto, può essere necessario passare ultimi barre del MACD al vettore supporto machine. There sono due possibili modi si può fare questo: è possibile creare un nuovo indicatore personalizzato che utilizza gli ultimi cinque barre del MACD a calcolare una tendenza come un singolo valore. Questo indicatore personalizzato può quindi essere passato alla macchina supporto vettore come un singolo ingresso, oppure è possibile utilizzare i precedenti cinque bar del MACD nella macchina vettore supporto come cinque ingressi separati. Il modo per farlo è quello di inizializzare le cinque diverse istanze del MACD. Ciascuno degli indicatori possono essere inizializzati con un offset dalla barra di corrente diversa. Poi i cinque maniglie dagli indicatori separati possono essere passati alla macchina supporto vettore. Va notato che l'opzione 2 tenderà a causare tempi di esecuzione più lunghi per la Expert Advisor. I più ingressi si hanno, più tempo ci vorrà per allenarsi con successo. Esecuzione Support Vector Machines in e Expert Advisor ho preparato un Expert Advisor che è un esempio di come qualcuno potrebbe potenzialmente utilizzare support vector machines nella propria negoziazione (una copia di questa può essere scaricato seguendo questo link mql5encode1229). Speriamo che l'Expert Advisor vi permetterà di sperimentare un po 'con support vector machines. Vi consiglio di copychangemodify l'Expert Advisor per soddisfare il proprio stile di trading. La EA funziona nel modo seguente: Due nuovi support vector machines sono creati utilizzando la libreria svMachineTool. Uno è impostato per segnalare nuovi Compro mestieri e l'altro è impostato per segnalare la nuova vendita compravendite. Sette indicatori standard vengono inizializzati con ciascuna delle loro maniglie memorizzati su un array di interi (Nota: qualsiasi combinazione di indicatori possono essere utilizzati come ingressi, hanno solo bisogno di essere passato al SVM in un singolo array intero). La gamma di maniglie indicatore è passato alle nuove support vector machines. Utilizzando la gamma di maniglie indicatori e di altri parametri, i dati storica dei prezzi viene utilizzato per generare gli ingressi e le uscite precise da utilizzare per la formazione dei support vector machines. Una volta che tutti gli ingressi e le uscite sono stati generati, entrambe le macchine support vector sono addestrati. Le Support Vector Machines addestrati sono utilizzati nella EA per segnalare nuovi di acquisto e vendita compravendite. Quando un nuovo acquisto o di vendita commercio viene segnalata, il commercio si apre con Stop Loss manuale e Take Profit. L'inizializzazione e la formazione della macchina supporto vettore vengono eseguiti all'interno della funzione onInit (). Per il vostro riferimento, questo segmento della svTrader EA è stato incluso in basso con le note. Avanzate Support Vector Machine Trading capacità addizionale è stata costruita nello strumento di apprendimento automatico Support Vector per gli utenti più avanzati là fuori. Lo strumento consente all'utente di inserire nel loro dati di input personalizzati e dati di uscita stessa (come nell'esempio Schnick). Questo permette di progettare su misura i tuoi propri criteri per gli ingressi della macchina support vector e le uscite, e passare manualmente tali dati per addestrarlo. Questo apre la possibilità di utilizzare delle macchine di supporto in ogni aspetto del tuo trading. Non è solo possibile utilizzare support vector machines per segnalare nuovi mestieri, ma può anche essere utilizzato per segnalare la chiusura delle negoziazioni, gestione del denaro, nuovi indicatori avanzati ecc Tuttavia per essere sicuri di non ricevete gli errori, è importante capire come questi ingressi e uscite devono essere strutturati. Ingressi: Gli ingressi sono passati al SVM come una matrice bidimensionale 1 di valori doppi. Si prega di notare che qualsiasi input si crea deve essere passato come un valore doppio. Booleano, intero, ecc devono tutti essere convertito in un valore doppio prima di passare nella macchina vettore di supporto. Gli ingressi sono necessari il seguente modulo. Ad esempio, supponiamo che stiamo passando in input con 3 ingressi x 5 punti di formazione. Per raggiungere questo obiettivo, il doppio array deve essere lungo 15 unità nel formato: A 1 B 1 C 1 A 2 B 2 C 2 A 3 B 3 C 3 A 4 B 4 C 4 A 5 B 5 C 5 È altresì necessario per passare in un valore per il numero di ingressi. Nel caso, NInputs3. Uscite: uscite sono passati come una matrice di valori booleani. Questi valori booleani sono l'uscita desiderata della SVM corrispondeva a ciascuno dei gruppi di ingressi passati in. Seguendo l'esempio precedente, dire abbiamo 5 punti di formazione. In questo scenario, passeremo in un array booleano di valori di uscita che è di 5 unità. Quando si genera il proprio input e output, essere sicuri che la lunghezza delle matrici corrisponde ai valori si passa. Se essi non corrispondono, un errore verrà generato notifica della discrepanza. Ad esempio, se abbiamo superato in NInputs3 e ingressi è un array di lunghezza 16, verrà generato un errore (dato un valore Ninputs 3 significa che la lunghezza di ogni matrice di ingresso dovrà essere un multiplo di 3) . Allo stesso modo, garantire che il numero di serie di ingressi e il numero di uscite che vengono passati in sono uguali. Anche in questo caso, se avete NInputs3, la lunghezza degli ingressi di 15 e una lunghezza di uscite del 6, verrà lanciato un altro errore (quando si dispone di 5 set di ingressi e 6 uscite). Fare in modo di avere abbastanza variazioni nelle uscite di allenamento. Ad esempio, se si passa a 100 punti di formazione, il che significa una serie di output di lunghezza 100, e tutti i valori sono false con un solo vero, allora la differenziazione tra il vero e proprio caso e il caso falso non è sufficiente. Ciò tende a portare alla formazione SVM molto veloce, ma la soluzione finale è molto scarsa. Un più diversificata training set porterà spesso a un SVM. Trading più affettiva con Support Vector Machines (SVM) Infine tutte le stelle sono allineate e posso tranquillamente dedicare un po 'di tempo per il back-sperimentazione di nuovi sistemi di trading, e Support Vector Machines (SVM ) sono il nuovo 8220toy8221 che sta per tenermi occupato per un po '. SVM sono uno strumento ben noto dalla zona di Machine Learning sorvegliato. e sono utilizzati sia per la classificazione e la regressione. Per maggiori dettagli fare riferimento alla letteratura. Mi sembra che l'applicazione più intuitiva per la negoziazione è la regressione, così let8217s iniziare con la costruzione di un modello di regressione SVM. A seguito della nostra esperienza con i modelli ARMAGARCH, inizieremo cercando di prevedere i rendimenti, invece di prezzi. Allo stesso modo, nei nostri primi test, useremo solo i rendimenti dei 5 giorni precedenti e le caratteristiche che determinano il ritorno di un giorno particolare. Inizieremo con la storia di 500 giorni come il training set. In termini più matematici, per l'insieme di addestramento abbiamo N caratteristiche, per ciascuno di essi abbiamo M campioni. Abbiamo anche le risposte M. Data una riga di valori caratteristica, la matrice di sinistra, la SVM è addestrato per produrre il valore di risposta. Nel nostro esempio specifico, abbiamo cinque colonne (caratteristiche), ciascuna colonna corrispondente ai rendimenti con un ritardo diverso (da 1 a 5). Abbiamo 500 campioni e le risposte corrispondenti. Una volta che il SVM è addestrato su questo insieme, possiamo iniziare alimentandola con gruppi di cinque funzioni, corrispondenti ai ritorni per i cinque giorni precedenti, e la SVM ci fornirà la risposta, che è il rendimento previsto. Ad esempio, dopo la formazione della SVM sui precedenti 500 giorni, useremo i rendimenti per i giorni 500, 499, 498, 497 e 496 (questi sono i nostri come ingresso per ottenere il ritorno previsto per il giorno 501. Da tutti i pacchetti disponibili in R, ho deciso di scegliere il pacchetto E1071. Una stretta seconda scelta era il pacchetto kernlab, che sto ancora pensando di provare in futuro. Poi ho provato alcune strategie. per prima cosa ho provato qualcosa di molto simile all'approccio ARMAGARCH 8211 la ritardati rendimenti dei cinque giorni precedenti. sono stato molto sorpreso di vedere questa strategia l'esecuzione migliore del ARMAGARCH (questa è la patria del ARMAGARCH e mi sarebbe stato molto felice solo con prestazioni paragonabili) Poi, ho provato la stessa cinque caratteristiche, ma cercando di selezionare la migliore sottoinsieme. la selezione è stata effettuata utilizzando un approccio avido, a partire da 0 caratteristiche, e in modo interattivo aggiungendo la funzione che riduce al minimo l'errore migliore. Questo approccio ha migliorato ulteriormente le cose. Infine, ho provato un approccio diverso con circa una dozzina di caratteristiche. Le caratteristiche incluse rendimenti oltre diverso periodo di tempo (1 giorno, 2 giorni, 5 giorni, ecc), alcune statistiche (media, mediana, deviazione standard, ecc) e il volume. Ho usato lo stesso approccio greedy per selezionare le funzioni. Questo sistema finale ha mostrato una performance molto buona pure, ma ci è voluto un sacco di tempo per l'esecuzione. È ora di concludere questo post, i risultati di test retrospettivi devono aspettare. Fino ad allora si può giocare con il codice sorgente completo da soli. Ecco un esempio di utilizzo: Hi In windows doesn8217t lavoro a causa del problema multicore. Una cosa che ho capito don8217t si riflette in questo alle righe del codice RET retsindex (dati) DataIndex dati (RET) A mio parere it8217s più efficace per unire serie smth come mydtret lt - na. exclude (merge (RET, i dati) e di avere un solo argumentobject di funzionare chiamata invece di 2 lavoro interessante, grazie Mike Argh, Windows 8211 lo uso raramente negli ultimi tempi. Molto sorpreso ancora, dal momento che il pacchetto parallela è parte della distribuzione di base R ora. Speriamo che sarà affrontata a breve . Nel frattempo, che ne dici di non utilizzare l'esecuzione parallela ci sono anche altri pacchetti che prevedono l'esecuzione parallela, ma che sarebbe più lavoro. Hai ragione circa l'unione 8211 mi chiedo ancora perché l'ho fatto in questo modo questa volta. :) I8217m ricevere errori. Ora l'errore è di dati GT svmFeatures (TT), C (1,2) Errore in match. fun (FUN). oggetto 8216skewness8217 non trovato, ma quando faccio manualmente oggetto dati ricevo errore nella previsione svmComputeOneForecast funzione lt - relativi a dimensioni e samplingquotcrossquot It039s difficile per me per eseguire il debug asimmetria deriva dal pacchetto PerformanceAnalytics, che è necessario installare da CRAN. L'aggiunta di require (PerformanceAnalytics) come la prima linea di svmFeatures dovrebbe affrontare il primo problema. ora di errore è l'errore in merge. xts (res, XTS (na. trim (lag (rollmean (RET, K 21, allineare 8220right8221). La durata del 8216dimnames8217 2 non è uguale a matrice misura sembra che nelle finestre di codice ha bisogno di un sacco di cambiamenti Mike, I never meant the code to be used directly (until now I was providing only snippets), but I am surprised that R on Windows is so ugly. Not sure what8217s your goal, but to analyze the strategies performance, you can use the indicator series which are already computed. It8217s just pure academic interest on SVM. I used to work with clusters, PCA and I am curious how SVM is doing the same work. In windows a lot of error are related to objects with dates as xts is or data frames. UNIX is better but all brokers give API for windows. Some of them in Java and only this we may use from UNIX. I don8217t like win architecture but it8217s a habit already and I don8217t have time to change OS. I just tried it on windows 7, 64 bit, R version 2.15.2. I get a warning from svmFeatures, which I know how to fix (calling sd on an xtszoo object does interesting conversion to a matrix), but no problems. Running: Thanks I8217ll try. One question if you don8217t mind Why are you using get with function cetSymbols from quantmod package I use call vers Example SPY lt - getSymbols(039SPY039, auto. assign FALSE) You have a lot to compute and get consume memory and takes time to obtain objects name as a string var The same error I8217m using R 2.15.1 But I8217m surprised with this result before call gt head(data) 1 function (8230, list character(), package NULL, lib. loc NULL, 2 verbose getOption(8220verbose8221), envir. GlobalEnv) 3 4 fileExt lt - function(x) 5 db lt - grepl(quot...(gzbz2xz)quot, x) 6 ans lt - sub(quot..quot, quotquot, x) It seems that data is reserved word And now I don039t know what is going to features functionTrading with Support Vector Machines (SVM) Finally all the stars have aligned and I can confidently devote some time for back-testing of new trading systems, and Support Vector Machines (SVM) are the new 8220toy8221 which is going to keep me busy for a while. SVMs are a well-known tool from the area of supervised Machine Learning. and they are used both for classification and regression. For more details refer to the literature. It seems to me that the most intuitive application for trading is regression, so let8217s start by building an SVM regression model. Following our experience with ARMAGARCH models, we will start by trying to forecast returns, instead of prices. Likewise, in our first tests, we will use only the returns of the previous 5 days as the features determining the return of a particular day. We will start with history of 500 days as the training set. In more mathematical terms, for the training set we have N features, for each of them we have M samples. We also have M responses. Given a row of feature values, the left matrix, the SVM is trained to produce the response value. In our specific example, we have five columns (features), each column corresponding to the returns with a different lag (from 1 to 5). We have 500 samples and the corresponding responses. Once the SVM is trained on this set, we can start feeding it with sets of five features, corresponding to the returns for the five previous days, and the SVM will provide us with the response, which is the forecasted return. For example, after training the SVM on the previous 500 days, we will use the returns for days 500, 499, 498, 497 and 496 (these are ours as the input to obtain the forecasted return for day 501. From all the packages available in R, I decided to choose the e1071 package. A close second choice was the kernlab package, which I am still planning to try in the future. Then I tried a few strategies. First I tried something very similar to the ARMAGARCH approach 8211 the lagged returns from the five previous days. I was quite surprised to see this strategy performing better than the ARMAGARCH (this is the home land of the ARMAGARCH and I would have been quite happy just with comparable performance) Next, I tried to the same five features, but trying to select the best subset. The selection was done using a greedy approach, starting with 0 features, and interactively adding the feature which minimizes the error best. This approach improved things further. Finally, I tried a different approach with about a dozen features. The features included returns over different period of time (1-day, 2-day, 5-day, etc), some statistics (mean, median, sd, etc) and volume. I used the same greedy approach to select features. This final system showed a very good performance as well, but it took a hell of a time to run. Time to end this post, the back-testing results have to wait. Until then you can play with the full source code yourself. Here is an example of using it: Never miss an update Subscribe to R-bloggers to receive e-mails with the latest R posts. (You will not see this message again.)Support Vector Machines: A Guide for Beginners In this guide I want to introduce you to an extremely powerful machine learning technique known as the Support Vector Machine (SVM). It is one of the best out of the box supervised classification techniques. As such, it is an important tool for both the quantitative trading researcher and data scientist. I feel it is important for a quant researcher or data scientist to be comfortable with both the theoretical aspects and practical usage of the techniques in their toolkit. Hence this article will form the first part in a series of articles that discuss support vector machines. This article specifically will cover the theory of maximal margin classifiers . support vector classifiers and support vector machines . Subsequent articles will make use of the Python scikit-learn library to demonstrate some examples of the aforementioned theoretical techniques on actual data. Motivation for Support Vector Machines The problem to be solved in this article is one of supervised binary classification . That is, we wish to categorise new unseen objects into two separate groups based on their properties and a set of known examples, which are already categorised. A good example of such a system is classifying a set of new documents into positive or negative sentiment groups, based on other documents which have already been classified as positive or negative. Similarly, we could classify new emails into spam or non-spam, based on a large corpus of documents that have already been marked as spam or non-spam by humans. SVMs are highly applicable to such situations. A Support Vector Machine models the situation by creating a feature space . which is a finite-dimensional vector space. each dimension of which represents a feature of a particular object. In the context of spam or document classification, each feature is the prevalence or importance of a particular word. The goal of the SVM is to train a model that assigns new unseen objects into a particular category. It achieves this by creating a linear partition of the feature space into two categories. Based on the features in the new unseen objects (e. g. documentsemails), it places an object above or below the separation plane, leading to a categorisation (e. g. spam or non-spam). This makes it an example of a non-probabilistic linear classifier. It is non-probabilistic, because the features in the new objects fully determine its location in feature space and there is no stochastic element involved. However, much of the benefit of SVMs comes from the fact that they are not restricted to being linear classifiers. Utilising a technique known as the kernel trick they can become much more flexible by introducing various types of non-linear decision boundaries. Formally, in mathematical language, SVMs construct linear separating hyperplanes in high-dimensional vector spaces. Data points are viewed as (vec , y) tuples, vec (x1, ldots, xp) where the xj are the feature values and y is the classification (usually given as 1 or -1). Optimal classification occurs when such hyperplanes provide maximal distance to the nearest training data points. Intuitively, this makes sense, as if the points are well separated, the classification between two groups is much clearer. However, if in a feature space some of the sets are not linearly separable (i. e. they overlap), then it is necessary to perform a mapping of the original feature space to a higher-dimensional space, in which the separation between the groups is clear, or at least clearer. However, this has the consequence of making the separation boundary in the original space potentially non-linear. In this article we will proceed by considering the advantages and disadvantages of SVMs as a classification technique, then defining the concept of an optimal linear separating hyperplane . which motivates a simple type of linear classifier known as a maximal margin classifier (MMC). We will then show that maximal margin classifiers are not often applicable to many real world situations and as such need modification, in the form of a support vector classifier (SVC). We will then relax the restriction of linearity and consider non-linear classifiers, namely support vector machines . which use kernel functions to improve computational efficiency. Advantages and Disadvantages of SVMs As a classification technique, the SVM has many advantages, many of which are due to its computational efficiency on large datasets. The Scikit-Learn team have summarised the main advantages and disadvantages here but I have repeated and elaborated on them for completeness: Advantages High-Dimensionality - The SVM is an effective tool in high-dimensional spaces, which is particularly applicable to document classification and sentiment analysis where the dimensionality can be extremely large (geq 106). Memory Efficiency - Since only a subset of the training points are used in the actual decision process of assigning new members, only these points need to be stored in memory (and calculated upon) when making decisions. Versatility - Class separation is often highly non-linear. The ability to apply new kernels allows substantial flexibility for the decision boundaries, leading to greater classification performance. Disadvantages p gt n - In situations where the number of features for each object (p) exceeds the number of training data samples (n), SVMs can perform poorly. This can be seen intuitively, as if the high-dimensional feature space is much larger than the samples, then there are less effective support vectors on which to support the optimal linear hyperplanes, leading to poorer classification performance as new unseen samples are added. Non-Probabilistic - Since the classifier works by placing objects above and below a classifying hyperplane, there is no direct probabilistic interpretation for group membership. However, one potential metric to determine effectiveness of the classification is how far from the decision boundary the new point is. Now that weve outlined the advantages and disadvantages, were going to discuss the geometric objects and mathematical entities that will ultimately allow us to define the SVMs and how they work. There are some fantastic references (both links and textbooks) that derive much of the mathematical detail of how SVMs work. In the following derivation I didnt want to reinvent the wheel too much, especially with regards notation and pedagogy, so Ive formulated the following treatment based on the references provided at the end of the article, making strong use of James et al (2013). Hastie et al (2009) and the Wikibooks article on SVMs. I have made changes to the notation where appropriate and have adjusted the narrative to suit individuals interested in quantitative finance. Linear Separating Hyperplanes The linear separating hyperplane is the key geometric entity that is at the heart of the SVM. Informally, if we have a high-dimensional feature space, then the linear hyperplane is an object one dimension lower than this space that divides the feature space into two regions. This linear separating plane need not pass through the origin of our feature space, i. e. it does not need to include the zero vector as an entity within the plane. Such hyperplanes are known as affine . If we consider a real-valued p-dimensional feature space, known mathematically as mathbb p, then our linear separating hyperplane is an affine p-1 dimensional space embedded within it. For the case of p2 this hyperplane is simply a one-dimensional straight line, which lives in the larger two-dimensional plane, whereas for p3 the hyerplane is a two-dimensional plane that lives in the larger three-dimensional feature space (see Fig 1 and Fig 2): If we consider an element of our p-dimensional feature space, i. e. vec (x1. xp) in mathbb p, then we can mathematically define an affine hyperplane by the following equation: begin b0 b1 x1 . bp xp 0 end b0 neq 0 gives us an affine plane (i. e. it does not pass through the origin). We can use a more succinct notation for this equation by introducing the summation sign: Notice however that this is nothing more than a multi-dimensional dot product (or, more generally, an inner product ), and as such can be written even more succinctly as: If an element vec in mathbb p satisfies this relation then it lives on the p-1-dimensional hyperplane. This hyperplane splits the p-dimensional feature space into two classification regions (see Fig 3): Elements vec above the plane satisfy: While those below it satisfy: The key point here is that it is possible for us to determine which side of the plane any element vec will fall on by calculating the sign of the expression vec cdot vec b0. This concept will form the basis of a supervised classification technique. Classification Continuing with our example of email spam filtering, we can think of our classification problem (say) as being provided with a thousand emails (n1000), each of which is marked spam (1) or non-spam (-1). In addition, each email has an associated set of keywords (i. e. separating the words on spacing) that provide features . Hence if we take the set of all possible keywords from all of the emails (and remove duplicates), we will be left with p keywords in total. If we translate this into a mathematical problem, the standard setup for a supervised classification procedure is to consider a set of n training observations . vec i, each of which is a p-dimensional vector of features. Each training observation has an associated class label . yi in . Hence we can think of n pairs of training observations (vec i, yi) representing the features and class labels (keyword lists and spamnon-spam). In addition to the training observations we can provide test observations . vec (x 1. x p) that are later used to test the performance of the classifiers. In our spam example, these test observations would be new emails that have not yet been seen. Our goal is to develop a classifier based on provided training observations that will correctly classify subsequent test observations using only their feature values. This translates into being able to classify an email as spam or non-spam solely based on the keywords contained within it. We will initially suppose that it is possible, via a means yet to be determined, to construct a hyperplane that separates training data perfectly according to their class labels (see Figs 4 and 5). This would mean cleanly separating spam emails from non-spam emails solely by using specific keywords. The following diagram is only showing p2, while for keyword lists we may have pgt106. Hence Figs 4 and 5 are only representative of the problem. This translates into a mathematical separating property of: begin vec cdot vec i b0 gt 0,enspacetext enspace yi 1 end begin vec cdot vec i b0 lt 0,enspacetext enspace yi -1 end This basically states that if each training observation is above or below the separating hyperplane, according to the geometric equation which defines the plane, then its associated class label will be 1 or -1. Thus we have developed a simple classification process. We assign a test observation to a class depending upon which side of the hyperplane it is located on. This can be formalised by considering the following function f(vec ), with a test observation vec (x 1. x p): If f(vec ) gt 0 then y 1, whereas if f(vec ) lt 0 then y -1. However, this tells us nothing about how we go about finding the bj components of vec , as well as b0, which are crucial in helping us determine the equation of the hyperplane separating the two regions. The next section discusses an approach for carrying this out, as well as introducing the concept of the maximal margin hyperplane and a classifier built on it, known as the maximal margin classifier . Deriving the Classifier At this stage it is worth pointing out that separating hyperplanes are not unique, since it is possible to slightly translate or rotate such a plane without touching any training observations (see Fig 4). So, not only do we need to know how to construct such a plane, but we also need to determine the most optimal . This motivates the concept of the maximal margin hyperplane (MMH), which is the separating hyperplane that is farthest from any training observations, and is thus optimal. How do we find the maximal margin hyperplane Firstly, we compute the perpendicular distance from each training observation vec i for a given separating hyperplane. The smallest perpendicular distance to a training observation from the hyperplane is known as the margin . The MMH is the separating hyperplane where the margin is the largest. This guarantees that it is the farthest minimum distance to a training observation. The classification procedure is then just simply a case of determining which side a test observation falls on. This can be carried out using the above formula for f(vec ). Such a classifier is known as a maximimal margin classifier (MMC). Note however that finding the particular values that lead to the MMH is purely based on the training observations . That is, we still need to be aware of how the MMC performs on the test observations . We are implicitly making the assumption that a large margin in the training observations will provide a large margin on the test observations, but this may not be the case. As always, we must be careful to avoid overfitting when the number of feature dimensions is large (e. g. in Natural Language Processing applications such as email spam classification). Overfitting here means that the MMH is a very good fit for the training data but can perform quite poorly when exposed to testing data . I discuss this issue in depth in the article on the bias-variance trade-off . To reiterate, our goal now becomes finding an algorithm that can produce the bj values, which will fix the geometry of the hyperplane and hence allow determination of f(vec ) for any test observation. If we consider Fig 6, we can see that the MMH is the mid-line of the widest block that we can insert between the two classes such that they are perfectly separated. One of the key features of the MMC (and subsequently SVC and SVM) is that the location of the MMH only depends on the support vectors . which are the training observations that lie directly on the margin (but not hyperplane) boundary (see points A, B and C in Fig 6). This means that the location of the MMH is NOT dependent upon any other training observations. Thus it can be immediately seen that a potential drawback of the MMC is that its MMH (and thus its classification performance) can be extremely sensitive to the support vector locations. However, it is also partially this feature that makes the SVM an attractive computational tool, as we only need to store the support vectors in memory once it has been trained (i. e. the bj values are fixed). Constructing the Maximal Margin Classifier I feel it is instructive to fully outline the optimisation problem that needs to be solved in order to create the MMH (and thus the MMC itself). While I will outline the constraints of the optimisation problem, the algorithmic solution to this problem is beyond the scope of the article. Thankfully these optimisation routines are implemented in scikit-learn (actually, via the LIBSVM library ). If you wish to read more about the solution to these algorithmic problems, take a look at Hastie et al (2009) and the Scikit-Learn page on Support Vector Machines . The procedure for determining a maximal margin hyperplane for a maximal margin classifier is as follows. Given n training observations vec 1. vec n in mathbb p and n class labels y1. yn in , the MMH is the solution to the following optimisation procedure: Maximise M in mathbb , by varying b1. bp such that: begin yi left( vec cdot vec b0 right) geq M, quad forall i 1. n end Despite the complex looking constraints, they actually state that each observation must be on the correct side of the hyperplane and at least a distance M from it. Since the goal of the procedure is to maximise M, this is precisely the condition we need to create the MMC Clearly, the case of perfect separability is an ideal one. Most real world datasets will not have such perfect separability via a linear hyperplane (see Fig 7). However, if there is no separability then we are unable to construct a MMC by the optimisation procedure above. So, how do we create a form of separating hyperplane Essentially we have to relax the requirement that a separating hyperplane will perfectly separate every training observation on the correct side of the line (i. e. guarantee that it is associated with its true class label), using what is called a soft margin . This motivates the concept of a support vector classifier (SVC). Support Vector Classifiers As we alluded to above, one of the problems with MMC is that they can be extremely sensitive to the addition of new training observations. Consider Figs 8 and 9. In Fig 8 it can be seen that there exists a MMH perfectly separating the two classes. However, in Fig 9 if we add one point to the 1 class we see that the location of the MMH changes substantially. Hence in this situation the MMH has clearly been over-fit : As we mentioned above also, we could consider a classifier based on a separating hyperplane that doesnt perfectly separate the two classes, but does have a greater robustness to the addition of new invididual observations and has a better classification on most of the training observations. This comes at the expense of some misclassification of a few training observations. This is how a support vector classifier or soft margin classifier works. A SVC allows some observations to be on the incorrect side of the margin (or hyperplane), hence it provides a soft separation. The following figures 10 and 11 demonstrate observations being on the wrong side of the margin and the wrong side of the hyperplane respectively: As before, an observation is classified depending upon which side of the separating hyperplane it lies on, but some points may be misclassified. It is instructive to see how the optimisation procedure differs from that described above for the MMC. We need to introduce new parameters, namely n epsiloni values (known as the slack values ) and a parameter C, known as the budget . We wish to maximise M, across b1. bp, epsilon1. epsilonn such that: begin yi left( vec cdot vec b0 right) geq M (1 - epsiloni), quad forall i 1. n end begin epsiloni geq 0, quad sum epsiloni leq C end Where C, the budget, is a non-negative tuning parameter. M still represents the margin and the slack variables epsiloni allow the individual observations to be on the wrong side of the margin or hyperplane. In essence the epsiloni tell us where the ith observation is located relative to the margin and hyperplane. For epsiloni0 it states that the xi training observation is on the correct side of the margin. For epsiloni0 we have that xi is on the wrong side of the margin, while for epsiloni1 we have that xi is on the wrong side of the hyperplane. C collectively controls how much the individual epsiloni can be modified to violate the margin. C0 implies that epsiloni0, forall i and thus no violation of the margin is possible, in which case (for separable classes) we have the MMC situation. For C0 it means that no more than C observations can violate the hyperplane. As C increases the margin will widen. See Fig 12 and 13 for two differing values of C: How do we choose C in practice Generally this is done via cross-validation. In essence C is the parameter that governs the bias-variance trade-off for the SVC. A small value of C means a low bias, high variance situation. A large value of C means a high bias, low variance situation. As before, to classify a new test observation x we simply calculate the sign of f(vec ) vec cdot vec b0. This is all well and good for classes that are linearly (or nearly linearly) separated. However, what about separation boundaries that are non-linear How do we deal with those situations This is where we can extend the concept of support vector classifiers to support vector machines. Support Vector Machines The motivation behind the extension of a SVC is to allow non-linear decision boundaries. This is the domain of the Support Vector Machine (SVM). Consider the following Figs 14 and 15. In such a situation a purely linear SVC will have extremely poor performance, simply because the data has no clear linear separation: Hence SVCs can be useless in highly non-linear class boundary problems. In order to motivate how an SVM works, we can consider a standard trick in linear regression, when considering non-linear situations. In particular a set of p features x1. xp can be transformed, say, into a set of 2p features x1, x21. xp, x2p. This allows us to apply a linear technique to a set of non-linear features. While the decision boundary is linear in the new 2p-dimensional feature space it is non-linear in the original p-dimensional space. We end up with a decision boundary given by q(vec )0 where q is a quadratic polynomial function of the original features and hence is a non-linear solution. This is clearly not restricted to quadratic polynomials. Higher dimensional polynomials, interaction terms and other functional forms, could all be considered. Although the drawback is that it dramatically increases the dimension of the feature space to the point that some algorithms can become untractable. The major advantage of SVMs is that they allow a non-linear enlargening of the feature space, while still retaining a significant computational efficiency, using a process known as the kernel trick. which will be outlined below shortly. So what are SVMs In essence they are an extension of SVCs that results from enlargening the feature space through the use of functions known as kernels . In order to understand kernels, we need to briefly discuss some aspects of the solution to the SVC optimisation problem outlined above. While calculating the solution to the SVC optimisation problem, the algorithm only needs to make use of inner products between the observations and not the observations themselves. Recall that an inner product is defined for two p-dimensional vectors u, v as: Hence for two observations an inner product is defined as: While we wont dwell on the details (since they are beyond the scope of this article), it is possible to show that a linear support vector classifier for a particular observation vec can be represented as a linear combination of inner products: begin f(vec ) b0 sum alphai langle vec , vec i rangle end With n ai coefficients, one for each of the training observations. To estimate the b0 and ai coefficients we only need to calculate n(n-1)2 inner products between all pairs of training observations. In fact, we ONLY need to calculate the inner products for the subset of training observations that represent the support vectors . I will call this subset mathscr . This means that: begin ai 0 enspace text enspace vec i notin mathscr end This means we can rewrite the representation formula as: This turns out to be a major advantage for computational efficiency. This now motivates the extension to SVMs. If we consider the inner product langle vec i, vec k rangle and replace it with a more general inner product kernel function KK(vec i, vec k), we can modify the SVC representation to use non-linear kernel functions and thus modify how we calculate similarity between two observations. For instance, to recover the SVC we just take K to be as follows: Since this kernel is linear in its features the SVC is known as the linear SVC. We can also consider polynomial kernels, of degree d: This provides a significantly more flexible decision boundary and essentially amounts to fitting a SVC in a higher-dimensional feature space involving d-degree polynomials of the features (see Fig 16). Hence, the definition of a support vector machine is a support vector classifier with a non-linear kernel function. We can also consider the popular radial kernel (see Fig 17): begin K(vec i, vec k) exp left(-gamma sum (x - x )2 right), quad gamma 0 end So how do radial kernels work They are clearly quite different from polynomial kernels. Essentially if our test observation vec is far from a training observation vec i in standard Euclidean distance then the sum sum (x j - x )2 will be large and thus K(vec, vec i) will be very small. Hence this particular training observation vec i will have almost no effect on where the test observation vec is placed, via f(vec ). Thus the radial kernel has extremely localised behaviour and only nearby training observations to vec will have an impact on its class label. While this article has been very theoretical, the next article on document classification using Scikit-Learn makes heavy use of SVMs in Python. Biblographic Notes Originally, SVMs were invented by Vapnik (1996). while the current standard soft margin approach is due to Cortes (1995). My treatment of the material follows, and is strongly influenced by, the excellent statistical machine learning texts of James et al (2013) and Hastie et al (2009) . References Vapnik, V. (1996) The Nature of Statistical Learning Theory Cortes, C. Vapnik, V. (1995) Support Vector Networks, Machine Learning 20 (3): 273 James, G. Witten, D. Hastie, T. Tibshiranie, R. (2013) An Introduction to Statistical Learning Hastie, T. Tibshiranie, R. Friedman, J. (2009) The Elements of Statistical Learning Wikibooks (2016) Support Vector Machines (Link ) Scikit-Learn (2016) Support Vector Machines (Link ) Just Getting Started with Quantitative Trading
No comments:
Post a Comment