Skip to content

Commit

Permalink
Added an extended PCA example with the iris dataset and plotting (#56)
Browse files Browse the repository at this point in the history
* Added an extended example with the iris dataset and plotting
  • Loading branch information
IanButterworth authored and wildart committed Dec 3, 2017
1 parent a65917f commit b8075a6
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions docs/source/pca.rst
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,46 @@ One can use the ``fit`` method to perform PCA over a given dataset.
# reconstruct testing observations (approximately)
Xr = reconstruct(M, Yte)
**Example with iris dataset and plotting:**

.. code-block:: julia
using MultivariateStats, RDatasets, Plots
plotly() # using plotly for 3D-interacive graphing
# load iris dataset
iris = dataset("datasets", "iris")
# split half to training set
Xtr = convert(Array,DataArray(iris[1:2:end,1:4]))'
Xtr_labels = convert(Array,DataArray(iris[1:2:end,5]))
# split other half to testing set
Xte = convert(Array,DataArray(iris[2:2:end,1:4]))'
Xte_labels = convert(Array,DataArray(iris[2:2:end,5]))
# suppose Xtr and Xte are training and testing data matrix,
# with each observation in a column
# train a PCA model, allowing up to 3 dimensions
M = fit(PCA, Xtr; maxoutdim=3)
# apply PCA model to testing set
Yte = transform(M, Xte)
# reconstruct testing observations (approximately)
Xr = reconstruct(M, Yte)
# group results by testing set labels for color coding
setosa = Yte[:,Xte_labels.=="setosa"]
versicolor = Yte[:,Xte_labels.=="versicolor"]
virginica = Yte[:,Xte_labels.=="virginica"]
# visualize first 3 principal components in 3D interacive plot
p = scatter(setosa[1,:],setosa[2,:],setosa[3,:],marker=:circle,linewidth=0)
scatter!(versicolor[1,:],versicolor[2,:],versicolor[3,:],marker=:circle,linewidth=0)
scatter!(virginica[1,:],virginica[2,:],virginica[3,:],marker=:circle,linewidth=0)
plot!(p,xlabel="PC1",ylabel="PC2",zlabel="PC3")
Core Algorithms
~~~~~~~~~~~~~~~~~
Expand Down

0 comments on commit b8075a6

Please sign in to comment.