In this assignment, you will get some practice building models and
interpreting their behavior. To do this, we will be using the NumPy and scikit-learn libraries. These are
standard numeric and machine learning Python libraries. To begin, as
usual: create a directory in your CSgit repo called hw6,
and in that directory, a file called hw6-writeup.txt. Then,
from the starter code repo, copy hw6-starter.py to
hw6.py.
In this assignment, we will be using the wine dataset included with scikit-learn. It is documented here. Documentation is a very powerful tool, especially in machine learning. Machine learning typically involves using a lot of functions and classes in a library, so reading the documentation is good practice for the future.
Install scikit-learn if you haven’t already. NumPy is a dependency of scikit-learn, so it will be installed with it. Use the following command (or your OS package manager, or a Python virtual environment manager):
pip install scikit-learn
If that worked, you should be able to run hw6.py file
without error – that is, you should be able to import numpy
and sklearn.datasets.
To learn more about NumPy, I suggest you look through this tutorial. Specifically, up to (but not including) shape manipulation. Shape manipulation is important, and we’ll deal with it later, but for now it’s not super important. Once you feel comfortable with NumPy, we can continue.
To begin with, it’s a good idea to understand how your data looks.
Implement the function dataset_summary. It takes a
dataset argument and returns nothing. For each feature, it prints the
minimum, maximum, median, mean, and standard deviation. NumPy has the
ability to compute all of these. Look through the documentation.
In the summary function, your data has a
data attribute that is a 2-dimensional array with all the,
well, data: each row has the data for one wine, and the columns
represent values for the features.
data.feature_names is a list of feature names; the index
of each corresponds to a column in data.data with the
values for that feature. To get the value for feature k in
row r, you can do data.data[r, k]. This
notation supports slicing; to understand how that works, compare to
regular Python lists: xs[5:12] represents the slice of
elements from index 5 to 11, and xs[:] is a slice of the
entire list.
For NumPy arrays, to get column k, you can use
data.data[:, k]. Note how that generalizes the
[r, k] notation: before the comma is just a colon, which
represents the slice of all rows, like regular Python slicing;
k represents column k.
To run the program and see the summary use the following command:
python3 hw6.py --summary
Compare your results with the documentation. They don’t label the columns for their statistics, but you should be able to match them up with your output.
Use dataset_summary to get a summary of the wine
dataset. Copy and paste the output into your writeup.
Your function should output statistics for each feature very similarly to this format:
========== feature_name:
min: 0.343424
max: 145.8
mean: 2.33634343242
median: 3.5650000000000002
std: 4.41400678934423
Now that we have our dataset ready, let’s train a model.
Find scikit-learn’s implementation of a k-nearest neighbors
classifier. Import it at the top of the file. In the if
statement that checks if args.model == ‘knn’, create a
k-nearest neighbors classifier and store it in the model variable. Your
script accepts a k argument which specifies the value of
that hyperparameter; you can access that with args.k to set
the number of neighbors used by your classifier.
Now you can actually train and evaluate the model. The
fit and predict functions handle training the
model and running the test set on it. Then the classification report
prints the proper statistics. To run the program with k-nearest
neighbors, run the following command:
python3 hw6.py --model knn
By default, k is 3, but it can be configured with the
k flag.
Run the program with k equal to 3, 5, and 7. In your
writeup, explain which one is best. Why do you think that’s “best”? Show
your results and explain your reasoning.
As we discussed, k-nearest neighbors is sensitive to scale. We should normalize our dataset.
Implement the min_max_normalize function. It should
perform the min-max normalization we discussed in class that is in the
slides – it just linearly maps the values for each feature into the
interval [0, 1]. The minimum and maximum should come from the training
set and should be used to normalize both the train and test set.
The idea is to take the raw values of a feature – which can be any size, well outside [0, 1] – and linearly squish them so the smallest value lands on 0, the largest lands on 1, and everything else falls in proportion in between:
Your implementation should not (directly) use any loops. The ideas here are (1) Python’s “batteries included” philosophy, and (2) “use the API”. NumPy is a large, old, foundational piece of software, and it is highly optimized. Also, you can assume it’s bug-free; it’s so widely used, and built on standard, well-tested algorithms, so that you can assume that the bugs have been beaten out of it.
(Usually when we think about software, being old is not considered a good thing. But in many cases, it’s very desirable. Old means it works.)
One piece of Python’s huge success is it has a very convenient C API for writing extension modules. This allows you to write very fast C code (or, any code binary-compatible with C code) that be accessed from Python, and which can access Python data structures.
In regular Python, if you did something like:
xs = [ 1.2, 3.4, -5.0, 3.141]
maximum = -float('inf')
for x in xs:
if x > maximum:
maximum = xor even just
xs = [ 1.2, 3.4, -5.0, 3.141]
m = max(xs)…the loops are pretty slow, because of Python’s dynamic, loose typing; it has to check the data type of each element in the list and appropriately handle encountering values for which the comparison is going to fail.
But if you do
xs = np.array([1.2, 3.4, -5])
xs.dtype
dtype('float64')
np.max(xs)then your list is more or less represented as a C array of 64-bit floats, and the loop for the maximum occurs at the C level without any typechecking overhead.
NumPy and the other big libraries we’ll use are all like this – they use industry-standard algorithms, and many, many people have worked on them for many, many years, and quite a lot of them are smarter than you. You can, and should, rely on them to be fast and correct.Instead, make use of NumPy’s functions and NumPy arrays. You should not use the scikit-learn implementation. The point is to practice using NumPy. If you use sources beside the NumPy tutorial above, please cite them in your writeup.
(NumPy is a huge and complex library; don’t feel discouraged if you can’t figure out how to do something – go ahead and ask me or classmates for help, or find other resources – and cite them. I do want to know what things you struggle with, and what you do to handle them.)
To run the program with normalization, use the
--normalize flag.
Run the program again with the same k values, but now
with normalization. In the writeup, discuss how the results compare to
the un-normalized models and explain the difference.
But there are different ways to scale data.
Re-do the above, now with the changes described below.
add a command-line switch --znormalize, just like
the existing --normalize.
add a branch analogous to the if args.normalize:
branch, but instead of calling min_max_normalize(), this
one calls a function called znormalize().
znormalize() works exactly like the existing
normalization function, but now it maps each data point to its
Z-score – that is, if μ is the mean of the values and σ the
standard deviation, the transformation is
\[ x→ (x - μ) / σ \]
Re-run your training and classification reports for the same
values of k. In your writeup, describe the results and how
they differ from the original normalization.
Which normalization does better? Why is it better? You don’t need to get deep into theory here – though if you have the stats background, please do – just describe as best you can how the geometry of the transformed points is “friendlier” for the kNN algorithm.)
Next, let’s look at the decision tree model.
Find scikit-learn’s implementation of a decision tree classifier.
Import it at the top of the file. In the if statement that
checks if args.model == ‘tree’, create a decision tree
classifier and store it in the model variable. Make sure to use entropy
as the splitting criterion and set the random_state to
0.
Run the program using a decision tree both with and without normalization. In your writeup, discuss the results of both. How does the difference compare to the difference for k-nearest neighbors? Why?
Finally, let’s look at a random forest.
Repeat the decision tree task, but with a random forest classifier.
Make sure to set random_state to 0.
In your writeup, discuss why the random forest performs differently than the individual decision tree. If a random forest is just a bunch of decision trees, why would it perform differently?
Don’t forget to push your code to CSgit!