Chapter 8 Example 1: A classification problem

Last update: Thu Oct 22 16:46:28 2020 -0500 (54a46ea04)

8.1 Code in Python

I will combine here R and Python code just to show how easy is integrating R and Python. First thing we have to do is loading the package rTorch. We do that in a chunk:

Then, we proceed to copy the standard Python code but in their own Python chunks. This is a very nice example that I found in the web. It explains the classic challenge of classification.

When rTorch is loaded, a number of Python libraries are also loaded, which enable us the immediate use of numpy, torch and matplotlib.

The next thing we do is setting a seed to make the example repeatable, in my machine and yours.

Then we generate some random samples.

And plot the original data for reference.

What follows is the definition of the model using a neural network and train the model. We set up the model:

Train the model:

Finally, we plot the results, by tracing the line that separates two classes, 0 and 1, which are both colored in the plot.

#> Final gradient descend: [Parameter containing:
#> tensor([[1.1277, 1.1242]], requires_grad=True), Parameter containing:
#> tensor([0.3226], requires_grad=True)]