-
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
Merged
sdenton4
merged 11 commits into
google-research:main
from
mschulist:feature/write-to-parquet
Aug 7, 2024
Merged
write to parquet #679
Changes from 10 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
f4f41a6
added write to parquet for classify
mschulist 33c3faf
whoops, pandas not polars
mschulist f3bf7ab
Merge branch 'main' into feature/write-to-parquet
mschulist b57de58
add print
mschulist e1e6b68
combine into single method
mschulist 552443b
Merge branch 'main' into feature/write-to-parquet
mschulist 32b7a12
fix rows list
mschulist da13b22
start test, definitely not finished...
mschulist bbc8e61
write test and fix errors in write
mschulist a273206
clean up writing code, add ePath ability
mschulist 4a66bb5
rename flush rows and remove old comments
mschulist File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,6 +25,9 @@ | |
import numpy as np | ||
import tensorflow as tf | ||
import tqdm | ||
import pandas as pd | ||
import os | ||
from etils import epath | ||
|
||
|
||
@dataclasses.dataclass | ||
|
@@ -180,45 +183,88 @@ def classify_batch(batch): | |
) | ||
return inference_ds | ||
|
||
def flush_rows( | ||
output_path: epath.Path, | ||
shard_num: int, | ||
rows: list[dict[str, str]], | ||
format: str, | ||
headers: list[str], | ||
): | ||
"""Helper method to write rows to disk.""" | ||
if format == 'csv': | ||
if shard_num == 0: | ||
with output_path.open('w') as f: | ||
f.write(','.join(headers) + '\n') | ||
with output_path.open('a') as f: | ||
for row in rows: | ||
csv_row = [ | ||
'{:.2f}'.format(row.get(h, '')) if isinstance(row.get(h, ''), np.float32) else row.get(h, '') | ||
for h in row | ||
] | ||
f.write(','.join(csv_row) + '\n') | ||
elif format == 'parquet': | ||
output_path.mkdir(parents=True, exist_ok=True) | ||
parquet_path = output_path / f'part.{shard_num}.parquet' | ||
pd.DataFrame(rows).to_parquet(parquet_path) | ||
else: | ||
raise ValueError('Output format must be either csv or parquet') | ||
|
||
def write_inference_csv( | ||
|
||
def write_inference_file( | ||
embeddings_ds: tf.data.Dataset, | ||
model: interface.LogitsOutputHead, | ||
labels: Sequence[str], | ||
output_filepath: str, | ||
output_filepath: epath.PathLike, | ||
embedding_hop_size_s: float, | ||
threshold: dict[str, float] | None = None, | ||
exclude_classes: Sequence[str] = ('unknown',), | ||
include_classes: Sequence[str] = (), | ||
shard_size: int = 1_000_000, | ||
): | ||
"""Write a CSV file of inference results.""" | ||
"""Write inference results.""" | ||
output_filepath = epath.Path(output_filepath) | ||
|
||
if str(output_filepath).endswith('.csv'): | ||
format = 'csv' | ||
elif str(output_filepath).endswith('.parquet'): | ||
format = 'parquet' | ||
else: | ||
raise ValueError('Output file must end with either .csv or .parquet') | ||
|
||
shard_num = 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]) | ||
row = [ | ||
ex['filename'].decode('utf-8'), | ||
'{:.2f}'.format(offset), | ||
label, | ||
logit, | ||
] | ||
f.write(','.join(row) + '\n') | ||
detection_count += 1 | ||
else: | ||
nondetection_count += 1 | ||
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 |
||
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] | ||
row = { | ||
headers[0]: ex["filename"].decode("utf-8"), | ||
headers[1]: np.float32(offset), | ||
headers[2]: label, | ||
headers[3]: np.float32(logit), | ||
} | ||
rows.append(row) | ||
if len(rows) >= shard_size: | ||
flush_rows(output_filepath, shard_num, rows, format, headers) | ||
rows = [] | ||
shard_num += 1 | ||
detection_count += 1 | ||
else: | ||
nondetection_count += 1 | ||
# write remaining rows | ||
flush_rows(output_filepath, shard_num, rows, format, headers) | ||
print('\n\n\n Detection count: ', detection_count) | ||
print('NonDetection count: ', nondetection_count) | ||
print('NonDetection count: ', nondetection_count) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Let's use a slightly more descriptive name, like
flush_inference_rows
.