-
Notifications
You must be signed in to change notification settings - Fork 40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
write to parquet #679
write to parquet #679
Changes from 9 commits
f4f41a6
33c3faf
f3bf7ab
b57de58
e1e6b68
552443b
32b7a12
da13b22
bbc8e61
a273206
4a66bb5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,6 +25,8 @@ | |
import numpy as np | ||
import tensorflow as tf | ||
import tqdm | ||
import pandas as pd | ||
import os | ||
|
||
|
||
@dataclasses.dataclass | ||
|
@@ -181,7 +183,7 @@ def classify_batch(batch): | |
return inference_ds | ||
|
||
|
||
def write_inference_csv( | ||
def write_inference_file( | ||
embeddings_ds: tf.data.Dataset, | ||
model: interface.LogitsOutputHead, | ||
labels: Sequence[str], | ||
|
@@ -190,35 +192,78 @@ def write_inference_csv( | |
threshold: dict[str, float] | None = None, | ||
exclude_classes: Sequence[str] = ('unknown',), | ||
include_classes: Sequence[str] = (), | ||
row_size: int = 1_000_000, | ||
format: str = 'parquet', | ||
): | ||
"""Write a CSV file of inference results.""" | ||
"""Write inference results.""" | ||
|
||
if format != 'parquet' and format != 'csv': | ||
raise ValueError('Format must be either "parquet" or "csv"') | ||
|
||
if format == 'parquet': | ||
if output_filepath.endswith('.csv'): | ||
output_filepath = output_filepath[:-4] | ||
if not output_filepath.endswith('.parquet'): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This second-guessing of the user-intention from the extension and format args is a bit cumbersome. Maybe we should get the extension from the output file and use that instead of an arg? (and complain if it's not one of our accepted types.) Then we would have:
which saves an argument and ~12 lines of code. |
||
output_filepath += '.parquet' | ||
os.mkdir(output_filepath) | ||
if format == 'csv': | ||
if output_filepath.endswith('.parquet'): | ||
output_filepath = output_filepath[:-8] | ||
if not output_filepath.endswith('.csv'): | ||
output_filepath += '.csv' | ||
|
||
parquet_count = 0 | ||
rows = [] | ||
|
||
inference_ds = get_inference_dataset(embeddings_ds, model) | ||
|
||
detection_count = 0 | ||
nondetection_count = 0 | ||
with open(output_filepath, 'w') as f: | ||
# Write column headers. | ||
headers = ['filename', 'timestamp_s', 'label', 'logit'] | ||
f.write(', '.join(headers) + '\n') | ||
for ex in tqdm.tqdm(inference_ds.as_numpy_iterator()): | ||
for t in range(ex['logits'].shape[0]): | ||
for i, label in enumerate(labels): | ||
if label in exclude_classes: | ||
continue | ||
if include_classes and label not in include_classes: | ||
continue | ||
if threshold is None or ex['logits'][t, i] > threshold[label]: | ||
offset = ex['timestamp_s'] + t * embedding_hop_size_s | ||
logit = '{:.2f}'.format(ex['logits'][t, i]) | ||
if format == 'csv': | ||
f = open(output_filepath, 'w') | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's good to use the |
||
headers = ['filename', 'timestamp_s', 'label', 'logit'] | ||
# Write column headers if CSV format | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seems like this comment can be deleted now |
||
if format == 'csv': | ||
f.write(','.join(headers) + '\n') | ||
for ex in tqdm.tqdm(inference_ds.as_numpy_iterator()): | ||
for t in range(ex['logits'].shape[0]): | ||
for i, label in enumerate(labels): | ||
if label in exclude_classes: | ||
continue | ||
if include_classes and label not in include_classes: | ||
continue | ||
if threshold is None or ex['logits'][t, i] > threshold[label]: | ||
offset = ex['timestamp_s'] + t * embedding_hop_size_s | ||
logit = ex['logits'][t, i] | ||
if format == 'parquet': | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe simpler: Write a helper function This also helps with the csv file handling; you just open the file and write to it when you're flushing the data to disk. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks! That make it SO much cleaner |
||
row = { | ||
headers[0]: ex["filename"].decode("utf-8"), | ||
headers[1]: offset, | ||
headers[2]: label, | ||
headers[3]: logit, | ||
} | ||
rows.append(row) | ||
if len(rows) >= row_size: | ||
tmp_df = pd.DataFrame(rows) | ||
tmp_df.to_parquet(f'{output_filepath}/part.{parquet_count}.parquet') | ||
parquet_count += 1 | ||
rows = [] | ||
elif format == 'csv': | ||
row = [ | ||
ex['filename'].decode('utf-8'), | ||
'{:.2f}'.format(offset), | ||
label, | ||
logit, | ||
'{:.2f}'.format(logit), | ||
] | ||
f.write(','.join(row) + '\n') | ||
detection_count += 1 | ||
else: | ||
nondetection_count += 1 | ||
detection_count += 1 | ||
else: | ||
nondetection_count += 1 | ||
# write remaining rows if parquet format | ||
if format == 'parquet' and rows: | ||
tmp_df = pd.DataFrame(rows) | ||
tmp_df.to_parquet(f'{output_filepath}/part.{parquet_count}.parquet') | ||
if format == 'csv': | ||
f.close() | ||
print('\n\n\n Detection count: ', detection_count) | ||
print('NonDetection count: ', nondetection_count) | ||
print('NonDetection count: ', nondetection_count) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A bit cleaner: