…
…
Write a k nearest neighbors model yourself on 200 fictional student records from one course; split training and test groups, build an experiment table with k and scaling, choose the best setting with caution, build a "suggest tutoring, no suggestion, leave to advisor" rule from the vote share, and explain the result to Elena.
The term is about to start. A course coordinator has brought Elena a question: "Which students should we offer tutoring?" She has the records of last term's 200 students (grades.csv, fictional sample data): weekly study hours, attendance percentage, homework score, and whether the student passed the course. The idea is the same as in lesson 7: look at the past students who are most similar to a new student; if most of them failed, suggest tutoring for this student.
In this project you will write from scratch the model you ran in the degistir blocks of lessons 7 and 8: distance, neighbors, voting, scaling, and the experiment table. At the end, your own code will produce this table on 60 test students:
Outputk [1, 3, 5, 7, 9, 15, 25]
Raw [52, 53, 48, 48, 48, 47, 44]
Scaled [56, 53, 51, 50, 50, 48, 48]The table is a starting point, not a decision. You will turn the prediction into a suggestion rule, count what kind of mistakes the rule makes, and write Elena a note in your own sentences: which setting, which mistake is more expensive, and who should keep the decision?
| Step | What you will do |
|---|---|
| 1 | Read the records and see the classes and the ranges of the features |
| 2 | Split training and test groups and write the distance function with divisors |
| 3 | Write the functions that find neighbors and predict by majority vote |
| 4 | See the scale problem and compute the divisors from the training group |
| 5–6 | Count the correct ones on the test students and build the k and scale experiment table |
| 7 | Choose the best setting and read the result with caution |
| 8 | Build the "suggest tutoring, no suggestion, leave to advisor" rule from the vote share |
| 9 | Count the mistakes and write your comment to Elena |
Lessons used: data, feature, label (5); nearest neighbor, distance, and "leave it to a person when you are not sure" (7); k, majority vote, vote share, scaling, and choosing a setting with an experiment table (8).
How to work: The nine cells share one session: the distance you write in step 2, neighbors and predict in step 3, and scaled_divisors in step 4 are used in later cells. The lines that read the file and print the results are ready; the comments say what to do, and where it says ___ you write the code. Run the cell, compare your output with the "Show expected output" area, then press Check. Do not type the results by hand; the checks also try your functions on other students and other k values. The records are fictional; real student grades are personal data, such a system can only be built within the institution's rules, and a person always makes the final decision.
What you'll do
Required topics
grades.csvDownload file
Reading file…
Code cells are for members
You can read the steps. Sign up free to run the code, complete the steps and save your progress.
Your course coordinator has a request for Elena: at the start of term, which students should be offered tutoring? She has last term's records for 200 students in grades.csv (fictional sample data). Each row has three features: weekly study hours, attendance percentage, homework score. There is one label: did the student pass the course (1) or fail (0)?
The idea is the same as in lesson 7: look at the past students who are most similar to a new student; if most of them failed, suggest tutoring for this student. One warning up front: the model does not label anyone as "will fail", it only prepares a list of suggestions. We will talk about why a person makes the final decision at the end.
The reading lines are ready: each student goes into the students list as ([hours, attendance, homework], passed). First get to know the data: how many students passed, and what range does each feature cover? The ranges matter, because the scale problem you saw in lesson 8 comes from exactly here.
This step's code cell is for members.Sign up free
Which students will we try the model on? In lesson 8, Elena set 12 questions aside; here we do the same. The rows in the file are already in mixed order. The first 140 students are
Code cells are for members
You can read the steps. Sign up free to run the code, complete the steps and save your progress.
Next, the distance function. We generalize the distance from lesson 7 by one step: we divide the absolute difference in each position by that position's divisor and add them up. With divisors [1, 1, 1] this is exactly the raw distance from lesson 7; in step 4 we will change the divisors to do scaling. If you write the function correctly once, you can use the same code for both experiments.
Our example student is Ethan: he studies 4 hours a week, attends 92 percent of classes, and has a homework average of 75. Compute Ethan's distance to the first training student in both orders and see that it comes out the same.
This step's code cell is for members.Sign up free
Now we build the k nearest neighbors model; it does the same job as the degistir block in lesson 8, this time with your own functions.
neighbors(new, k, divisor) should build a (distance, passed) pair for every training student, sort these pairs from smallest to largest with sorted, and return the first k. Because the first element of each pair is the distance, sorted orders them by distance; if distances are equal it looks at the second element (passed), so the result is the same on every run.
predict(new, k, divisor) counts one vote for each of these k neighbors, using its own passed value. The value with the most votes is the prediction; the function also returns the vote share (the winner's votes / k). The vote share is the rough confidence signal you saw in lesson 8.
In the output, look at the results for Ethan with k = 1, 3, 5. For now we use the raw distance.
This step's code cell is for members.Sign up free
Go back to the ranges from step 1: study hours run from 0 to 19, attendance from 42 to 100, homework score from 28 to 100. In the raw distance, a 1-hour difference in study time and a 1-point difference in attendance count with the same weight. Yet the gap between studying 4 hours and 13 hours a week (9) is a big one, while 9 points of attendance is a small wobble. In the raw calculation the voice of study hours is barely heard: Ethan's neighbors are students whose attendance and homework look like his, and how many hours they study hardly matters.
You saw the fix in lesson 8: scaling. Divide each feature by its largest value in the archive. The divisors are computed from the training group, not the test group: the model should not have seen the test students, and neither should the divisors.
Build the scaled_divisors list, then look again at Ethan's neighbors and prediction. Did the prediction change? Which feature now has more say?
This step's code cell is for members.Sign up free
We cannot say which setting is good by looking at a single student; we do not even know Ethan's real outcome. We will measure the settings on the 60 test students whose outcome we know but the model has never seen.
correct_count(k, divisor) should make a prediction for each test student, count it if the prediction matches the real outcome (passed), and return the count. predict returns two values; here we look only at the first, the predicted outcome.
The output will show the raw and scaled results for k = 1 side by side. In lesson 9 we will call this number accuracy; for now we just say "how many of the 60 are correct".
This step's code cell is for members.Sign up free
Now you build the experiment table from lesson 8 with your own data. There are seven k values: 1, 3, 5, 7, 9, 15, 25. For each one, compute the raw and scaled correct counts and write them in order into two lists: raw_row and scaled_row.
All of them are odd numbers, because there are only two classes here (passed, failed): when an odd number of neighbors vote, a tie cannot happen.
When you read the table, ask two questions. First: does scaling help at every k? Second: what happens as k grows? In lesson 8 we saw a large k lose to the far-away, crowded class. In this archive the two classes are almost equal (of the 140 training students, 66 passed and 74 failed), so the drop will not be as sharp as in lesson 8; still, as k grows, far-away students who hardly resemble the question start to vote too. In the test group, 45 of the 60 students passed and 15 failed; finding those 15 who failed is the real job of this project.
This step's code cell is for members.Sign up free
We put the 14 settings from the table into the settings list as (correct count, k, "raw" or "scaled") tuples. In tuples, max looks at the first element first, that is, the correct count.
You will make two choices. The first is best: the one that gets the most right among all settings. The second is best_voted: the one that gets the most right among settings where k is at least 3. Why a second choice? With k = 1 a single neighbor votes and the vote share is always 1/1; the model says "I'm sure", but that is not information. In the next step we will leave the question to a person when the majority is weak, and for that the vote share needs to say something.
When you read the result, remember the warning from lesson 8: 60 students is few. A difference of a few students could have switched places if we had picked another 60. This table is enough to say "scaling is good on this data, a very large k is bad"; it is not enough to say "k = 1 is surely the best". There is one more thing: because we chose the setting by looking at the test students, these numbers show the model's success on new students a bit too optimistically. You will see why in lesson 11.
This step's code cell is for members.Sign up free
The model now gives a prediction; what the coordinator wants is a suggestion. You will write the rule that turns the prediction into three decisions. We use the scaled divisors, because the table supported them.
1. If the vote share is below the threshold: "leave to advisor". The neighbors are split; the model is not sure, and a person should talk to the student.
2. Otherwise, if the prediction is 0 (will fail): "suggest tutoring".
3. Otherwise: "no suggestion".
The ready code runs the rule on the test students with k = 3 and k = 5 and a threshold of 0.8, and counts how many students inside each decision actually failed and how many passed. That way you see the mistakes by name:
Compare the two k values. Which one leaves more work to the advisor, which one makes more mistakes? Deciding which mistake is more expensive here is your job.
This step's code cell is for members.Sign up free
In the last step you prepare a short note for Elena. The setting: k = 5, scaled, vote share threshold 0.8. We chose this setting because it leaves fewer students to the advisor than k = 3; the price is a few mistakes.
First compute three numbers with code: unnecessary (offered tutoring but passed), missed (told no suggestion but failed) and to_advisor (students left to the advisor). Do not type the numbers by hand; count them by running the advice function from step 8 on the test students.
Then write the comment text in your own sentences (at least 25 words). Answer these three questions:
This step's code cell is for members.Sign up free