Looking for answers without outsourcing to LLM
ยท Updated:Some examples of where i get limited by a specific programming language/framework’s syntax/particular way of doing things, and how I navigate it by trying to see if i can solve it myself based on what i know or good old internet search, (i.e. manually looking at links/posts) and learning a bit more in the process.
I know there is research now showing the impact of using LLMs on our brain, but to me, this is just how I want to do my work. I want to be involved.
Navigation
1
I want to get access to the subject_id within my Pytorch dataset. I know that
it is present in a dictionary for each row of my data.
(Pdb) eval_dataset
<__main__.Cardiomegaly object at 0x00000298DF1C8BC0>
(Pdb) dir(eval_dataset)
['__add__', '__class__', '__class_getitem__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__orig_bases__', '__parameters__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'df', 'img_dir', 'transform']
(Pdb) eval_dataset[0]
(tensor([....]]), tensor([0.]), {'subject_id': '10000032', 'study_id': np.int64(50414267)})
(Pdb) type(eval_dataset[0])
<class 'tuple'>
(Pdb) eval_dataset[0][0]
tensor([[[ 0.9988, 0.5878, 0.1939, ..., -0.0972, -0.1143, -0.1486],
[ 0.9817, 0.6392, 0.2796, ..., -0.1143, -0.1314, -0.0801],
[ 1.0331, 0.6906, 0.4166, ..., 0.0569, 0.0398, 0.0056],
...,
...,
[-1.5430, -1.6650, -1.7522, ..., -1.7696, -1.7696, -1.7696],
[-1.5430, -1.6302, -1.7522, ..., -1.8044, -1.8044, -1.8044],
[-1.5430, -1.6476, -1.7347, ..., -1.8044, -1.8044, -1.8044]]])
(Pdb) eval_dataset[0][1]
tensor([0.])
(Pdb) eval_dataset[0][2]
{'subject_id': '10000032', 'study_id': np.int64(50414267)}
And there I have it, so now collecting the subject_ids is a matter of:
(Pdb) subject_ids = [row[2]["subject_id"] for row in eval_dataset]
Python makes it easy to inspect objects and get things. Other languages, a bit trickier perhaps, but it’s possible, we have the good old printing!
2
I have an integer and i want to just run a loop that many times.
- I search for
for loop javascript - I pick the MDN link
I preferred MDN over w3schools since i am aware of the authority of MDN - similar to w3schools, of course for me, but just went with MDN.
3
I have a dataframe which is multi indexed and i want to each each unique combination of index columns data:
(Pdb) insurance_metrics
n tp tn fp fn accuracy precision recall f1 auc pr_auc
dataset insurance
eval_1_cardiomegaly.csv.gz Medicaid 14877.0 1816.0 9472.0 2897.0 692.0 0.758755 0.385317 0.724083 0.502977 0.826120 0.481929
Medicare 45393.0 8678.0 21264.0 13126.0 2325.0 0.659617 0.398000 0.788694 0.529033 0.772568 0.493489
...
I want to get access to the data for each unique combination of dataset and insurance":
insurance_metrics.index
MultiIndex([('eval_1_cardiomegaly.csv.gz', 'Medicaid'),
('eval_1_cardiomegaly.csv.gz', 'Medicare'),
('eval_1_cardiomegaly.csv.gz', 'No charge'),
Search query: “pandas selecting by index value”
Reading, https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#selection-by-label
The .loc attribute is the primary access method. The following are valid inputs: A single label, e.g. 5 or ‘a’ (Note that 5 is interpreted as a label of the index. This use is not an integer position along the index.).
A list or array of labels [‘a’, ‘b’, ‘c’].
A slice object with labels ‘a’:‘f’. Note that contrary to usual Python slices, both the start and the stop are included, when present in the index! See Slicing with labels.
A boolean array.
My brain goes. omg.
So, i start hacking around:
(Pdb) insurance_metrics.get(('eval_1_cardiomegaly.csv.gz', 'Medicaid'))
No dice.
Okay, I know, loc, and i know that i want to specify a tuple, since I have a MultiIndex:
(Pdb) insurance_metrics.loc(('eval_1_cardiomegaly.csv.gz', 'Medicaid'))
*** ValueError: No axis named ('eval_1_cardiomegaly.csv.gz', 'Medicaid') for object type DataFrame
(Pdb) insurance_metrics.loc[("eval_1_cardiomegaly.csv.gz", "Medicare")]
n 45393.000000
tp 8678.000000
tn 21264.000000
fp 13126.000000
fn 2325.000000
accuracy 0.659617
precision 0.398000
recall 0.788694
f1 0.529033
auc 0.772568
pr_auc 0.493489
Name: (eval_1_cardiomegaly.csv.gz, Medicare), dtype: float64
Okay, so i have what i needed. To automate it, i am just gonna use groupby:
(Pdb) items=[(d, i) for d, i in insurance_metrics.groupby(by=['dataset', 'insurance'])]
(Pdb) type(items[0])
<class 'tuple'>
(Pdb) items[0][0]
('eval_1_cardiomegaly.csv.gz', 'Medicaid')
(Pdb) items[0][1]
n tp tn fp fn accuracy precision recall f1 auc pr_auc
dataset insurance
eval_1_cardiomegaly.csv.gz Medicaid 14877.0 1816.0 9472.0 2897.0 692.0 0.758755 0.385317 0.724083 0.502977 0.82612 0.481929
Okay, so apparentely, groupby works with index columns too.
4
I have two dataframes, new_results and baseline_results.
I want to copy all the data from a baseline_results for a specific column value into new_results. In this case,
the column value is baseline_cardiomegaly.csv.gz for dataset column.
My trial and error attempts and how i got there:
(Pdb) new_results
Unnamed: 0 y_true y_pred prob_1 ... dataset gender race insurance
0 0 1 1 0.649867 ... eval_1_cardiomegaly.csv.gz M WHITE Medicare
... ... ... ... ... ... ... ... ... ...
[142698 rows x 11 columns]
```python
(Pdb) baseline_results
Unnamed: 0 y_true y_pred prob_1 ... dataset gender race insurance
0 0 0 0 0.057635 ... baseline_cardiomegaly.csv.gz M RECORD_NOT_FOUND RECORD_NOT_FOUND
[362281 rows x 12 columns]
Awfully bad attempts, without even thinking, one might say, hands typing, brain listening to music (perhaps from the muscle memory of yesterday):
(Pdb) new_results["baseline_cardiomegaly.csv.gz"] = baseline_results["baseline_cardiomegaly.csv.gz"]
*** KeyError: 'baseline_cardiomegaly.csv.gz'
(Pdb) new_results["baseline_cardiomegaly.csv.gz"] = baseline_results.loc("baseline_cardiomegaly.csv.gz")
*** ValueError: No axis named baseline_cardiomegaly.csv.gz for object type DataFrame
(Pdb) new_results["baseline_cardiomegaly.csv.gz"] = baseline_results.loc(["baseline_cardiomegaly.csv.gz"])
*** TypeError: unhashable type: 'list'
(Pdb) new_results["baseline_cardiomegaly.csv.gz"] = pd.Series(baseline_results.loc(["baseline_cardiomegaly.csv.gz"]))
*** TypeError: unhashable type: 'list'
(Pdb) baseline_results.loc(["baseline_cardiomegaly.csv.gz"])
*** TypeError: unhashable type: 'list'
(Pdb) baseline_results.loc(("baseline_cardiomegaly.csv.gz"))
*** ValueError: No axis named baseline_cardiomegaly.csv.gz for object type DataFrame
The above attempts are all my brain not considering the fact that I am choosing the value for a specific column and the value itself is not an index or a column name.
dataset is a column and that’s the column I must look up (not an index).
Once the brain has that updated context, I struggle with the exact syntax for filtering a bit:
(Pdb) new_results["baseline_cardiomegaly.csv.gz"] = baseline_results[baseline_results[dataset == "baseline_cardiomegaly..csv.gz"]]
*** NameError: name 'dataset' is not defined
(Pdb) new_results["baseline_cardiomegaly.csv.gz"] = baseline_results[baseline_results["dataset" == "baseline_cardiomegaly..csv.gz"]]
*** KeyError: False
(Pdb) new_results["baseline_cardiomegaly.csv.gz"] = baseline_results[baseline_results["dataset"] == "baseline_cardiomegaly.csv.gz"]
*** ValueError: Cannot set a DataFrame with multiple columns to the single column baseline_cardiomegaly.csv.gz
At this point I realize, what i am doing wrong, i have the selection correct, but i am trying to put in multiple columns and assign it to a single column,
so I need concat which I again struggle with the right syntax:
(Pdb) new_results = new_results.concat(baseline_results[baseline_results["dataset"] == "baseline_cardiomegaly.csv.gz"])
*** AttributeError: 'DataFrame' object has no attribute 'concat'
(Pdb) new_results = pd.concat(new_results, baseline_results[baseline_results["dataset"] == "baseline_cardiomegaly.csv.gz"])
*** TypeError: concat() takes 1 positional argument but 2 were given
(Pdb) new_results = pd.concat([baseline_results[baseline_results["dataset"] == "baseline_cardiomegaly.csv.gz"], new_results])
Okay finally i have it! Trial and error is my favorite way to learn, the brain needs to take the paths to the solution and there is a satisfaction I derive from that process:
(Pdb) new_results
Unnamed: 0 y_true y_pred prob_1 ... dataset gender race insurance
0 0 0 0 0.057635 ... baseline_cardiomegaly.csv.gz M RECORD_NOT_FOUND RECORD_NOT_FOUND
[362281 rows x 12 columns]
Okay, so I am training myself i think. I am my favorite agent.
5
I want the equivalent of ternary operator ? (in C or javascript) in Python. I have forgotten exactly how, but i know that
i can use if..else in list comprehension, so perhaps it works outside it too?
Let’s try:
>>> import random
>>> value = 1 if random.random() > 0.5 else 0
>>> value
0
>>> value = 1 if random.random() > 0.5 else 0
>>> value
0
>>> value = 1 if random.random() > 0.5 else 0
>>> value
1
yeah, it does.
of course, random.random() > 0.5 is an example of a conditional evaluation.
6
I want to access, feature-prep directory which is at the same level as utils, from inside a file inside utils. Basically:
- Traverse one directory up from
utils - Go down another directory,
feature-prep
(Pdb) Path(__file__) / "..//feature-prep"
WindowsPath('C:/Users/amits/work/github.com/amitsaha/ml-fairness-health/mywork/experiments/mimic-cxr/utils/common_experiment.py/../feature-prep')
(Pdb) import os
(Pdb) os.path.exists(Path(__file__) / "..//feature-prep")
False
(Pdb) os.path.exists(Path(__file__))
True
(Pdb) os.path.basename(Path(__file__))
'common_experiment.py'
(Pdb) os.path.dirname(Path(__file__))
'C:\\Users\\amits\\work\\github.com\\amitsaha\\ml-fairness-health\\mywork\\experiments\\mimic-cxr\\utils'
(Pdb) os.path.dirname(os.path.dirname(Path(__file__)))
'C:\\Users\\amits\\work\\github.com\\amitsaha\\ml-fairness-health\\mywork\\experiments\\mimic-cxr'
(Pdb) os.path.exists(os.path.dirname(os.path.dirname(Path(__file__)))
*** SyntaxError: '(' was never closed
(Pdb) os.path.exists(os.path.dirname(os.path.dirname(Path(__file__))))
True
(Pdb) os.path.exists(Path(os.path.dirname(os.path.dirname(Path(__file__)))) / "feature-prep")
True
(Pdb) os.path.exists(Path(os.path.dirname(os.path.dirname(Path(__file__)))) / "feature-prep")
7
> const userQueries = ["foo", "bar"];
undefined
> console.log(userQueries)
[ 'foo', 'bar' ]
undefined
> for (const item in userQueries) {
... console.log(item)
... }
0
1
undefined
> for (const idx, item in userQueries) {
for (const idx, item in userQueries) {
^^^
Uncaught SyntaxError: Missing initializer in const declaration
> for (const {idx, item} in userQueries) {
... console.log(item)
... {
... }
... }
undefined
undefined
undefined
> for (const item in Object.entries(userQueries)) {
... console.log(item)
... }
0
1
undefined
Then, i come across https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement when I search again and in the Google AI summary.
So, we have a for..of !? (why???)
> for (const item of userQueries) {
... console.log(item)
... }
foo
bar
undefined
8
Needed to upgrade some projects to tailwind v4 from v3.
Used Github Copilot AI to see if i can get it do it, took me on a wild ride, with no luck and it appears to have stuck.
Then it hit me, let’s try https://tailwindcss.com/docs/upgrade-guide and the command worked like a charm.
9
I wanted to find the row which has the minimum and maximum value for recall in this dataframe:
(Pdb) current_group_results
n tp tn fp fn accuracy precision recall f1 auc pr_auc
race
AMERICAN INDIAN 4.0 0.0 1.0 0.0 3.0 0.250000 0.000000 0.000000 0.000000 0.333333 0.805556
ASIAN 27.0 1.0 21.0 1.0 4.0 0.814815 0.500000 0.200000 0.285714 0.754545 0.379762
BLACK 145.0 4.0 113.0 11.0 17.0 0.806897 0.266667 0.190476 0.222222 0.763441 0.299849
HISPANIC 66.0 3.0 55.0 1.0 7.0 0.878788 0.750000 0.300000 0.428571 0.757143 0.430238
OTHER 81.0 9.0 55.0 4.0 13.0 0.790123 0.692308 0.409091 0.514286 0.822804 0.660273
RECORD_NOT_PRESENT 121.0 2.0 111.0 2.0 6.0 0.933884 0.500000 0.250000 0.333333 0.853982 0.417907
WHITE 536.0 31.0 398.0 16.0 91.0 0.800373 0.659574 0.254098 0.366864 0.825097 0.581051
(Pdb) type(current_group_results)
<class 'pandas.core.frame.DataFrame'>
First attempt, just to check if i remembered it correctly:
(Pdb) current_group_results.minidx
*** AttributeError: 'DataFrame' object has no attribute 'minidx'
I had a vague recollection that there is a method named in that manner, so i do a dir:
(Pdb) dir(current_group_results)
['...
'idxmax', 'idxmin', ...]
Once i spotted those, I was curious if they would also work on the series:
(Pdb) type(current_group_results["recall"])
<class 'pandas.core.series.Series'>
Let’s try it:
(Pdb) current_group_results["recall"]
AMERICAN INDIAN 0.000000
ASIAN 0.200000
BLACK 0.190476
HISPANIC 0.300000
OTHER 0.409091
RECORD_NOT_PRESENT 0.250000
WHITE 0.254098
Name: recall, dtype: float64>
(Pdb) current_group_results["recall"].idxmax()
'OTHER'
(Pdb) current_group_results["recall"].idxmin()
'AMERICAN INDIAN'
We can get the max and min values as well:
(Pdb) current_group_results["recall"]["OTHER"]
np.float64(0.4090909090909091)
(Pdb) current_group_results["recall"]["AMERICAN INDIAN"]
np.float64(0.0)
10
I want to filter a pandas dataframe rows by combining two filters/conditions. I have done this many times, but everytime without giving myself a chance, i have had to search or ask an LLM for the exact syntax.
This time, I decided not to outsource.
I got it by brute force and now i know i will likely remember this:
(Pdb) retraining_dataset[retraining_dataset[group] == min_recall_category]
Unnamed: 0 dicom_id subject_id study_id Cardiomegaly split race gender insurance
..
[704 rows x 9 columns]
(Pdb) retraining_dataset[retraining_dataset[group] == min_recall_category && retraining_dataset[Cardiomegaly]]
*** SyntaxError: invalid syntax
(Pdb) retraining_dataset[retraining_dataset[group] == min_recall_category & retraining_dataset[Cardiomegaly]]
*** NameError: name 'Cardiomegaly' is not defined
(Pdb) retraining_dataset[retraining_dataset[group] == min_recall_category & retraining_dataset['Cardiomegaly']]
*** TypeError: Cannot perform 'rand_' with a dtyped [float64] array and scalar of type [bool]
(Pdb) retraining_dataset[(retraining_dataset[group] == min_recall_category) && (retraining_dataset['Cardiomegaly'])]
*** SyntaxError: invalid syntax
(Pdb) retraining_dataset[(retraining_dataset[group] == min_recall_category) && (retraining_dataset['Cardiomegaly']==True)]
*** SyntaxError: invalid syntax
(Pdb) retraining_dataset[(retraining_dataset[group] == min_recall_category) & (retraining_dataset['Cardiomegaly']==True)]
WORKS
So, the key is:
- Individual conditions in parentheses
- Combine them by
&(or|(foror)
11
I have a dataframe:
(Pdb) subgroup_results["metrics_race"]
n tp tn fp fn accuracy precision recall f1 auc pr_auc
dataset race
eval_1_cardiomegaly.csv.gz AMERICAN INDIAN 179.0 33.0 60.0 60.0 26.0 0.519553 0.354839 0.559322 0.434211 0.560169 0.354330
ASIAN 2779.0 297.0 1720.0 464.0 298.0 0.725801 0.390276 0.499160 0.438053 0.738761 0.391143
..
eval_2_cardiomegaly.csv.gz AMERICAN INDIAN 43.0 1.0 26.0 10.0 6.0 0.627907 0.090909 0.142857 0.111111 0.424603 0.204916
ASIAN 738.0 67.0 475.0 109.0 87.0 0.734417 0.380682 0.435065 0.406061 0.746197 0.412286
..
eval_3_cardiomegaly.csv.gz AMERICAN INDIAN 14.0 5.0 5.0 2.0 2.0 0.714286 0.714286 0.714286 0.714286 0.775510 0.705195
ASIAN 101.0 22.0 33.0 38.0 8.0 0.544554 0.366667 0.733333 0.488889 0.618310 0.467499
..
eval_4_cardiomegaly.csv.gz AMERICAN INDIAN 6.0 0.0 4.0 2.0 0.0 0.666667 0.000000 NaN 0.000000 NaN NaN
ASIAN 71.0 11.0 41.0 16.0 3.0 0.732394 0.407407 0.785714 0.536585 0.775689 0.379455
..
RECORD_NOT_FOUND 375.0 41.0 264.0 46.0 24.0 0.813333 0.471264 0.630769 0.539474 0.824367 0.413750
WHITE 1704.0 204.0 978.0 352.0 170.0 0.693662 0.366906 0.545455 0.438710 0.713397 0.345630
My end goal is i want to extract the recall values per dataset, preserving the category specific data, and for my purposes I want an array of these dicts,
one element per dataset - i want to ensure that the array is ordered i.e. eval_1 must come before eval_2 and so on.
.. to be completed ..
12
I have used AI to create a matplotlib figure for me based on some text instructions, because i don’t find it fun to write programs to generate matplotlib lib figures. I don’t find it fun in expanded version means:
- My goal here is to get a visual description of my text specification quick so that i can iterate over it
- Hence, i don’t want to look up matplotlib documentation for figuring out how to draw rectangles/patches, etc
- I have always found matplotlib design hard. It took me lots of solid sleuthing to get over the global design of
plt,axand so on. And I attribute a lot of learning that happened to me working on my “Doing Math with Python” book and i haven’t tried to learn any of it again for the last 12 years at least - Also, and perhaps this is important - i am generating it because i know that if i need to go and tweak the script to suit my needs, i know enough matplotlib to find my way around - the learning that happened in (3).
- So, basically, if i need to figure it out, i can. This is not completely something I don’t know or have a hang of.
- Hence, I generate.
Okay, so I have this snippet, which I wrote - replacing the hardcoded figure names that was generated:
plt.savefig(
f"{__name__}.pdf",
bbox_inches="tight"
)
plt.savefig(
f"{__name__}.png",
dpi=600,
bbox_inches="tight"
)
My intention is that i want the figures to be named after my file name, but the files are being named as:
-a---- 31/08/2026 9:06 AM 25330 __main__.pdf
-a---- 31/08/2026 9:06 AM 582014 __main__.png
So obviously, i have made the mistake of assuming __name__ points to the file name. So:
- The first time i saw this, the file names being
__main__my brain assumed that the f-string expansion is not correct - and the fault in thinking that is that i am equating,__name__to__main__. - As i was starting to write this post, the first thing that i occurred to me, yes, I should use
__file__but the fallacy in (1) was still not corrected - And now finally, when I just was finishing point (1), i realized, I used
__name__here because I have often written__name__==__main__- i learned about__name__in some detail 15 years back, and I have not forgotten any of it.
So, this is the code that achieves what i wanted:
plt.savefig(
f"{os.path.basename(__file__).split(".")[0]}.pdf",
bbox_inches="tight"
)
plt.savefig(
f"{os.path.basename(__file__).split(".")[0]}.png",
dpi=600,
bbox_inches="tight"
)
I didn’t query LLM or search the internet, I didn’t have to. That is because I have been coding in Python in one form or the other for the last 15 years. And the grunt work, the trial and error involved in learning things has stayed with me, and I just needed to allow myself the time to retrieve all of that i already know.
The work of understanding - is what I am reflecting on and understanding a system is essentially a way to know how to operate a system.
13
https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html
>>> X
array([[1.0000e+04, 1.0000e-01, 2.0000e-01],
[1.0000e+04, 9.1000e-02, 1.4000e-02],
[1.0001e+04, 1.1100e-01, 1.1100e-01],
[1.0003e+04, 1.1000e-01, 2.2100e-01]])
>>> y=[0, 0, 1, 1]
>>> skf=StratifiedKFold(n_splits=2)
>>> folds = [(train_idx, test_idx) for i, (train_idx, test_idx) in enumerate(skf.split(X,y))]
# 50% of 0 and 1 in each split
>>> folds[0]
# [0, 0, 1, 1]
(array([1, 3]), array([0, 2]))
>>> folds[1]
# [0, 0, 1, 1]
(array([0, 2]), array([1, 3]))
However, we see that the subject ID 1.0000e+04 has leaked into the test set:
# train set
>>> X[1]
array([1.0e+04, 9.1e-02, 1.4e-02])
>>> X[3]
array([1.0003e+04, 1.1000e-01, 2.2100e-01])
# test/validation set
>>> X[0]
array([1.e+04, 1.e-01, 2.e-01])
>>> X[2]
array([1.0001e+04, 1.1100e-01, 1.1100e-01])
We don’t want to have the subject ID repeated between the train and the test set while also preserving the class/label balance.
So, what shall we do?
So, this is where my brain wants to take short cuts:
- I want to ask AI chat
- I want to at least do a good old internet search
I have already cursorily looked at the scikit learn model selection reference: https://scikit-learn.org/stable/api/sklearn.model_selection.html - none of them appear to give me a straight and fast answer to take me out of this unknown I am finding myself in.
I have implemented this or I think i have done the same in another experiment, where I used AI’s help to simply copy paste the snippet it gave me. Hence I don’t know what I did there.
In fact, i probably used
StratifiedGroupKFoldthere, but now looking at the reference documentation now, i can’t help how it might have helped me there. So, may be the code works, but it isn’t doing what i want it to do as this is another example of what happens to my brain and learning when I don’t take the time to understand what I am doing.
Looking at LeaveOneGroupOut. The documentation says:
“Provides train/test indices to split data such that each training set is comprised of all samples except ones belonging to one specific group. Arbitrary domain-specific group information is provided as an array of integers that encodes the group of each sample”
14
I wanted to do some updates to the code and website for doing math with python: https://doingmathwithpython.github.io/code-and-solutions-refresh.html. It has been a good solid 10 years since I had touched the code and 3 years since i touched the website. My body memory/muscle memory of it all - was very weak/non-existent.
While updating the code, I first had to understand the issue a user had reported me to. While updating the website I had to first remember the restructured text formatting, the publishing workflow, etc. I used a combination of AI tools and manual effort to achieve the following:
- Create a new version of the code that didn’t depend on the 3rd party service
- Update the website with the new blog post
- Update the publishing workflow to use CI (github actions) so that I don’t have to manually do it
For (1), the key requirement was that I needed to give the reader a way to access weather forecast data that they can download. I looked at the open weather map updated API and it all just looked too complicated for me to suggest the reader to use, plus I wanted some kind of “control” over how the data format/availability worked. So, I used Google’s AI studio to use the Google maps platform API to build a custom web application for it. This was 100% vibe coded. It works.
Then, I wanted to write the updated code, for that I referred to the existing solutions and the Python standard library’s csvfile documentation and updated the code manually. No AI was used in this process - of understanding the previous error, figuring out why the code was breaking and then fixing it. I noticed a friction, a resistance to need to again get my brain into a whole different area - and I didn’t give in - i didn’t give in to the resistance and “used AI”. I persisted since I had set an intention to do it manually.
For (2) I noticed the same friction when writing restructured text blog posts, and had the urge to “ask AI” to get pelican to use mardkdown, since that’s what i write most my blog posts/content now, but I persisted, i opened the restructured text reference and I coded it. I had a few problems, in hunting down anonymoous hyperlinks (if you know you know!) - that was a blast from the past - when I did all these fixes manually - and that has stayed with me, in my memory, but I sorted them all manually. Once again, I had set an intention to do it manually.
For (3), I didn’t want to deal with the CI stuff, so i let “AI” do it.
After my analysis in https://echorand.me/posts/learning-and-current-software-development/ - i am slowly deciding what I want to be involved in - and one way I am doing that based on my primary objective - here my primary objective was to fix up the code and publish a blog post sharing the updates and i did both of that manually. Getting access to the data and making it available to my readers and fixing up CI workflow were not my primary goals, so I let “AI” do it.
15
This is different from all the above tips, since here I am trying to understand a code that I used LLM to generate. I used LLM to generate this
piece of code for creating a decision tree using scikit-learn. I had generated it because I was in a rush - which is I have realized most of my
outsourcing tends to happen. Once a human being, for example, me knows that there is a quicker/easier way to do it, i have to try really hard to
do it the hard way. Hence, before I first tried to learn how the generated code was working, I manually first learned what I needed to know by writing a decision tree
by following the documentation and good old internet searches. (See code and gvim as
my editor with no AI support.
Now that I have fairly good idea of how it all works and is implemented due to me going through that disciplined process of not outsourcing any of my thinking to LLM, I wanted to better understand the generated code.
I get most of it, I simplify it first, write my own comments and then a specific piece of code stands out that i don’t follow.
def leaf_counts(assigned_leaves, error_targets):
"""Exact missed/sepsis counts for each leaf id in `assigned`."""
counts = {}
for leaf_id, members in assigned_leaves.groupby(assigned_leaves):
missed = int(error_targets.loc[members.index].sum())
counts[int(leaf_id)] = (missed, int(len(members)))
return counts
From my first reading I get what it’s trying to do, but i don’t really get how it is doing it. I have used groupby() for various things, but this usage
of groupby feels unfamiliar to me, since it is a Series of int-like values.
So, I insert import pdb; pdb.set_trace() just after counts and i see this:
(Pdb) assigned
131 4
142 11
162 10
240 11
257 4
..
28741 10
28757 10
28766 4
28799 10
28847 10
Name: leaf_id, Length: 621, dtype: int64
(Pdb) assigned.value_counts(normalize=True)
leaf_id
4 0.481481
10 0.257649
11 0.173913
14 0.041868
3 0.020934
7 0.016103
6 0.004831
13 0.003221
(Pdb) type(assigned)
<class 'pandas.core.series.Series'>
Looking around the code, I see, that the Series has an index set to the element IDs, so basically what this series is a collection of leaf indices, with the index
being the element ID, sort of like a hash table implemented using a linked list, where the key is the leaf id and the list contains all the element IDs that end up in that
leaf. Okay cool! But here’s the thing, I got this intuitive idea by experimenting with a demo Series, as follows:
>>> import pandas as pd
>>> demo_series = pd.Series([1, 2, 6, 6, 1], index=[1, 2, 3, 4, 6])
The series is basically this using my hash table/linked list analogy:
1 -> [1, 6]
2 -> [2]
6 -> [3, 4]
And so now when we do the groupby() on this print out the element and the index, we get this:
>>> for i, j in demo_series.groupby(demo_series):
... print(i, j.index)
...
1 Index([1, 6], dtype='int64')
2 Index([2], dtype='int64')
6 Index([3, 4], dtype='int64')
So, this is how I end up understanding this code. Abstractions are great, and I could have easily glossed over the usage of groupby because oh yes i know it, but if i hadn’t done this detour, I would have had no clue really!
And I could have asked LLM to explain to me that code, but where’s the fun in that?