Search is not available for this dataset
repo_id
stringlengths 12
110
| file_path
stringlengths 24
164
| content
stringlengths 3
89.3M
| __index_level_0__
int64 0
0
|
---|---|---|---|
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/pyplots/tracker_binary.py | import matplotlib.pyplot as plt
import torch
import torchmetrics
N = 10
num_updates = 10
num_steps = 5
w = torch.tensor([0.2, 0.8])
target = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
preds = lambda it: (it * torch.randn(100)).sigmoid()
confmat = torchmetrics.ConfusionMatrix(task="binary")
roc = torchmetrics.ROC(task="binary")
tracker = torchmetrics.wrappers.MetricTracker(
torchmetrics.MetricCollection(
torchmetrics.Accuracy(task="binary"),
torchmetrics.Recall(task="binary"),
torchmetrics.Precision(task="binary"),
confmat,
roc,
)
)
fig = plt.figure(layout="constrained", figsize=(6.8, 4.8), dpi=500)
ax1 = plt.subplot(2, 2, 1)
ax2 = plt.subplot(2, 2, 2)
ax3 = plt.subplot(2, 2, (3, 4))
for step in range(num_steps):
tracker.increment()
for _ in range(N):
tracker.update(preds(step), target(step))
# get the results from all steps and extract for confusion matrix and roc
all_results = tracker.compute_all()
confmat.plot(val=all_results[-1]["BinaryConfusionMatrix"], ax=ax1)
roc.plot(all_results[-1]["BinaryROC"], ax=ax2)
scalar_results = [{k: v for k, v in ar.items() if isinstance(v, torch.Tensor) and v.numel() == 1} for ar in all_results]
tracker.plot(val=scalar_results, ax=ax3)
fig.show()
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/pyplots/collection_binary_together.py | import matplotlib.pyplot as plt
import torch
import torchmetrics
N = 10
num_updates = 10
num_steps = 5
w = torch.tensor([0.2, 0.8])
target = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
preds = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
collection = torchmetrics.MetricCollection(
torchmetrics.Accuracy(task="binary"),
torchmetrics.Recall(task="binary"),
torchmetrics.Precision(task="binary"),
)
values = []
fig, ax = plt.subplots(1, 1, figsize=(6.8, 4.8), dpi=500)
for step in range(num_steps):
for _ in range(N):
collection.update(preds(step), target(step))
values.append(collection.compute())
collection.reset()
collection.plot(val=values, ax=ax, together=True)
fig.tight_layout()
fig.show()
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/pyplots/binary_accuracy_multistep.py | import matplotlib.pyplot as plt
import torch
import torchmetrics
N = 10
num_updates = 10
num_steps = 5
w = torch.tensor([0.2, 0.8])
target = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
preds = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
fig, ax = plt.subplots(1, 1, figsize=(6.8, 4.8), dpi=500)
metric = torchmetrics.Accuracy(task="binary")
values = []
for step in range(num_steps):
for _ in range(N):
metric.update(preds(step), target(step))
values.append(metric.compute()) # save value
metric.reset()
metric.plot(values, ax=ax)
fig.show()
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/_templates/theme_variables.jinja | {%- set external_urls = {
'github': 'https://github.com/Lightning-AI/torchmetrics',
'github_issues': 'https://github.com/Lightning-AI/torchmetrics/issues',
'contributing': 'https://github.com/Lightning-AI/torchmetrics/blob/master/.github/CONTRIBUTING.md',
'docs': 'https://lightning.ai/docs/torchmetrics/latest',
'twitter': 'https://twitter.com/PyTorchLightnin',
'discuss': 'https://pytorch-lightning.slack.com',
'previous_pytorch_versions': 'https://torchmetrics.rtfd.io/en/latest/',
'home': 'https://torchmetrics.rtfd.io/en/latest/',
'get_started': 'https://lightning.ai/docs/torchmetrics/latest/pages/quickstart.html',
'blog': 'https://www.pytorchlightning.ai/blog',
'support': 'https://github.com/Lightning-AI/torchmetrics/issues',
'community': 'https://pytorch-lightning.slack.com',
'forums': 'https://pytorch-lightning.slack.com',
}
-%}
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/_templates/classtemplate.rst | .. role:: hidden
:class: hidden-section
.. currentmodule:: {{ module }}
{{ name | underline}}
.. autoclass:: {{ name }}
:members:
..
autogenerated from source/_templates/classtemplate.rst
note it does not have :inherited-members:
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/_templates/layout.html | {% extends "!layout.html" %}
<link rel="canonical" href="{{ theme_canonical_url }}{{ pagename }}.html" />
{% block footer %} {{ super() }}
<script script type="text/javascript">
var collapsedSections = [
"Audio",
"Classification",
"Image",
"Detection",
"Pairwise",
"Regression",
"Retrieval",
"Text",
"Aggregation",
"Wrappers",
"API Reference",
"Community",
];
</script>
{% endblock %}
| 0 |
public_repos/torchmetrics/docs/source/_templates | public_repos/torchmetrics/docs/source/_templates/autosummary/module.rst | {{ name | escape | underline }}
.. currentmodule:: {{ fullname }}
{% block functions %}
{% if functions %}
.. rubric:: Functions
.. autosummary::
:nosignatures:
{% for item in functions %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block classes %}
{% if classes %}
.. rubric:: Classes
.. autosummary::
:nosignatures:
{% for item in classes %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block exceptions %}
{% if exceptions %}
.. rubric:: Exceptions
.. autosummary::
:nosignatures:
{% for item in exceptions %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
.. automodule:: {{ fullname }}
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/_static/copybutton.js | /* Copied from the official Python docs: https://docs.python.org/3/_static/copybutton.js */
$(document).ready(function () {
/* Add a [>>>] button on the top-right corner of code samples to hide
* the >>> and ... prompts and the output and thus make the code
* copyable. */
var div = $(
".highlight-python .highlight," +
".highlight-python3 .highlight," +
".highlight-pycon .highlight," +
".highlight-default .highlight",
);
var pre = div.find("pre");
// get the styles from the current theme
pre.parent().parent().css("position", "relative");
var hide_text = "Hide the prompts and output";
var show_text = "Show the prompts and output";
var border_width = pre.css("border-top-width");
var border_style = pre.css("border-top-style");
var border_color = pre.css("border-top-color");
var button_styles = {
cursor: "pointer",
position: "absolute",
top: "0",
right: "0",
"border-color": border_color,
"border-style": border_style,
"border-width": border_width,
color: border_color,
"text-size": "75%",
"font-family": "monospace",
"padding-left": "0.2em",
"padding-right": "0.2em",
"border-radius": "0 3px 0 0",
};
// create and add the button to all the code blocks that contain >>>
div.each(function (index) {
var jthis = $(this);
if (jthis.find(".gp").length > 0) {
var button = $('<span class="copybutton">>>></span>');
button.css(button_styles);
button.attr("title", hide_text);
button.data("hidden", "false");
jthis.prepend(button);
}
// tracebacks (.gt) contain bare text elements that need to be
// wrapped in a span to work with .nextUntil() (see later)
jthis
.find("pre:has(.gt)")
.contents()
.filter(function () {
return this.nodeType == 3 && this.data.trim().length > 0;
})
.wrap("<span>");
});
// define the behavior of the button when it's clicked
$(".copybutton").click(function (e) {
e.preventDefault();
var button = $(this);
if (button.data("hidden") === "false") {
// hide the code output
button.parent().find(".go, .gp, .gt").hide();
button.next("pre").find(".gt").nextUntil(".gp, .go").css("visibility", "hidden");
button.css("text-decoration", "line-through");
button.attr("title", show_text);
button.data("hidden", "true");
} else {
// show the code output
button.parent().find(".go, .gp, .gt").show();
button.next("pre").find(".gt").nextUntil(".gp, .go").css("visibility", "visible");
button.css("text-decoration", "none");
button.attr("title", hide_text);
button.data("hidden", "false");
}
});
});
| 0 |
public_repos/torchmetrics/docs/source/_static | public_repos/torchmetrics/docs/source/_static/images/logo.svg | <svg width="390" height="100" viewBox="0 0 390 100" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_402_94)">
<path d="M41.5646 0.591703L1.76872 23.6686C1.17915 23.9645 0.88437 24.5562 0.294801 25.1479C0.0547165 25.7069 -0.0464476 26.3161 1.54153e-05 26.9231V73.0769C0.0610756 73.7056 0.262599 74.3124 0.589587 74.8521C0.923176 75.4815 1.4364 75.9966 2.06351 76.3314L41.5646 99.4083C42.0749 99.7924 42.6955 100 43.3333 100C43.9712 100 44.5918 99.7924 45.1021 99.4083L84.6032 76.3314C85.2303 75.9966 85.7435 75.4815 86.0771 74.8521C86.4041 74.3124 86.6056 73.7056 86.6667 73.0769V26.9527C86.6056 26.324 86.4041 25.7172 86.0771 25.1775C85.7435 24.5481 85.2303 24.033 84.6032 23.6982L45.1021 0.62129C44.5643 0.293111 43.9597 0.0908541 43.3333 0.0295715C42.7093 0.0818102 42.1049 0.273906 41.5646 0.591703Z" fill="url(#paint0_linear_402_94)"/>
<path d="M40.868 55.7649L40.868 33.1875C40.868 31.804 39.7465 30.6825 38.3631 30.6825C36.9796 30.6825 35.8581 31.804 35.8581 33.1875L35.8581 55.7649C35.8581 57.1483 36.9796 58.2698 38.3631 58.2698C39.7465 58.2698 40.868 57.1483 40.868 55.7649Z" fill="white"/>
<path d="M60.9046 60.7778L25.8413 60.7778C24.4562 60.7778 23.3334 61.9006 23.3334 63.2857C23.3334 64.6708 24.4562 65.7936 25.8413 65.7936L60.9046 65.7936C62.2897 65.7936 63.4126 64.6708 63.4126 63.2857C63.4126 61.9006 62.2897 60.7778 60.9046 60.7778Z" fill="white"/>
<path d="M60.9076 55.7649L60.9076 28.1716C60.9076 26.7882 59.7861 25.6667 58.4026 25.6667C57.0192 25.6667 55.8977 26.7882 55.8977 28.1716L55.8977 55.7649C55.8977 57.1483 57.0192 58.2698 58.4026 58.2698C59.7861 58.2698 60.9076 57.1483 60.9076 55.7649Z" fill="white"/>
<path d="M30.8483 55.7649L30.8483 48.2351C30.8483 46.8517 29.7268 45.7302 28.3433 45.7302C26.9599 45.7302 25.8384 46.8517 25.8384 48.2351L25.8384 55.7649C25.8384 57.1483 26.9599 58.2698 28.3433 58.2698C29.7268 58.2698 30.8483 57.1483 30.8483 55.7649Z" fill="white"/>
<path d="M45.8779 38.2034V55.7649C45.8779 57.1483 46.9994 58.2698 48.3829 58.2698C49.7663 58.2698 50.8878 57.1483 50.8878 55.7649V38.2034C50.8878 36.8199 49.7663 35.6984 48.3829 35.6984C46.9994 35.6984 45.8779 36.8199 45.8779 38.2034Z" fill="white"/>
</g>
<path d="M106.567 16.9457V12.5281H129.777V16.9457H120.786V41.619H115.559V16.9457H106.567ZM139.378 42.0452C137.247 42.0452 135.4 41.5764 133.838 40.6389C132.275 39.7014 131.063 38.3899 130.201 36.7042C129.349 35.0186 128.923 33.0489 128.923 30.7952C128.923 28.5414 129.349 26.5669 130.201 24.8719C131.063 23.1768 132.275 21.8605 133.838 20.923C135.4 19.9855 137.247 19.5167 139.378 19.5167C141.508 19.5167 143.355 19.9855 144.917 20.923C146.48 21.8605 147.687 23.1768 148.54 24.8719C149.401 26.5669 149.832 28.5414 149.832 30.7952C149.832 33.0489 149.401 35.0186 148.54 36.7042C147.687 38.3899 146.48 39.7014 144.917 40.6389C143.355 41.5764 141.508 42.0452 139.378 42.0452ZM139.406 37.9258C140.561 37.9258 141.527 37.6086 142.304 36.9741C143.08 36.3302 143.658 35.4685 144.037 34.3889C144.425 33.3094 144.619 32.1067 144.619 30.7809C144.619 29.4457 144.425 28.2383 144.037 27.1588C143.658 26.0698 143.08 25.2033 142.304 24.5594C141.527 23.9154 140.561 23.5934 139.406 23.5934C138.222 23.5934 137.237 23.9154 136.451 24.5594C135.675 25.2033 135.093 26.0698 134.704 27.1588C134.326 28.2383 134.136 29.4457 134.136 30.7809C134.136 32.1067 134.326 33.3094 134.704 34.3889C135.093 35.4685 135.675 36.3302 136.451 36.9741C137.237 37.6086 138.222 37.9258 139.406 37.9258ZM153.196 41.619V19.8008H158.182V23.4372H158.41C158.807 22.1777 159.489 21.2071 160.455 20.5253C161.43 19.834 162.543 19.4883 163.793 19.4883C164.077 19.4883 164.394 19.5025 164.745 19.5309C165.105 19.5499 165.403 19.583 165.64 19.6304V24.3605C165.422 24.2847 165.076 24.2184 164.603 24.1616C164.139 24.0953 163.689 24.0622 163.253 24.0622C162.316 24.0622 161.473 24.2658 160.725 24.673C159.986 25.0707 159.404 25.6247 158.978 26.3349C158.552 27.0452 158.339 27.8643 158.339 28.7923V41.619H153.196ZM176.674 42.0452C174.496 42.0452 172.626 41.5669 171.064 40.6105C169.511 39.6541 168.313 38.333 167.47 36.6474C166.637 34.9524 166.22 33.0016 166.22 30.7952C166.22 28.5792 166.646 26.6238 167.498 24.9287C168.351 23.2241 169.553 21.8984 171.106 20.9514C172.669 19.995 174.515 19.5167 176.646 19.5167C178.417 19.5167 179.984 19.8435 181.348 20.4969C182.721 21.1408 183.815 22.0546 184.629 23.2383C185.443 24.4126 185.907 25.7857 186.021 27.3577H181.106C180.907 26.3065 180.434 25.4306 179.686 24.7298C178.947 24.0196 177.958 23.6645 176.717 23.6645C175.666 23.6645 174.743 23.9486 173.947 24.5167C173.152 25.0755 172.531 25.8804 172.086 26.9315C171.651 27.9827 171.433 29.2421 171.433 30.7099C171.433 32.1967 171.651 33.4751 172.086 34.5452C172.522 35.6058 173.133 36.4249 173.919 37.0025C174.714 37.5707 175.647 37.8548 176.717 37.8548C177.475 37.8548 178.152 37.7128 178.748 37.4287C179.354 37.1351 179.861 36.7137 180.268 36.1645C180.675 35.6152 180.955 34.9476 181.106 34.1616H186.021C185.898 35.7052 185.443 37.0736 184.657 38.2667C183.871 39.4505 182.801 40.3785 181.447 41.0508C180.093 41.7137 178.502 42.0452 176.674 42.0452ZM194.385 28.8349V41.619H189.243V12.5281H194.272V23.5082H194.527C195.039 22.2772 195.83 21.3065 196.9 20.5963C197.979 19.8766 199.352 19.5167 201.019 19.5167C202.534 19.5167 203.855 19.834 204.982 20.4684C206.109 21.1029 206.98 22.0309 207.596 23.2525C208.221 24.4741 208.533 25.9656 208.533 27.727V41.619H203.391V28.5224C203.391 27.0546 203.012 25.9135 202.255 25.0991C201.507 24.2753 200.455 23.8633 199.101 23.8633C198.192 23.8633 197.378 24.0622 196.658 24.4599C195.948 24.8482 195.389 25.4116 194.982 26.1503C194.584 26.8889 194.385 27.7838 194.385 28.8349ZM213.002 12.5281H219.451L228.087 33.6077H228.428L237.064 12.5281H243.513V41.619H238.456V21.6332H238.187L230.147 41.5338H226.368L218.329 21.5906H218.059V41.619H213.002V12.5281ZM257.684 42.0452C255.496 42.0452 253.607 41.5906 252.016 40.6815C250.435 39.763 249.218 38.4656 248.366 36.7895C247.513 35.1039 247.087 33.12 247.087 30.8378C247.087 28.5935 247.513 26.6238 248.366 24.9287C249.227 23.2241 250.43 21.8984 251.973 20.9514C253.517 19.995 255.33 19.5167 257.414 19.5167C258.759 19.5167 260.027 19.7345 261.221 20.1702C262.423 20.5963 263.484 21.2592 264.402 22.1588C265.33 23.0584 266.06 24.2042 266.59 25.5963C267.12 26.9789 267.385 28.6266 267.385 30.5395V32.1162H249.502V28.6503H262.456C262.447 27.6654 262.234 26.7895 261.817 26.0224C261.401 25.2459 260.818 24.6351 260.07 24.19C259.331 23.745 258.47 23.5224 257.485 23.5224C256.434 23.5224 255.51 23.7781 254.715 24.2895C253.92 24.7914 253.299 25.4542 252.854 26.2781C252.419 27.0925 252.196 27.9874 252.187 28.9628V31.9883C252.187 33.2573 252.419 34.3463 252.883 35.2554C253.347 36.155 253.995 36.8463 254.829 37.3292C255.662 37.8027 256.637 38.0395 257.755 38.0395C258.503 38.0395 259.18 37.9353 259.786 37.727C260.392 37.5092 260.918 37.1919 261.363 36.7753C261.808 36.3586 262.144 35.8425 262.371 35.227L267.172 35.7667C266.869 37.0357 266.292 38.1436 265.439 39.0906C264.597 40.0281 263.517 40.7573 262.201 41.2781C260.884 41.7895 259.379 42.0452 257.684 42.0452ZM281.63 19.8008V23.7781H269.088V19.8008H281.63ZM272.184 14.5736H277.326V35.0565C277.326 35.7478 277.431 36.2781 277.639 36.6474C277.857 37.0073 278.141 37.2535 278.491 37.3861C278.842 37.5186 279.23 37.5849 279.656 37.5849C279.978 37.5849 280.272 37.5613 280.537 37.5139C280.811 37.4666 281.02 37.4239 281.162 37.3861L282.028 41.406C281.754 41.5006 281.361 41.6048 280.849 41.7185C280.347 41.8321 279.732 41.8984 279.003 41.9173C277.715 41.9552 276.555 41.7611 275.522 41.3349C274.49 40.8993 273.671 40.227 273.065 39.3179C272.469 38.4088 272.175 37.2724 272.184 35.9088V14.5736ZM284.931 41.619V19.8008H289.917V23.4372H290.144C290.542 22.1777 291.223 21.2071 292.189 20.5253C293.165 19.834 294.277 19.4883 295.527 19.4883C295.812 19.4883 296.129 19.5025 296.479 19.5309C296.839 19.5499 297.137 19.583 297.374 19.6304V24.3605C297.156 24.2847 296.811 24.2184 296.337 24.1616C295.873 24.0953 295.423 24.0622 294.988 24.0622C294.05 24.0622 293.207 24.2658 292.459 24.673C291.721 25.0707 291.138 25.6247 290.712 26.3349C290.286 27.0452 290.073 27.8643 290.073 28.7923V41.619H284.931ZM299.79 41.619V19.8008H304.932V41.619H299.79ZM302.375 16.7042C301.561 16.7042 300.86 16.4344 300.273 15.8946C299.686 15.3453 299.393 14.6872 299.393 13.9202C299.393 13.1436 299.686 12.4855 300.273 11.9457C300.86 11.3965 301.561 11.1219 302.375 11.1219C303.199 11.1219 303.9 11.3965 304.478 11.9457C305.065 12.4855 305.358 13.1436 305.358 13.9202C305.358 14.6872 305.065 15.3453 304.478 15.8946C303.9 16.4344 303.199 16.7042 302.375 16.7042ZM318.737 42.0452C316.559 42.0452 314.689 41.5669 313.126 40.6105C311.573 39.6541 310.375 38.333 309.532 36.6474C308.699 34.9524 308.282 33.0016 308.282 30.7952C308.282 28.5792 308.709 26.6238 309.561 24.9287C310.413 23.2241 311.616 21.8984 313.169 20.9514C314.731 19.995 316.578 19.5167 318.709 19.5167C320.479 19.5167 322.047 19.8435 323.41 20.4969C324.783 21.1408 325.877 22.0546 326.692 23.2383C327.506 24.4126 327.97 25.7857 328.084 27.3577H323.169C322.97 26.3065 322.496 25.4306 321.748 24.7298C321.01 24.0196 320.02 23.6645 318.78 23.6645C317.728 23.6645 316.805 23.9486 316.01 24.5167C315.214 25.0755 314.594 25.8804 314.149 26.9315C313.713 27.9827 313.495 29.2421 313.495 30.7099C313.495 32.1967 313.713 33.4751 314.149 34.5452C314.585 35.6058 315.195 36.4249 315.981 37.0025C316.777 37.5707 317.71 37.8548 318.78 37.8548C319.537 37.8548 320.214 37.7128 320.811 37.4287C321.417 37.1351 321.924 36.7137 322.331 36.1645C322.738 35.6152 323.017 34.9476 323.169 34.1616H328.084C327.96 35.7052 327.506 37.0736 326.72 38.2667C325.934 39.4505 324.864 40.3785 323.51 41.0508C322.156 41.7137 320.565 42.0452 318.737 42.0452ZM348.55 25.5679L343.863 26.0792C343.73 25.6058 343.498 25.1607 343.167 24.744C342.845 24.3274 342.409 23.9912 341.86 23.7355C341.311 23.4798 340.638 23.352 339.843 23.352C338.773 23.352 337.873 23.584 337.144 24.048C336.424 24.512 336.069 25.1133 336.079 25.852C336.069 26.4864 336.301 27.0025 336.775 27.4003C337.258 27.798 338.053 28.1247 339.161 28.3804L342.883 29.1758C344.947 29.6209 346.481 30.3264 347.485 31.2923C348.498 32.2582 349.009 33.5224 349.019 35.0849C349.009 36.458 348.607 37.6702 347.812 38.7213C347.026 39.763 345.932 40.5774 344.53 41.1645C343.129 41.7516 341.519 42.0452 339.701 42.0452C337.03 42.0452 334.881 41.4864 333.252 40.369C331.623 39.2421 330.652 37.6749 330.34 35.6673L335.354 35.1844C335.581 36.1692 336.064 36.9126 336.803 37.4145C337.542 37.9164 338.503 38.1673 339.687 38.1673C340.908 38.1673 341.888 37.9164 342.627 37.4145C343.375 36.9126 343.749 36.2923 343.749 35.5537C343.749 34.9287 343.508 34.4126 343.025 34.0054C342.551 33.5982 341.812 33.2857 340.809 33.0679L337.087 32.2866C334.994 31.851 333.446 31.1171 332.442 30.0849C331.438 29.0433 330.941 27.727 330.951 26.1361C330.941 24.7914 331.306 23.6266 332.045 22.6417C332.793 21.6474 333.83 20.8804 335.155 20.3406C336.491 19.7914 338.029 19.5167 339.772 19.5167C342.329 19.5167 344.341 20.0613 345.809 21.1503C347.286 22.2393 348.2 23.7118 348.55 25.5679Z" fill="#1C1C1C"/>
<path d="M123.159 68.3333H121.045C120.92 67.7254 120.702 67.1913 120.389 66.731C120.082 66.2708 119.707 65.8844 119.264 65.5719C118.827 65.2538 118.341 65.0151 117.807 64.856C117.273 64.6969 116.716 64.6174 116.136 64.6174C115.08 64.6174 114.122 64.8844 113.264 65.4185C112.412 65.9526 111.733 66.7396 111.227 67.7793C110.727 68.8191 110.477 70.0947 110.477 71.606C110.477 73.1174 110.727 74.393 111.227 75.4327C111.733 76.4725 112.412 77.2594 113.264 77.7935C114.122 78.3276 115.08 78.5947 116.136 78.5947C116.716 78.5947 117.273 78.5151 117.807 78.356C118.341 78.1969 118.827 77.9612 119.264 77.6487C119.707 77.3305 120.082 76.9413 120.389 76.481C120.702 76.0151 120.92 75.481 121.045 74.8788H123.159C123 75.7708 122.71 76.5691 122.29 77.2737C121.869 77.9782 121.347 78.5776 120.722 79.0719C120.097 79.5606 119.395 79.9327 118.616 80.1884C117.844 80.4441 117.017 80.5719 116.136 80.5719C114.648 80.5719 113.324 80.2083 112.165 79.481C111.006 78.7538 110.094 77.7197 109.429 76.3788C108.764 75.0379 108.432 73.4469 108.432 71.606C108.432 69.7651 108.764 68.1742 109.429 66.8333C110.094 65.4924 111.006 64.4583 112.165 63.731C113.324 63.0038 114.648 62.6401 116.136 62.6401C117.017 62.6401 117.844 62.768 118.616 63.0237C119.395 63.2793 120.097 63.6543 120.722 64.1487C121.347 64.6373 121.869 65.2339 122.29 65.9384C122.71 66.6373 123 67.4356 123.159 68.3333ZM126.302 80.3333V67.2424H128.245V69.2197H128.381C128.62 68.5719 129.052 68.0464 129.677 67.643C130.302 67.2396 131.006 67.0379 131.79 67.0379C131.938 67.0379 132.123 67.0407 132.344 67.0464C132.566 67.0521 132.734 67.0606 132.847 67.0719V69.1174C132.779 69.1004 132.623 69.0748 132.379 69.0407C132.14 69.0009 131.887 68.981 131.62 68.981C130.984 68.981 130.415 69.1146 129.915 69.3816C129.421 69.643 129.029 70.0066 128.739 70.4725C128.455 70.9327 128.313 71.4583 128.313 72.0492V80.3333H126.302ZM140.322 80.606C139.06 80.606 137.972 80.3276 137.058 79.7708C136.148 79.2083 135.447 78.4242 134.952 77.4185C134.464 76.4072 134.219 75.231 134.219 73.8901C134.219 72.5492 134.464 71.3674 134.952 70.3447C135.447 69.3163 136.134 68.5151 137.015 67.9413C137.901 67.3617 138.935 67.0719 140.117 67.0719C140.799 67.0719 141.472 67.1856 142.137 67.4129C142.802 67.6401 143.407 68.0094 143.952 68.5208C144.498 69.0265 144.933 69.6969 145.256 70.5322C145.58 71.3674 145.742 72.3958 145.742 73.6174V74.4697H135.651V72.731H143.697C143.697 71.9924 143.549 71.3333 143.254 70.7538C142.964 70.1742 142.549 69.7168 142.009 69.3816C141.475 69.0464 140.844 68.8788 140.117 68.8788C139.316 68.8788 138.623 69.0776 138.038 69.4754C137.458 69.8674 137.012 70.3788 136.7 71.0094C136.387 71.6401 136.231 72.3163 136.231 73.0379V74.1969C136.231 75.1856 136.401 76.0237 136.742 76.7112C137.089 77.393 137.569 77.9129 138.183 78.2708C138.796 78.6231 139.509 78.7992 140.322 78.7992C140.85 78.7992 141.327 78.7254 141.754 78.5776C142.185 78.4242 142.558 78.1969 142.87 77.8958C143.183 77.589 143.424 77.2083 143.594 76.7538L145.538 77.2992C145.333 77.9583 144.989 78.5379 144.506 79.0379C144.023 79.5322 143.427 79.9185 142.717 80.1969C142.006 80.4697 141.208 80.606 140.322 80.606ZM152.654 80.6401C151.825 80.6401 151.072 80.4839 150.396 80.1714C149.719 79.8532 149.183 79.3958 148.785 78.7992C148.387 78.1969 148.188 77.4697 148.188 76.6174C148.188 75.8674 148.336 75.2594 148.631 74.7935C148.927 74.3219 149.322 73.9526 149.816 73.6856C150.31 73.4185 150.856 73.2197 151.452 73.089C152.055 72.9526 152.66 72.8447 153.268 72.7651C154.063 72.6629 154.708 72.5862 155.202 72.535C155.702 72.4782 156.066 72.3844 156.293 72.2538C156.526 72.1231 156.643 71.8958 156.643 71.5719V71.5038C156.643 70.6629 156.413 70.0094 155.952 69.5435C155.498 69.0776 154.808 68.8447 153.881 68.8447C152.921 68.8447 152.168 69.0549 151.623 69.4754C151.077 69.8958 150.694 70.3447 150.472 70.8219L148.563 70.1401C148.904 69.3447 149.359 68.7254 149.927 68.2822C150.501 67.8333 151.126 67.5208 151.802 67.3447C152.484 67.1629 153.154 67.0719 153.813 67.0719C154.234 67.0719 154.717 67.1231 155.262 67.2254C155.813 67.3219 156.344 67.5237 156.856 67.8305C157.373 68.1373 157.802 68.6004 158.143 69.2197C158.484 69.839 158.654 70.6685 158.654 71.7083V80.3333H156.643V78.5606H156.54C156.404 78.8447 156.177 79.1487 155.859 79.4725C155.54 79.7964 155.117 80.0719 154.589 80.2992C154.06 80.5265 153.415 80.6401 152.654 80.6401ZM152.961 78.8333C153.756 78.8333 154.427 78.6771 154.972 78.3646C155.523 78.0521 155.938 77.6487 156.217 77.1543C156.501 76.66 156.643 76.1401 156.643 75.5947V73.7538C156.558 73.856 156.37 73.9498 156.08 74.035C155.796 74.1146 155.467 74.1856 155.092 74.2481C154.722 74.3049 154.362 74.356 154.009 74.4015C153.663 74.4413 153.381 74.4754 153.165 74.5038C152.643 74.5719 152.154 74.6827 151.7 74.8362C151.251 74.9839 150.887 75.2083 150.609 75.5094C150.336 75.8049 150.2 76.2083 150.2 76.7197C150.2 77.4185 150.458 77.9469 150.975 78.3049C151.498 78.6572 152.16 78.8333 152.961 78.8333ZM168.018 67.2424V68.9469H161.234V67.2424H168.018ZM163.212 64.106H165.223V76.5833C165.223 77.1515 165.305 77.5776 165.47 77.8617C165.641 78.1401 165.857 78.3276 166.118 78.4242C166.385 78.5151 166.666 78.5606 166.962 78.5606C167.183 78.5606 167.365 78.5492 167.507 78.5265C167.649 78.4981 167.763 78.4754 167.848 78.4583L168.257 80.2651C168.121 80.3163 167.93 80.3674 167.686 80.4185C167.442 80.4754 167.132 80.5038 166.757 80.5038C166.189 80.5038 165.632 80.3816 165.087 80.1373C164.547 79.893 164.098 79.5208 163.74 79.0208C163.388 78.5208 163.212 77.8901 163.212 77.1288V64.106ZM176.392 80.606C175.131 80.606 174.043 80.3276 173.128 79.7708C172.219 79.2083 171.517 78.4242 171.023 77.4185C170.534 76.4072 170.29 75.231 170.29 73.8901C170.29 72.5492 170.534 71.3674 171.023 70.3447C171.517 69.3163 172.205 68.5151 173.085 67.9413C173.972 67.3617 175.006 67.0719 176.188 67.0719C176.869 67.0719 177.543 67.1856 178.207 67.4129C178.872 67.6401 179.477 68.0094 180.023 68.5208C180.568 69.0265 181.003 69.6969 181.327 70.5322C181.651 71.3674 181.812 72.3958 181.812 73.6174V74.4697H171.722V72.731H179.767C179.767 71.9924 179.619 71.3333 179.324 70.7538C179.034 70.1742 178.619 69.7168 178.08 69.3816C177.545 69.0464 176.915 68.8788 176.188 68.8788C175.386 68.8788 174.693 69.0776 174.108 69.4754C173.528 69.8674 173.082 70.3788 172.77 71.0094C172.457 71.6401 172.301 72.3163 172.301 73.0379V74.1969C172.301 75.1856 172.472 76.0237 172.812 76.7112C173.159 77.393 173.639 77.9129 174.253 78.2708C174.866 78.6231 175.58 78.7992 176.392 78.7992C176.92 78.7992 177.398 78.7254 177.824 78.5776C178.256 78.4242 178.628 78.1969 178.94 77.8958C179.253 77.589 179.494 77.2083 179.665 76.7538L181.608 77.2992C181.403 77.9583 181.06 78.5379 180.577 79.0379C180.094 79.5322 179.497 79.9185 178.787 80.1969C178.077 80.4697 177.278 80.606 176.392 80.606ZM189.815 80.606C188.724 80.606 187.761 80.3305 186.926 79.7793C186.091 79.2225 185.438 78.4384 184.966 77.4271C184.494 76.41 184.259 75.2083 184.259 73.8219C184.259 72.4469 184.494 71.2538 184.966 70.2424C185.438 69.231 186.094 68.4498 186.935 67.8987C187.776 67.3475 188.747 67.0719 189.849 67.0719C190.702 67.0719 191.375 67.214 191.869 67.4981C192.369 67.7765 192.75 68.0947 193.011 68.4526C193.278 68.8049 193.486 69.0947 193.634 69.3219H193.804V62.8788H195.815V80.3333H193.872V78.3219H193.634C193.486 78.5606 193.276 78.8617 193.003 79.2254C192.73 79.5833 192.341 79.9043 191.835 80.1884C191.33 80.4668 190.656 80.606 189.815 80.606ZM190.088 78.7992C190.895 78.7992 191.577 78.589 192.134 78.1685C192.69 77.7424 193.114 77.1543 193.403 76.4043C193.693 75.6487 193.838 74.7765 193.838 73.7879C193.838 72.8106 193.696 71.9555 193.412 71.2225C193.128 70.4839 192.707 69.91 192.151 69.5009C191.594 69.0862 190.906 68.8788 190.088 68.8788C189.236 68.8788 188.526 69.0975 187.957 69.535C187.395 69.9668 186.972 70.5549 186.688 71.2992C186.409 72.0379 186.27 72.8674 186.27 73.7879C186.27 74.7197 186.412 75.5663 186.696 76.3276C186.986 77.0833 187.412 77.6856 187.974 78.1344C188.543 78.5776 189.247 78.7992 190.088 78.7992ZM206.801 80.3333V62.8788H208.812V69.3219H208.983C209.131 69.0947 209.335 68.8049 209.597 68.4526C209.864 68.0947 210.244 67.7765 210.739 67.4981C211.239 67.214 211.915 67.0719 212.767 67.0719C213.869 67.0719 214.841 67.3475 215.682 67.8987C216.523 68.4498 217.179 69.231 217.651 70.2424C218.122 71.2538 218.358 72.4469 218.358 73.8219C218.358 75.2083 218.122 76.41 217.651 77.4271C217.179 78.4384 216.526 79.2225 215.69 79.7793C214.855 80.3305 213.892 80.606 212.801 80.606C211.96 80.606 211.287 80.4668 210.781 80.1884C210.276 79.9043 209.886 79.5833 209.614 79.2254C209.341 78.8617 209.131 78.5606 208.983 78.3219H208.744V80.3333H206.801ZM208.778 73.7879C208.778 74.7765 208.923 75.6487 209.213 76.4043C209.503 77.1543 209.926 77.7424 210.483 78.1685C211.04 78.589 211.722 78.7992 212.528 78.7992C213.369 78.7992 214.071 78.5776 214.634 78.1344C215.202 77.6856 215.628 77.0833 215.912 76.3276C216.202 75.5663 216.347 74.7197 216.347 73.7879C216.347 72.8674 216.205 72.0379 215.92 71.2992C215.642 70.5549 215.219 69.9668 214.651 69.535C214.088 69.0975 213.381 68.8788 212.528 68.8788C211.71 68.8788 211.023 69.0862 210.466 69.5009C209.909 69.91 209.489 70.4839 209.205 71.2225C208.92 71.9555 208.778 72.8106 208.778 73.7879ZM222.261 85.2424C221.92 85.2424 221.616 85.214 221.349 85.1572C221.082 85.106 220.898 85.0549 220.795 85.0038L221.307 83.231C221.795 83.356 222.227 83.4015 222.602 83.3674C222.977 83.3333 223.31 83.1657 223.599 82.8646C223.895 82.5691 224.165 82.089 224.409 81.4242L224.784 80.4015L219.943 67.2424H222.125L225.739 77.6742H225.875L229.489 67.2424H231.67L226.114 82.2424C225.864 82.9185 225.554 83.4782 225.185 83.9214C224.815 84.3702 224.386 84.7026 223.898 84.9185C223.415 85.1344 222.869 85.2424 222.261 85.2424ZM241.348 80.3333V62.8788H243.462V78.4583H251.575V80.3333H241.348ZM254.575 80.3333V67.2424H256.587V80.3333H254.575ZM255.598 65.0606C255.206 65.0606 254.868 64.9271 254.584 64.66C254.305 64.393 254.166 64.0719 254.166 63.6969C254.166 63.3219 254.305 63.0009 254.584 62.7339C254.868 62.4668 255.206 62.3333 255.598 62.3333C255.99 62.3333 256.325 62.4668 256.604 62.7339C256.888 63.0009 257.03 63.3219 257.03 63.6969C257.03 64.0719 256.888 64.393 256.604 64.66C256.325 64.9271 255.99 65.0606 255.598 65.0606ZM265.555 85.5151C264.583 85.5151 263.748 85.3901 263.049 85.1401C262.35 84.8958 261.768 84.5719 261.302 84.1685C260.842 83.7708 260.475 83.3447 260.202 82.8901L261.805 81.7651C261.987 82.0038 262.217 82.2765 262.495 82.5833C262.773 82.8958 263.154 83.1657 263.637 83.393C264.126 83.6259 264.765 83.7424 265.555 83.7424C266.612 83.7424 267.484 83.4867 268.171 82.9754C268.859 82.464 269.202 81.6629 269.202 80.5719V77.9129H269.032C268.884 78.1515 268.674 78.4469 268.401 78.7992C268.134 79.1458 267.748 79.4555 267.242 79.7282C266.742 79.9952 266.066 80.1288 265.214 80.1288C264.157 80.1288 263.208 79.8788 262.367 79.3788C261.532 78.8788 260.87 78.1515 260.381 77.1969C259.898 76.2424 259.657 75.0833 259.657 73.7197C259.657 72.3788 259.893 71.2112 260.364 70.2168C260.836 69.2168 261.492 68.4441 262.333 67.8987C263.174 67.3475 264.146 67.0719 265.248 67.0719C266.1 67.0719 266.776 67.214 267.276 67.4981C267.782 67.7765 268.168 68.0947 268.435 68.4526C268.708 68.8049 268.918 69.0947 269.066 69.3219H269.271V67.2424H271.214V80.7083C271.214 81.8333 270.958 82.7481 270.447 83.4526C269.941 84.1629 269.259 84.6827 268.401 85.0123C267.549 85.3475 266.6 85.5151 265.555 85.5151ZM265.487 78.3219C266.293 78.3219 266.975 78.1373 267.532 77.768C268.089 77.3987 268.512 76.8674 268.802 76.1742C269.092 75.481 269.237 74.6515 269.237 73.6856C269.237 72.7424 269.094 71.91 268.81 71.1884C268.526 70.4668 268.106 69.9015 267.549 69.4924C266.992 69.0833 266.305 68.8788 265.487 68.8788C264.634 68.8788 263.924 69.0947 263.356 69.5265C262.793 69.9583 262.37 70.5379 262.086 71.2651C261.808 71.9924 261.668 72.7992 261.668 73.6856C261.668 74.5947 261.81 75.3987 262.094 76.0975C262.384 76.7907 262.81 77.3362 263.373 77.7339C263.941 78.1259 264.646 78.3219 265.487 78.3219ZM276.907 72.4583V80.3333H274.896V62.8788H276.907V69.2879H277.077C277.384 68.6117 277.844 68.0748 278.458 67.6771C279.077 67.2737 279.901 67.0719 280.93 67.0719C281.822 67.0719 282.603 67.2509 283.273 67.6089C283.944 67.9612 284.464 68.5038 284.833 69.2367C285.208 69.964 285.396 70.8901 285.396 72.0151V80.3333H283.384V72.1515C283.384 71.1117 283.114 70.3077 282.575 69.7396C282.04 69.1657 281.299 68.8788 280.35 68.8788C279.691 68.8788 279.1 69.018 278.577 69.2964C278.06 69.5748 277.651 69.981 277.35 70.5151C277.055 71.0492 276.907 71.6969 276.907 72.4583ZM294.768 67.2424V68.9469H287.984V67.2424H294.768ZM289.962 64.106H291.973V76.5833C291.973 77.1515 292.055 77.5776 292.22 77.8617C292.391 78.1401 292.607 78.3276 292.868 78.4242C293.135 78.5151 293.416 78.5606 293.712 78.5606C293.933 78.5606 294.115 78.5492 294.257 78.5265C294.399 78.4981 294.513 78.4754 294.598 78.4583L295.007 80.2651C294.871 80.3163 294.68 80.3674 294.436 80.4185C294.192 80.4754 293.882 80.5038 293.507 80.5038C292.939 80.5038 292.382 80.3816 291.837 80.1373C291.297 79.893 290.848 79.5208 290.49 79.0208C290.138 78.5208 289.962 77.8901 289.962 77.1288V64.106ZM299.805 72.4583V80.3333H297.794V67.2424H299.737V69.2879H299.908C300.214 68.6231 300.68 68.089 301.305 67.6856C301.93 67.2765 302.737 67.0719 303.726 67.0719C304.612 67.0719 305.388 67.2538 306.053 67.6174C306.717 67.9754 307.234 68.5208 307.604 69.2538C307.973 69.981 308.158 70.9015 308.158 72.0151V80.3333H306.146V72.1515C306.146 71.1231 305.879 70.3219 305.345 69.7481C304.811 69.1685 304.078 68.8788 303.146 68.8788C302.504 68.8788 301.93 69.018 301.425 69.2964C300.925 69.5748 300.53 69.981 300.24 70.5151C299.95 71.0492 299.805 71.6969 299.805 72.4583ZM311.833 80.3333V67.2424H313.844V80.3333H311.833ZM312.856 65.0606C312.464 65.0606 312.126 64.9271 311.842 64.66C311.563 64.393 311.424 64.0719 311.424 63.6969C311.424 63.3219 311.563 63.0009 311.842 62.7339C312.126 62.4668 312.464 62.3333 312.856 62.3333C313.248 62.3333 313.583 62.4668 313.862 62.7339C314.146 63.0009 314.288 63.3219 314.288 63.6969C314.288 64.0719 314.146 64.393 313.862 64.66C313.583 64.9271 313.248 65.0606 312.856 65.0606ZM319.54 72.4583V80.3333H317.528V67.2424H319.472V69.2879H319.642C319.949 68.6231 320.415 68.089 321.04 67.6856C321.665 67.2765 322.472 67.0719 323.46 67.0719C324.347 67.0719 325.122 67.2538 325.787 67.6174C326.452 67.9754 326.969 68.5208 327.338 69.2538C327.707 69.981 327.892 70.9015 327.892 72.0151V80.3333H325.881V72.1515C325.881 71.1231 325.614 70.3219 325.08 69.7481C324.545 69.1685 323.813 68.8788 322.881 68.8788C322.239 68.8788 321.665 69.018 321.159 69.2964C320.659 69.5748 320.264 69.981 319.974 70.5151C319.685 71.0492 319.54 71.6969 319.54 72.4583ZM336.852 85.5151C335.88 85.5151 335.045 85.3901 334.346 85.1401C333.647 84.8958 333.065 84.5719 332.599 84.1685C332.138 83.7708 331.772 83.3447 331.499 82.8901L333.102 81.7651C333.283 82.0038 333.513 82.2765 333.792 82.5833C334.07 82.8958 334.451 83.1657 334.934 83.393C335.423 83.6259 336.062 83.7424 336.852 83.7424C337.908 83.7424 338.781 83.4867 339.468 82.9754C340.156 82.464 340.499 81.6629 340.499 80.5719V77.9129H340.329C340.181 78.1515 339.971 78.4469 339.698 78.7992C339.431 79.1458 339.045 79.4555 338.539 79.7282C338.039 79.9952 337.363 80.1288 336.511 80.1288C335.454 80.1288 334.505 79.8788 333.664 79.3788C332.829 78.8788 332.167 78.1515 331.678 77.1969C331.195 76.2424 330.954 75.0833 330.954 73.7197C330.954 72.3788 331.19 71.2112 331.661 70.2168C332.133 69.2168 332.789 68.4441 333.63 67.8987C334.471 67.3475 335.442 67.0719 336.545 67.0719C337.397 67.0719 338.073 67.214 338.573 67.4981C339.079 67.7765 339.465 68.0947 339.732 68.4526C340.005 68.8049 340.215 69.0947 340.363 69.3219H340.567V67.2424H342.511V80.7083C342.511 81.8333 342.255 82.7481 341.744 83.4526C341.238 84.1629 340.556 84.6827 339.698 85.0123C338.846 85.3475 337.897 85.5151 336.852 85.5151ZM336.783 78.3219C337.59 78.3219 338.272 78.1373 338.829 77.768C339.386 77.3987 339.809 76.8674 340.099 76.1742C340.388 75.481 340.533 74.6515 340.533 73.6856C340.533 72.7424 340.391 71.91 340.107 71.1884C339.823 70.4668 339.403 69.9015 338.846 69.4924C338.289 69.0833 337.602 68.8788 336.783 68.8788C335.931 68.8788 335.221 69.0947 334.653 69.5265C334.09 69.9583 333.667 70.5379 333.383 71.2651C333.104 71.9924 332.965 72.7992 332.965 73.6856C332.965 74.5947 333.107 75.3987 333.391 76.0975C333.681 76.7907 334.107 77.3362 334.67 77.7339C335.238 78.1259 335.942 78.3219 336.783 78.3219ZM353.931 80.3333H351.715L358.124 62.8788H360.306L366.715 80.3333H364.499L359.283 65.6401H359.147L353.931 80.3333ZM354.749 73.5151H363.681V75.3901H354.749V73.5151ZM371.548 62.8788V80.3333H369.434V62.8788H371.548Z" fill="#4F4F4F"/>
<defs>
<linearGradient id="paint0_linear_402_94" x1="62.02" y1="30.7504" x2="-41.4315" y2="126.361" gradientUnits="userSpaceOnUse">
<stop stop-color="#792EE5"/>
<stop offset="1" stop-color="#428FF4"/>
</linearGradient>
<clipPath id="clip0_402_94">
<rect width="86.6667" height="100" fill="white"/>
</clipPath>
</defs>
</svg>
| 0 |
public_repos/torchmetrics/docs/source/_static | public_repos/torchmetrics/docs/source/_static/images/logo_light.svg | <svg width="202" height="42" viewBox="0 0 202 42" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M0 10.5L17.9393 0L35.88 10.5V31.5L17.94 42L0 31.5V10.5ZM17 15V26H15L15 15H17ZM26 27H10V29H26V27ZM25 13V26H23V13H25ZM13 26V21H11V26H13ZM19 26V17H21V26H19Z" fill="#792EE5"/>
<path d="M62.144 17.288V14.72H47.48V17.288H53.432V32H56.192V17.288H62.144ZM67.0404 32.216C70.8084 32.216 73.3764 29.336 73.3764 26.024C73.3764 22.664 70.6884 19.832 67.0404 19.832C63.3924 19.832 60.7044 22.664 60.7044 26.024C60.7044 29.36 63.2724 32.216 67.0404 32.216ZM67.0404 29.744C65.0004 29.744 63.3924 28.04 63.3924 26.024C63.3924 23.912 65.0004 22.304 67.0404 22.304C69.0804 22.304 70.6884 23.912 70.6884 26.024C70.6884 28.04 69.0804 29.744 67.0404 29.744ZM78.5098 25.736C78.5098 23.816 79.5178 22.376 81.4138 22.376H82.8538V20.048H81.4858C79.9018 20.048 78.9178 20.888 78.5098 21.728V20.048H75.8698V32H78.5098V25.736ZM89.6034 32.216C91.4274 32.216 92.9874 31.568 94.1154 30.488L95.2674 28.208H92.4834C92.0274 29.144 91.1394 29.744 89.6274 29.744C87.6834 29.744 86.2914 28.064 86.2914 26C86.2914 23.96 87.6594 22.304 89.6994 22.304C91.0674 22.304 91.9794 22.952 92.4114 23.84H95.2914C94.5954 21.824 92.8914 19.832 89.6274 19.832C86.1954 19.832 83.5794 22.592 83.5794 26C83.5794 29.384 86.1474 32.216 89.6034 32.216ZM100.025 25.328C100.025 23.504 101.081 22.304 102.809 22.304C104.537 22.304 105.497 23.552 105.497 25.112V32H108.137V24.776C108.137 21.632 106.265 19.832 103.433 19.832C101.969 19.832 100.769 20.528 100.025 21.44V14.72H97.3854V32H100.025V25.328ZM114.303 18.776L119.031 32H122.319L127.047 18.776V32H129.711V14.72H125.919L120.687 29.312L115.503 14.72H111.639V32H114.303V18.776ZM143.417 30.272L144.473 28.208H141.689C141.137 29.192 140.369 29.888 138.713 29.888C136.817 29.888 135.137 28.544 134.945 26.72H144.569C144.761 22.904 142.601 19.832 138.593 19.832C135.017 19.832 132.353 22.592 132.353 25.976C132.353 29.36 134.897 32.216 138.713 32.216C140.729 32.216 142.193 31.496 143.417 30.272ZM138.545 22.112C140.345 22.112 141.569 23.24 141.905 24.704H135.113C135.473 23.312 136.457 22.112 138.545 22.112ZM153.407 32V29.744H152.351C151.271 29.744 150.503 29.096 150.503 27.8V22.328H153.791V20.048H150.503V16.04L148.079 16.928L147.551 20.048H145.943L145.487 22.328H147.863V28.088C147.863 30.68 149.639 32.048 151.943 32.048C152.543 32.048 153.071 32.024 153.407 32ZM158.877 25.736C158.877 23.816 159.885 22.376 161.781 22.376H163.221V20.048H161.853C160.269 20.048 159.285 20.888 158.877 21.728V20.048H156.237V32H158.877V25.736ZM165.284 17.36H167.924V14.72H165.284V17.36ZM165.284 32H167.924V20.048H165.284V32ZM176.439 32.216C178.263 32.216 179.823 31.568 180.951 30.488L182.103 28.208H179.319C178.863 29.144 177.975 29.744 176.463 29.744C174.519 29.744 173.127 28.064 173.127 26C173.127 23.96 174.495 22.304 176.535 22.304C177.903 22.304 178.815 22.952 179.247 23.84H182.127C181.431 21.824 179.727 19.832 176.463 19.832C173.031 19.832 170.415 22.592 170.415 26C170.415 29.384 172.983 32.216 176.439 32.216ZM183.544 28.208L184.384 30.248C185.176 31.256 186.688 32.216 188.896 32.216C191.92 32.216 193.792 30.632 193.792 28.448C193.792 26.744 192.808 25.472 190.024 24.992L187.984 24.632C186.64 24.392 186.256 24.032 186.256 23.432C186.256 22.64 187.048 22.088 188.488 22.088C189.856 22.088 190.84 22.736 191.176 23.84H193.768L192.808 21.704C191.992 20.768 190.768 19.832 188.536 19.832C185.848 19.832 183.808 21.392 183.808 23.528C183.808 25.352 184.912 26.552 187.552 27.032L189.376 27.368C190.888 27.656 191.296 28.064 191.296 28.664C191.296 29.408 190.528 29.96 189.16 29.96C187.6 29.96 186.568 29.384 186.136 28.208H183.544Z" fill="#FFFFFF"/>
</svg>
| 0 |
public_repos/torchmetrics/docs/source/_static | public_repos/torchmetrics/docs/source/_static/images/icon.svg | <svg width="87" height="101" viewBox="0 0 87 101" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_4_50)">
<path d="M41.5884 0.710874L1.79245 23.7878C1.20288 24.0837 0.908094 24.6754 0.318525 25.2671C0.0784401 25.8261 -0.022724 26.4353 0.023739 27.0422V73.1961C0.0847992 73.8248 0.286322 74.4315 0.61331 74.9712C0.946899 75.6006 1.46013 76.1157 2.08723 76.4505L41.5884 99.5274C42.0986 99.9115 42.7192 100.119 43.3571 100.119C43.9949 100.119 44.6155 99.9115 45.1258 99.5274L84.6269 76.4505C85.254 76.1157 85.7672 75.6006 86.1008 74.9712C86.4278 74.4315 86.6293 73.8248 86.6904 73.1961V27.0718C86.6293 26.4431 86.4278 25.8364 86.1008 25.2967C85.7672 24.6673 85.254 24.1522 84.6269 23.8174L45.1258 0.740461C44.588 0.412282 43.9835 0.210025 43.3571 0.148743C42.733 0.200981 42.1286 0.393077 41.5884 0.710874Z" fill="url(#paint0_linear_4_50)"/>
<path d="M40.8917 55.884L40.8917 33.3066C40.8917 31.9232 39.7702 30.8017 38.3868 30.8017C37.0033 30.8017 35.8818 31.9232 35.8818 33.3066L35.8818 55.884C35.8818 57.2675 37.0033 58.389 38.3868 58.389C39.7702 58.389 40.8917 57.2675 40.8917 55.884Z" fill="white"/>
<path d="M60.9284 60.8969L25.865 60.8969C24.4799 60.8969 23.3571 62.0198 23.3571 63.4049C23.3571 64.79 24.4799 65.9128 25.865 65.9128L60.9284 65.9128C62.3134 65.9128 63.4363 64.79 63.4363 63.4049C63.4363 62.0198 62.3134 60.8969 60.9284 60.8969Z" fill="white"/>
<path d="M60.9313 55.8841L60.9313 28.2908C60.9313 26.9073 59.8098 25.7858 58.4264 25.7858C57.0429 25.7858 55.9214 26.9073 55.9214 28.2908L55.9214 55.8841C55.9214 57.2675 57.0429 58.389 58.4264 58.389C59.8098 58.389 60.9313 57.2675 60.9313 55.8841Z" fill="white"/>
<path d="M30.8719 55.884L30.8719 48.3543C30.8719 46.9708 29.7504 45.8493 28.367 45.8493C26.9835 45.8493 25.862 46.9708 25.862 48.3543L25.862 55.8841C25.862 57.2675 26.9835 58.389 28.367 58.389C29.7504 58.389 30.8719 57.2675 30.8719 55.884Z" fill="white"/>
<path d="M45.9016 38.3225V55.8841C45.9016 57.2675 47.0231 58.389 48.4066 58.389C49.79 58.389 50.9115 57.2675 50.9115 55.8841V38.3225C50.9115 36.9391 49.79 35.8176 48.4066 35.8176C47.0231 35.8176 45.9016 36.9391 45.9016 38.3225Z" fill="white"/>
</g>
<defs>
<linearGradient id="paint0_linear_4_50" x1="86.6904" y1="0.14874" x2="-2.4846" y2="97.8395" gradientUnits="userSpaceOnUse">
<stop stop-color="#792EE5"/>
<stop offset="1" stop-color="#428FF4"/>
</linearGradient>
<clipPath id="clip0_4_50">
<rect width="86.6667" height="100" fill="white" transform="translate(0.0237427 0.119171)"/>
</clipPath>
</defs>
</svg>
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/word_info_preserved.rst | .. customcarditem::
:header: Word Information Preserved
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
####################
Word Info. Preserved
####################
Module Interface
________________
.. autoclass:: torchmetrics.text.WordInfoPreserved
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.word_information_preserved
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/edit.rst | .. customcarditem::
:header: Edit Distance
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
#############
Edit Distance
#############
Module Interface
________________
.. autoclass:: torchmetrics.text.EditDistance
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.edit_distance
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/char_error_rate.rst | .. customcarditem::
:header: Character Error Rate
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
###############
Char Error Rate
###############
Module Interface
________________
.. autoclass:: torchmetrics.text.CharErrorRate
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.char_error_rate
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/word_info_lost.rst | .. customcarditem::
:header: Word Information Lost
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
###############
Word Info. Lost
###############
Module Interface
________________
.. autoclass:: torchmetrics.text.WordInfoLost
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.word_information_lost
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/squad.rst | .. customcarditem::
:header: SQuAD
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
#####
SQuAD
#####
Module Interface
________________
.. autoclass:: torchmetrics.text.SQuAD
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.squad
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/rouge_score.rst | .. customcarditem::
:header: ROUGE Score
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
###########
ROUGE Score
###########
Module Interface
________________
.. autoclass:: torchmetrics.text.rouge.ROUGEScore
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.rouge.rouge_score
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/translation_edit_rate.rst | .. customcarditem::
:header: Translation Edit Rate (TER)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
###########################
Translation Edit Rate (TER)
###########################
Module Interface
________________
.. autoclass:: torchmetrics.text.TranslationEditRate
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.translation_edit_rate
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/bert_score.rst | .. customcarditem::
:header: BERT Score
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
##########
BERT Score
##########
Module Interface
________________
.. autoclass:: torchmetrics.text.bert.BERTScore
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.bert.bert_score
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/perplexity.rst | .. customcarditem::
:header: Perplexity
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
##########
Perplexity
##########
Module Interface
________________
.. autoclass:: torchmetrics.text.perplexity.Perplexity
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.perplexity.perplexity
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/extended_edit_distance.rst | .. customcarditem::
:header: Extended Edit Distance
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
######################
Extended Edit Distance
######################
Module Interface
________________
.. autoclass:: torchmetrics.text.ExtendedEditDistance
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.extended_edit_distance
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/bleu_score.rst | .. customcarditem::
:header: BLEU Score
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
##########
BLEU Score
##########
Module Interface
________________
.. autoclass:: torchmetrics.text.BLEUScore
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.bleu_score
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/sacre_bleu_score.rst | .. customcarditem::
:header: Sacre BLEU Score
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
################
Sacre BLEU Score
################
Module Interface
________________
.. autoclass:: torchmetrics.text.SacreBLEUScore
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.sacre_bleu_score
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/infolm.rst | .. customcarditem::
:header: InfoLM
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
######
InfoLM
######
Module Interface
________________
.. autoclass:: torchmetrics.text.infolm.InfoLM
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.infolm.infolm
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/match_error_rate.rst | .. customcarditem::
:header: Match Error Rate
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
################
Match Error Rate
################
Module Interface
________________
.. autoclass:: torchmetrics.text.MatchErrorRate
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.match_error_rate
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/chrf_score.rst | .. customcarditem::
:header: ChrF Score
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
##########
ChrF Score
##########
Module Interface
________________
.. autoclass:: torchmetrics.text.CHRFScore
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.chrf_score
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/text/word_error_rate.rst | .. customcarditem::
:header: Word Error Rate
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/summarization.svg
:tags: Text
.. include:: ../links.rst
###############
Word Error Rate
###############
Module Interface
________________
.. autoclass:: torchmetrics.text.WordErrorRate
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.text.word_error_rate
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/wrappers/running.rst | .. customcarditem::
:header: Running
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/graph_classification.svg
:tags: Wrappers
.. include:: ../links.rst
#######
Running
#######
Module Interface
________________
.. autoclass:: torchmetrics.wrappers.Running
:exclude-members: update, compute
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/wrappers/classwise_wrapper.rst | .. customcarditem::
:header: Classwise Wrapper
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/graph_classification.svg
:tags: Wrappers
.. include:: ../links.rst
#################
Classwise Wrapper
#################
Module Interface
________________
.. autoclass:: torchmetrics.wrappers.ClasswiseWrapper
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/wrappers/min_max.rst | .. customcarditem::
:header: Min / Max
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/graph_classification.svg
:tags: Wrappers
.. include:: ../links.rst
#########
Min / Max
#########
Module Interface
________________
.. autoclass:: torchmetrics.wrappers.MinMaxMetric
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/wrappers/bootstrapper.rst | .. customcarditem::
:header: Bootstrapper
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/graph_classification.svg
:tags: Wrappers
.. include:: ../links.rst
############
Bootstrapper
############
Module Interface
________________
.. autoclass:: torchmetrics.wrappers.BootStrapper
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/wrappers/metric_tracker.rst | .. customcarditem::
:header: Metric Tracker
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/graph_classification.svg
:tags: Wrappers
.. include:: ../links.rst
##############
Metric Tracker
##############
Module Interface
________________
.. autoclass:: torchmetrics.wrappers.MetricTracker
:exclude-members: update, compute
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/wrappers/multi_task_wrapper.rst | .. customcarditem::
:header: Multi-task Wrapper
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/graph_classification.svg
:tags: Wrappers
.. include:: ../links.rst
####################
Multi-task Wrapper
####################
Module Interface
________________
.. autoclass:: torchmetrics.wrappers.MultitaskWrapper
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/wrappers/multi_output_wrapper.rst | .. customcarditem::
:header: Multi-output Wrapper
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/graph_classification.svg
:tags: Wrappers
.. include:: ../links.rst
####################
Multi-output Wrapper
####################
Module Interface
________________
.. autoclass:: torchmetrics.wrappers.MultioutputWrapper
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/audio/complex_scale_invariant_signal_noise_ratio.rst | .. customcarditem::
:header: Complex Scale-Invariant Signal-to-Noise Ratio (C-SI-SNR)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/audio_classification.svg
:tags: Audio
.. include:: ../links.rst
########################################################
Complex Scale-Invariant Signal-to-Noise Ratio (C-SI-SNR)
########################################################
Module Interface
________________
.. autoclass:: torchmetrics.audio.ComplexScaleInvariantSignalNoiseRatio
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.audio.complex_scale_invariant_signal_noise_ratio
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/audio/signal_noise_ratio.rst | .. customcarditem::
:header: Signal-to-Noise Ratio (SNR)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/audio_classification.svg
:tags: Audio
.. include:: ../links.rst
###########################
Signal-to-Noise Ratio (SNR)
###########################
Module Interface
________________
.. autoclass:: torchmetrics.audio.SignalNoiseRatio
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.audio.signal_noise_ratio
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/audio/scale_invariant_signal_noise_ratio.rst | .. customcarditem::
:header: Scale-Invariant Signal-to-Noise Ratio (SI-SNR)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/audio_classification.svg
:tags: Audio
.. include:: ../links.rst
##############################################
Scale-Invariant Signal-to-Noise Ratio (SI-SNR)
##############################################
Module Interface
________________
.. autoclass:: torchmetrics.audio.ScaleInvariantSignalNoiseRatio
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.audio.scale_invariant_signal_noise_ratio
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/audio/speech_reverberation_modulation_energy_ratio.rst | .. customcarditem::
:header: Speech-to-Reverberation Modulation Energy Ratio (SRMR)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/audio_classification.svg
:tags: Audio
.. include:: ../links.rst
######################################################
Speech-to-Reverberation Modulation Energy Ratio (SRMR)
######################################################
Module Interface
________________
.. autoclass:: torchmetrics.audio.srmr.SpeechReverberationModulationEnergyRatio
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.audio.srmr.speech_reverberation_modulation_energy_ratio
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/audio/scale_invariant_signal_distortion_ratio.rst | .. customcarditem::
:header: Scale-Invariant Signal-to-Distortion Ratio (SI-SDR)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/audio_classification.svg
:tags: Audio
.. include:: ../links.rst
###################################################
Scale-Invariant Signal-to-Distortion Ratio (SI-SDR)
###################################################
Module Interface
________________
.. autoclass:: torchmetrics.audio.ScaleInvariantSignalDistortionRatio
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.audio.scale_invariant_signal_distortion_ratio
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/audio/permutation_invariant_training.rst | .. customcarditem::
:header: Permutation Invariant Training (PIT)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/audio_classification.svg
:tags: Audio
.. include:: ../links.rst
####################################
Permutation Invariant Training (PIT)
####################################
Module Interface
________________
.. autoclass:: torchmetrics.audio.PermutationInvariantTraining
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.audio.permutation_invariant_training
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/audio/signal_distortion_ratio.rst | .. customcarditem::
:header: Signal to Distortion Ratio (SDR)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/audio_classification.svg
:tags: Audio
.. include:: ../links.rst
################################
Signal to Distortion Ratio (SDR)
################################
Module Interface
________________
.. autoclass:: torchmetrics.audio.SignalDistortionRatio
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.audio.signal_distortion_ratio
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/audio/short_time_objective_intelligibility.rst | .. customcarditem::
:header: Short-Time Objective Intelligibility (STOI)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/audio_classification.svg
:tags: Audio
.. include:: ../links.rst
###########################################
Short-Time Objective Intelligibility (STOI)
###########################################
Module Interface
________________
.. autoclass:: torchmetrics.audio.stoi.ShortTimeObjectiveIntelligibility
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.audio.stoi.short_time_objective_intelligibility
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/audio/source_aggregated_signal_distortion_ratio.rst | .. customcarditem::
:header: Source Aggregated Signal-to-Distortion Ratio (SA-SDR)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/audio_classification.svg
:tags: Audio
.. include:: ../links.rst
#####################################################
Source Aggregated Signal-to-Distortion Ratio (SA-SDR)
#####################################################
Module Interface
________________
.. autoclass:: torchmetrics.audio.sdr.SourceAggregatedSignalDistortionRatio
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.audio.sdr.source_aggregated_signal_distortion_ratio
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/audio/perceptual_evaluation_speech_quality.rst | .. customcarditem::
:header: Perceptual Evaluation of Speech Quality (PESQ)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/audio_classification.svg
:tags: Audio
.. include:: ../links.rst
##############################################
Perceptual Evaluation of Speech Quality (PESQ)
##############################################
Module Interface
________________
.. autoclass:: torchmetrics.audio.pesq.PerceptualEvaluationSpeechQuality
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.audio.pesq.perceptual_evaluation_speech_quality
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/references/utilities.rst | .. role:: hidden
:class: hidden-section
######################
torchmetrics.utilities
######################
In the following is listed public utility functions that may be beneficial to use in your own code. These functions are
not part of the public API and may change at any time.
***************************
torchmetrics.utilities.data
***************************
The `data` utilities are used to help with data manipulation, such as converting labels in classification from one
format to another.
select_topk
~~~~~~~~~~~
.. autofunction:: torchmetrics.utilities.data.select_topk
to_categorical
~~~~~~~~~~~~~~
.. autofunction:: torchmetrics.utilities.data.to_categorical
to_onehot
~~~~~~~~~
.. autofunction:: torchmetrics.utilities.data.to_onehot
dim_zero_cat
~~~~~~~~~~~~
.. autofunction:: torchmetrics.utilities.data.dim_zero_cat
dim_zero_max
~~~~~~~~~~~~
.. autofunction:: torchmetrics.utilities.data.dim_zero_max
dim_zero_mean
~~~~~~~~~~~~~
.. autofunction:: torchmetrics.utilities.data.dim_zero_mean
dim_zero_min
~~~~~~~~~~~~
.. autofunction:: torchmetrics.utilities.data.dim_zero_min
dim_zero_sum
~~~~~~~~~~~~
.. autofunction:: torchmetrics.utilities.data.dim_zero_sum
**********************************
torchmetrics.utilities.distributed
**********************************
The `distributed` utilities are used to help with synchronization of metrics across multiple processes.
gather_all_tensors
~~~~~~~~~~~~~~~~~~
.. autofunction:: torchmetrics.utilities.distributed.gather_all_tensors
:noindex:
*********************************
torchmetrics.utilities.exceptions
*********************************
TorchMetricsUserError
~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: torchmetrics.utilities.exceptions.TorchMetricsUserError
TorchMetricsUserWarning
~~~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: torchmetrics.utilities.exceptions.TorchMetricsUserWarning
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/references/metric.rst | .. role:: hidden
:class: hidden-section
###################
torchmetrics.Metric
###################
The base ``Metric`` class is an abstract base class that are used as the building block for all other Module
metrics.
.. autoclass:: torchmetrics.Metric
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/retrieval/r_precision.rst | .. customcarditem::
:header: Retrieval R-Precision
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/text_classification.svg
:tags: Retrieval
.. include:: ../links.rst
#####################
Retrieval R-Precision
#####################
Module Interface
________________
.. autoclass:: torchmetrics.retrieval.RetrievalRPrecision
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.retrieval.retrieval_r_precision
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/retrieval/mrr.rst | .. customcarditem::
:header: Retrieval Mean Reciprocal Rank (MRR)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/text_classification.svg
:tags: Retrieval
.. include:: ../links.rst
####################################
Retrieval Mean Reciprocal Rank (MRR)
####################################
Module Interface
________________
.. autoclass:: torchmetrics.retrieval.RetrievalMRR
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.retrieval.retrieval_reciprocal_rank
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/retrieval/map.rst | .. customcarditem::
:header: Retrieval Mean Average Precision (MAP)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/text_classification.svg
:tags: Retrieval
.. include:: ../links.rst
######################################
Retrieval Mean Average Precision (MAP)
######################################
Module Interface
________________
.. autoclass:: torchmetrics.retrieval.RetrievalMAP
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.retrieval.retrieval_average_precision
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/retrieval/fall_out.rst | .. customcarditem::
:header: Retrieval Fall-Out
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/text_classification.svg
:tags: Retrieval
.. include:: ../links.rst
##################
Retrieval Fall-Out
##################
Module Interface
________________
.. autoclass:: torchmetrics.retrieval.RetrievalFallOut
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.retrieval.retrieval_fall_out
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/retrieval/recall.rst | .. customcarditem::
:header: Retrieval Recall
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/text_classification.svg
:tags: Retrieval
.. include:: ../links.rst
################
Retrieval Recall
################
Module Interface
________________
.. autoclass:: torchmetrics.retrieval.RetrievalRecall
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.retrieval.retrieval_recall
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/retrieval/hit_rate.rst | .. customcarditem::
:header: Retrieval Hit Rate
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/text_classification.svg
:tags: Retrieval
.. include:: ../links.rst
##################
Retrieval Hit Rate
##################
Module Interface
________________
.. autoclass:: torchmetrics.retrieval.RetrievalHitRate
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.retrieval.retrieval_hit_rate
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/retrieval/precision.rst | .. customcarditem::
:header: Retrieval Precision
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/text_classification.svg
:tags: Retrieval
.. include:: ../links.rst
###################
Retrieval Precision
###################
Module Interface
________________
.. autoclass:: torchmetrics.retrieval.RetrievalPrecision
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.retrieval.retrieval_precision
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/retrieval/normalized_dcg.rst | .. customcarditem::
:header: Retrieval Normalized Discounted Cumulative Gain (DCG)
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/text_classification.svg
:tags: Retrieval
.. include:: ../links.rst
########################
Retrieval Normalized DCG
########################
Module Interface
________________
.. autoclass:: torchmetrics.retrieval.RetrievalNormalizedDCG
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.retrieval.retrieval_normalized_dcg
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/retrieval/precision_recall_curve.rst | .. customcarditem::
:header: Precision Recall Curve
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/text_classification.svg
:tags: Retrieval
.. include:: ../links.rst
######################
Precision Recall Curve
######################
Module Interface
________________
.. autoclass:: torchmetrics.retrieval.RetrievalPrecisionRecallCurve
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.retrieval.retrieval_precision_recall_curve
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/multimodal/clip_score.rst | .. customcarditem::
:header: CLIP Score
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/image_classification.svg
:tags: Image
.. include:: ../links.rst
##########
CLIP Score
##########
Module Interface
________________
.. autoclass:: torchmetrics.multimodal.clip_score.CLIPScore
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.multimodal.clip_score.clip_score
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/multimodal/clip_iqa.rst | .. customcarditem::
:header: CLIP IQA
:image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/image_classification.svg
:tags: Image
.. include:: ../links.rst
########################################
CLIP Image Quality Assessment (CLIP-IQA)
########################################
Module Interface
________________
.. autoclass:: torchmetrics.multimodal.CLIPImageQualityAssessment
:noindex:
:exclude-members: update, compute
Functional Interface
____________________
.. autofunction:: torchmetrics.functional.multimodal.clip_image_quality_assessment
:noindex:
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/pages/lightning.rst | .. testsetup:: *
import torch
from torch.nn import Module
from lightning.pytorch import LightningModule
from torchmetrics import Metric
#################################
TorchMetrics in PyTorch Lightning
#################################
TorchMetrics was originally created as part of `PyTorch Lightning <https://github.com/Lightning-AI/pytorch-lightning>`_, a powerful deep learning research
framework designed for scaling models without boilerplate.
.. note::
TorchMetrics always offers compatibility with the last 2 major PyTorch Lightning versions, but we recommend to always keep both frameworks
up-to-date for the best experience.
While TorchMetrics was built to be used with native PyTorch, using TorchMetrics with Lightning offers additional benefits:
* Modular metrics are automatically placed on the correct device when properly defined inside a LightningModule.
This means that your data will always be placed on the same device as your metrics. No need to call ``.to(device)`` anymore!
* Native support for logging metrics in Lightning using
`self.log <https://pytorch-lightning.readthedocs.io/en/stable/extensions/logging.html#logging-from-a-lightningmodule>`_ inside
your LightningModule.
* The ``.reset()`` method of the metric will automatically be called at the end of an epoch.
The example below shows how to use a metric in your `LightningModule <https://pytorch-lightning.readthedocs.io/en/stable/common/lightning_module.html>`_:
.. testcode:: python
class MyModel(LightningModule):
def __init__(self, num_classes):
...
self.accuracy = torchmetrics.classification.Accuracy(task="multiclass", num_classes=num_classes)
def training_step(self, batch, batch_idx):
x, y = batch
preds = self(x)
...
# log step metric
self.accuracy(preds, y)
self.log('train_acc_step', self.accuracy)
...
def on_train_epoch_end(self):
# log epoch metric
self.log('train_acc_epoch', self.accuracy)
Metric logging in Lightning happens through the ``self.log`` or ``self.log_dict`` method. Both methods only support the
logging of *scalar-tensors*. While the vast majority of metrics in torchmetrics returns a scalar tensor, some metrics
such as :class:`~torchmetrics.classification.confusion_matrix.ConfusionMatrix`,
:class:`~torchmetrics.classification.roc.ROC`,
:class:`~torchmetrics.detection.mean_ap.MeanAveragePrecision`, :class:`~torchmetrics.text.rouge.ROUGEScore` return
outputs that are non-scalar tensors (often dicts or list of tensors) and should therefore be dealt with separately.
For info about the return type and shape please look at the documentation for the ``compute`` method for each metric
you want to log.
********************
Logging TorchMetrics
********************
Logging metrics can be done in two ways: either logging the metric object directly or the computed metric values.
When :class:`~torchmetrics.Metric` objects, which return a scalar tensor are logged directly in Lightning using the
LightningModule `self.log <https://pytorch-lightning.readthedocs.io/en/stable/extensions/logging.html#logging-from-a-lightningmodule>`_
method, Lightning will log the metric based on ``on_step`` and ``on_epoch`` flags present in ``self.log(...)``. If
``on_epoch`` is True, the logger automatically logs the end of epoch metric value by calling ``.compute()``.
.. note::
``sync_dist``, ``sync_dist_group`` and ``reduce_fx`` flags from ``self.log(...)`` don't affect the metric logging
in any manner. The metric class contains its own distributed synchronization logic.
This however is only true for metrics that inherit the base class ``Metric``,
and thus the functional metric API provides no support for in-built distributed synchronization
or reduction functions.
.. testcode:: python
class MyModule(LightningModule):
def __init__(self, num_classes):
...
self.train_acc = torchmetrics.classification.Accuracy(task="multiclass", num_classes=num_classes)
self.valid_acc = torchmetrics.classification.Accuracy(task="multiclass", num_classes=num_classes)
def training_step(self, batch, batch_idx):
x, y = batch
preds = self(x)
...
self.train_acc(preds, y)
self.log('train_acc', self.train_acc, on_step=True, on_epoch=False)
def validation_step(self, batch, batch_idx):
logits = self(x)
...
self.valid_acc(logits, y)
self.log('valid_acc', self.valid_acc, on_step=True, on_epoch=True)
As an alternative to logging the metric object and letting Lightning take care of when to reset the metric etc. you can
also manually log the output of the metrics.
.. testcode:: python
class MyModule(LightningModule):
def __init__(self):
...
self.train_acc = torchmetrics.classification.Accuracy(task="multiclass", num_classes=num_classes)
self.valid_acc = torchmetrics.classification.Accuracy(task="multiclass", num_classes=num_classes)
def training_step(self, batch, batch_idx):
x, y = batch
preds = self(x)
...
batch_value = self.train_acc(preds, y)
self.log('train_acc_step', batch_value)
def on_train_epoch_end(self):
self.train_acc.reset()
def validation_step(self, batch, batch_idx):
logits = self(x)
...
self.valid_acc.update(logits, y)
def on_validation_epoch_end(self, outputs):
self.log('valid_acc_epoch', self.valid_acc.compute())
self.valid_acc.reset()
Note that logging metrics this way will require you to manually reset the metrics at the end of the epoch yourself.
In general, we recommend logging the metric object to make sure that metrics are correctly computed and reset.
Additionally, we highly recommend that the two ways of logging are not mixed as it can lead to wrong results.
.. note::
When using any Modular metric, calling ``self.metric(...)`` or ``self.metric.forward(...)`` serves the dual purpose
of calling ``self.metric.update()`` on its input and simultaneously returning the metric value over the provided
input. So if you are logging a metric *only* on epoch-level (as in the example above), it is recommended to call
``self.metric.update()`` directly to avoid the extra computation.
.. testcode:: python
class MyModule(LightningModule):
def __init__(self, num_classes):
...
self.valid_acc = torchmetrics.classification.Accuracy(task="multiclass", num_classes=num_classes)
def validation_step(self, batch, batch_idx):
logits = self(x)
...
self.valid_acc.update(logits, y)
self.log('valid_acc', self.valid_acc, on_step=True, on_epoch=True)
***************
Common Pitfalls
***************
The following contains a list of pitfalls to be aware of:
* Modular metrics contain internal states that should belong to only one DataLoader. In case you are using multiple DataLoaders,
it is recommended to initialize a separate modular metric instances for each DataLoader and use them separately. The same holds
for using separate metrics for training, validation and testing.
.. testcode:: python
class MyModule(LightningModule):
def __init__(self, num_classes):
...
self.val_acc = nn.ModuleList(
[torchmetrics.classification.Accuracy(task="multiclass", num_classes=num_classes) for _ in range(2)]
)
def val_dataloader(self):
return [DataLoader(...), DataLoader(...)]
def validation_step(self, batch, batch_idx, dataloader_idx):
x, y = batch
preds = self(x)
...
self.val_acc[dataloader_idx](preds, y)
self.log('val_acc', self.val_acc[dataloader_idx])
* Mixing the two logging methods by calling ``self.log("val", self.metric)`` in ``{training|validation|test}_step``
method and then calling ``self.log("val", self.metric.compute())`` in the corresponding
``on_{train|validation|test}_epoch_end`` method.
Because the object is logged in the first case, Lightning will reset the metric before calling the second line leading
to errors or nonsense results.
* Calling ``self.log("val", self.metric(preds, target))`` with the intention of logging the metric object. Because
``self.metric(preds, target)`` corresponds to calling the forward method, this will return a tensor and not the
metric object. Such logging will be wrong in this case. Instead, it is essential to separate into several lines:
.. testcode:: python
def training_step(self, batch, batch_idx):
x, y = batch
preds = self(x)
...
# log step metric
self.accuracy(preds, y) # compute metrics
self.log('train_acc_step', self.accuracy) # log metric object
* Using :class:`~torchmetrics.wrappers.MetricTracker` wrapper with Lightning is a special case, because the wrapper in itself is not a metric
i.e. it does not inherit from the base :class:`~torchmetrics.Metric` class but instead from :class:`~torch.nn.ModuleList`. Thus,
to log the output of this metric one needs to manually log the returned values (not the object) using ``self.log``
and for epoch level logging this should be done in the appropriate ``on_{train|validation|test}_epoch_end`` method.
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/pages/quickstart.rst | ###########
Quick Start
###########
TorchMetrics is a collection of 100+ PyTorch metrics implementations and an easy-to-use API to create custom metrics. It offers:
* A standardized interface to increase reproducibility
* Reduces Boilerplate
* Distributed-training compatible
* Rigorously tested
* Automatic accumulation over batches
* Automatic synchronization between multiple devices
You can use TorchMetrics in any PyTorch model, or within `PyTorch Lightning <https://pytorch-lightning.readthedocs.io/en/stable/>`_ to enjoy additional features:
* This means that your data will always be placed on the same device as your metrics.
* Native support for logging metrics in Lightning to reduce even more boilerplate.
Install
*******
You can install TorchMetrics using pip or conda:
.. code-block:: bash
# Python Package Index (PyPI)
pip install torchmetrics
# Conda
conda install -c conda-forge torchmetrics
Eventually if there is a missing PyTorch wheel for your OS or Python version you can simply compile `PyTorch from source <https://github.com/pytorch/pytorch>`_:
.. code-block:: bash
# Optional if you do not need compile GPU support
export USE_CUDA=0 # just to keep it simple
# you can install the latest state from master
pip install git+https://github.com/pytorch/pytorch.git
# OR set a particular PyTorch release
pip install git+https://github.com/pytorch/pytorch.git@<release-tag>
# and finalize with installing TorchMetrics
pip install torchmetrics
Using TorchMetrics
******************
Functional metrics
~~~~~~~~~~~~~~~~~~
Similar to `torch.nn <https://pytorch.org/docs/stable/nn>`_, most metrics have both a class-based and a functional version.
The functional versions implement the basic operations required for computing each metric.
They are simple python functions that as input take `torch.tensors <https://pytorch.org/docs/stable/tensors.html>`_
and return the corresponding metric as a ``torch.tensor``.
The code-snippet below shows a simple example for calculating the accuracy using the functional interface:
.. testcode::
import torch
# import our library
import torchmetrics
# simulate a classification problem
preds = torch.randn(10, 5).softmax(dim=-1)
target = torch.randint(5, (10,))
acc = torchmetrics.functional.accuracy(preds, target, task="multiclass", num_classes=5)
Module metrics
~~~~~~~~~~~~~~
Nearly all functional metrics have a corresponding class-based metric that calls it a functional counterpart underneath.
The class-based metrics are characterized by having one or more internal metrics states (similar to the parameters of
the PyTorch module) that allow them to offer additional functionalities:
* Accumulation of multiple batches
* Automatic synchronization between multiple devices
* Metric arithmetic
The code below shows how to use the class-based interface:
.. testcode::
import torch
# import our library
import torchmetrics
# initialize metric
metric = torchmetrics.classification.Accuracy(task="multiclass", num_classes=5)
n_batches = 10
for i in range(n_batches):
# simulate a classification problem
preds = torch.randn(10, 5).softmax(dim=-1)
target = torch.randint(5, (10,))
# metric on current batch
acc = metric(preds, target)
print(f"Accuracy on batch {i}: {acc}")
# metric on all batches using custom accumulation
acc = metric.compute()
print(f"Accuracy on all data: {acc}")
# Resetting internal state such that metric ready for new data
metric.reset()
.. testoutput::
:hide:
:options: +ELLIPSIS, +NORMALIZE_WHITESPACE
Accuracy on batch ...
Implementing your own metric
****************************
Implementing your own metric is as easy as subclassing a :class:`torch.nn.Module`. Simply, subclass :class:`~torchmetrics.Metric` and do the following:
1. Implement ``__init__`` where you call ``self.add_state`` for every internal state that is needed for the metrics computations
2. Implement ``update`` method, where all logic that is necessary for updating metric states go
3. Implement ``compute`` method, where the final metric computations happens
For practical examples and more info about implementing a metric, please see this :ref:`page <implement>`.
Development Environment
~~~~~~~~~~~~~~~~~~~~~~~
TorchMetrics provides a `Devcontainer <https://code.visualstudio.com/docs/remote/containers>`_ configuration for `Visual Studio Code <https://code.visualstudio.com/>`_ to use a `Docker container <https://www.docker.com/>`_ as a pre-configured development environment.
This avoids struggles setting up a development environment and makes them reproducible and consistent.
Please follow the `installation instructions <https://code.visualstudio.com/docs/remote/containers#_installation>`_ and make yourself familiar with the `container tutorials <https://code.visualstudio.com/docs/remote/containers-tutorial>`_ if you want to use them.
In order to use GPUs, you can enable them within the ``.devcontainer/devcontainer.json`` file.
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/pages/overview.rst | .. testsetup:: *
import torch
from lightning.pytorch import LightningModule
##################
Structure Overview
##################
TorchMetrics is a Metrics API created for easy metric development and usage in
PyTorch and PyTorch Lightning. It is rigorously tested for all edge cases and includes a growing list of
common metric implementations.
The metrics API provides ``update()``, ``compute()``, ``reset()`` functions to the user. The metric :ref:`base class <references/metric:torchmetrics.Metric>` inherits
:class:`torch.nn.Module` which allows us to call ``metric(...)`` directly. The ``forward()`` method of the base ``Metric`` class
serves the dual purpose of calling ``update()`` on its input and simultaneously returning the value of the metric over the
provided input.
These metrics work with DDP in PyTorch and PyTorch Lightning by default. When ``.compute()`` is called in
distributed mode, the internal state of each metric is synced and reduced across each process, so that the
logic present in ``.compute()`` is applied to state information from all processes.
This metrics API is independent of PyTorch Lightning. Metrics can directly be used in PyTorch as shown in the example:
.. code-block:: python
from torchmetrics.classification import BinaryAccuracy
train_accuracy = BinaryAccuracy()
valid_accuracy = BinaryAccuracy()
for epoch in range(epochs):
for x, y in train_data:
y_hat = model(x)
# training step accuracy
batch_acc = train_accuracy(y_hat, y)
print(f"Accuracy of batch{i} is {batch_acc}")
for x, y in valid_data:
y_hat = model(x)
valid_accuracy.update(y_hat, y)
# total accuracy over all training batches
total_train_accuracy = train_accuracy.compute()
# total accuracy over all validation batches
total_valid_accuracy = valid_accuracy.compute()
print(f"Training acc for epoch {epoch}: {total_train_accuracy}")
print(f"Validation acc for epoch {epoch}: {total_valid_accuracy}")
# Reset metric states after each epoch
train_accuracy.reset()
valid_accuracy.reset()
.. note::
Metrics contain internal states that keep track of the data seen so far.
Do not mix metric states across training, validation and testing.
It is highly recommended to re-initialize the metric per mode as
shown in the examples above.
.. note::
Metric states are **not** added to the models ``state_dict`` by default.
To change this, after initializing the metric, the method ``.persistent(mode)`` can
be used to enable (``mode=True``) or disable (``mode=False``) this behaviour.
.. note::
Due to specialized logic around metric states, we in general do **not** recommend
that metrics are initialized inside other metrics (nested metrics), as this can lead
to weird behaviour. Instead consider subclassing a metric or use
``torchmetrics.MetricCollection``.
*******************
Metrics and devices
*******************
Metrics are simple subclasses of :class:`~torch.nn.Module` and their metric states behave
similar to buffers and parameters of modules. This means that metrics states should
be moved to the same device as the input of the metric:
.. code-block:: python
from torchmetrics.classification import BinaryAccuracy
target = torch.tensor([1, 1, 0, 0], device=torch.device("cuda", 0))
preds = torch.tensor([0, 1, 0, 0], device=torch.device("cuda", 0))
# Metric states are always initialized on cpu, and needs to be moved to
# the correct device
confmat = BinaryAccuracy().to(torch.device("cuda", 0))
out = confmat(preds, target)
print(out.device) # cuda:0
However, when **properly defined** inside a :class:`~torch.nn.Module` or
`LightningModule <https://pytorch-lightning.readthedocs.io/en/stable/common/lightning_module.html>`_ the metric will
be automatically moved to the same device as the module when using ``.to(device)``. Being
**properly defined** means that the metric is correctly identified as a child module of the
model (check ``.children()`` attribute of the model). Therefore, metrics cannot be placed
in native python ``list`` and ``dict``, as they will not be correctly identified
as child modules. Instead of ``list`` use :class:`~torch.nn.ModuleList` and instead of
``dict`` use :class:`~torch.nn.ModuleDict`. Furthermore, when working with multiple metrics
the native `MetricCollection`_ module can also be used to wrap multiple metrics.
.. testcode::
from torchmetrics import MetricCollection
from torchmetrics.classification import BinaryAccuracy
class MyModule(torch.nn.Module):
def __init__(self):
...
# valid ways metrics will be identified as child modules
self.metric1 = BinaryAccuracy()
self.metric2 = nn.ModuleList(BinaryAccuracy())
self.metric3 = nn.ModuleDict({'accuracy': BinaryAccuracy()})
self.metric4 = MetricCollection([BinaryAccuracy()]) # torchmetrics built-in collection class
def forward(self, batch):
data, target = batch
preds = self(data)
...
val1 = self.metric1(preds, target)
val2 = self.metric2[0](preds, target)
val3 = self.metric3['accuracy'](preds, target)
val4 = self.metric4(preds, target)
You can always check which device the metric is located on using the `.device` property.
*****************************
Metrics and memory management
*****************************
As stated before, metrics have states and those states take up a certain amount of memory depending on the metric.
In general metrics can be divided into two categories when we talk about memory management:
* Metrics with tensor states: These metrics only have states that are instances of :class:`~torch.Tensor`. When these
kind of metrics are updated the values of those tensors are updated. Importantly the size of the tensors is
**constant** meaning that regardless of how much data is passed to the metric, its memory footprint will not change.
* Metrics with list states: These metrics have at least one state that is a list, which gets tensors appended as the
metric is updated. Importantly the size of the list is therefore **not constant** and will grow. The growth depends
on the particular metric (some metrics only need to store a single value per sample, some much more).
You can always check the current metric state by accessing the `.metric_state` property, and checking if any of the
states are lists.
.. testcode::
import torch
from torchmetrics.regression import SpearmanCorrCoef
gen = torch.manual_seed(42)
metric = SpearmanCorrCoef()
metric(torch.rand(2,), torch.rand(2,))
print(metric.metric_state)
metric(torch.rand(2,), torch.rand(2,))
print(metric.metric_state)
.. testoutput::
:options: +NORMALIZE_WHITESPACE
{'preds': [tensor([0.8823, 0.9150])], 'target': [tensor([0.3829, 0.9593])]}
{'preds': [tensor([0.8823, 0.9150]), tensor([0.3904, 0.6009])], 'target': [tensor([0.3829, 0.9593]), tensor([0.2566, 0.7936])]}
In general we have a few recommendations for memory management:
* When done with a metric, we always recommend calling the `reset` method. The reason for this being that the python
garbage collector can struggle to totally clean the metric states if this is not done. In the worst case, this can
lead to a memory leak if multiple instances of the same metric for different purposes are created in the same script.
* Better to always try to reuse the same instance of a metric instead of initializing a new one. Calling the `reset` method
returns the metric to its initial state, and can therefore be used to reuse the same instance. However, we still
highly recommend to use **different** instances from training, validation and testing.
* If only the results on a batch level are needed e.g no aggregation or alternatively if you have a small dataset that
fits into iteration of evaluation, we can recommend using the functional API instead as it does not keep an internal
state and memory is therefore freed after each call.
See :ref:`Metric kwargs` for different advanced settings for controlling the memory footprint of metrics.
***********************************************
Metrics in Distributed Data Parallel (DDP) mode
***********************************************
When using metrics in `Distributed Data Parallel (DDP) <https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html>`_
mode, one should be aware that DDP will add additional samples to your dataset if the size of your dataset is
not equally divisible by ``batch_size * num_processors``. The added samples will always be replicates of datapoints
already in your dataset. This is done to secure an equal load for all processes. However, this has the consequence
that the calculated metric value will be slightly biased towards those replicated samples, leading to a wrong result.
During training and/or validation this may not be important, however it is highly recommended when evaluating
the test dataset to only run on a single gpu or use a `join <https://pytorch.org/docs/stable/_modules/torch/nn/parallel/distributed.html#DistributedDataParallel.join>`_
context in conjunction with DDP to prevent this behaviour.
****************************
Metrics and 16-bit precision
****************************
Most metrics in our collection can be used with 16-bit precision (``torch.half``) tensors. However, we have found
the following limitations:
* In general ``pytorch`` had better support for 16-bit precision much earlier on GPU than CPU. Therefore, we
recommend that anyone that want to use metrics with half precision on CPU, upgrade to at least pytorch v1.6
where support for operations such as addition, subtraction, multiplication etc. was added.
* Some metrics does not work at all in half precision on CPU. We have explicitly stated this in their docstring,
but they are also listed below:
- :ref:`image/peak_signal_noise_ratio:Peak Signal-to-Noise Ratio (PSNR)`
- :ref:`image/structural_similarity:Structural Similarity Index Measure (SSIM)`
- :ref:`regression/kl_divergence:KL Divergence`
You can always check the precision/dtype of the metric by checking the `.dtype` property.
*****************
Metric Arithmetic
*****************
Metrics support most of python built-in operators for arithmetic, logic and bitwise operations.
For example for a metric that should return the sum of two different metrics, implementing a new metric is an
overhead that is not necessary. It can now be done with:
.. code-block:: python
first_metric = MyFirstMetric()
second_metric = MySecondMetric()
new_metric = first_metric + second_metric
``new_metric.update(*args, **kwargs)`` now calls update of ``first_metric`` and ``second_metric``. It forwards
all positional arguments but forwards only the keyword arguments that are available in respective metric's update
declaration. Similarly ``new_metric.compute()`` now calls compute of ``first_metric`` and ``second_metric`` and
adds the results up. It is important to note that all implemented operations always return a new metric object. This means
that the line ``first_metric == second_metric`` will not return a bool indicating if ``first_metric`` and ``second_metric``
is the same metric, but will return a new metric that checks if the ``first_metric.compute() == second_metric.compute()``.
This pattern is implemented for the following operators (with ``a`` being metrics and ``b`` being metrics, tensors, integer or floats):
* Addition (``a + b``)
* Bitwise AND (``a & b``)
* Equality (``a == b``)
* Floordivision (``a // b``)
* Greater Equal (``a >= b``)
* Greater (``a > b``)
* Less Equal (``a <= b``)
* Less (``a < b``)
* Matrix Multiplication (``a @ b``)
* Modulo (``a % b``)
* Multiplication (``a * b``)
* Inequality (``a != b``)
* Bitwise OR (``a | b``)
* Power (``a ** b``)
* Subtraction (``a - b``)
* True Division (``a / b``)
* Bitwise XOR (``a ^ b``)
* Absolute Value (``abs(a)``)
* Inversion (``~a``)
* Negative Value (``neg(a)``)
* Positive Value (``pos(a)``)
* Indexing (``a[0]``)
.. note::
Some of these operations are only fully supported from Pytorch v1.4 and onwards, explicitly we found:
``add``, ``mul``, ``rmatmul``, ``rsub``, ``rmod``
****************
MetricCollection
****************
In many cases it is beneficial to evaluate the model output by multiple metrics.
In this case the ``MetricCollection`` class may come in handy. It accepts a sequence
of metrics and wraps these into a single callable metric class, with the same
interface as any other metric.
Example:
.. testcode::
from torchmetrics import MetricCollection
from torchmetrics.classification import MulticlassAccuracy, MulticlassPrecision, MulticlassRecall
target = torch.tensor([0, 2, 0, 2, 0, 1, 0, 2])
preds = torch.tensor([2, 1, 2, 0, 1, 2, 2, 2])
metric_collection = MetricCollection([
MulticlassAccuracy(num_classes=3, average="micro"),
MulticlassPrecision(num_classes=3, average="macro"),
MulticlassRecall(num_classes=3, average="macro")
])
print(metric_collection(preds, target))
.. testoutput::
:options: +NORMALIZE_WHITESPACE
{'MulticlassAccuracy': tensor(0.1250),
'MulticlassPrecision': tensor(0.0667),
'MulticlassRecall': tensor(0.1111)}
Similarly it can also reduce the amount of code required to log multiple metrics
inside your LightningModule. In most cases we just have to replace ``self.log`` with ``self.log_dict``.
.. testcode::
from torchmetrics import MetricCollection
from torchmetrics.classification import MulticlassAccuracy, MulticlassPrecision, MulticlassRecall
class MyModule(LightningModule):
def __init__(self, num_classes: int):
super().__init__()
metrics = MetricCollection([
MulticlassAccuracy(num_classes), MulticlassPrecision(num_classes), MulticlassRecall(num_classes)
])
self.train_metrics = metrics.clone(prefix='train_')
self.valid_metrics = metrics.clone(prefix='val_')
def training_step(self, batch, batch_idx):
logits = self(x)
# ...
output = self.train_metrics(logits, y)
# use log_dict instead of log
# metrics are logged with keys: train_Accuracy, train_Precision and train_Recall
self.log_dict(output)
def validation_step(self, batch, batch_idx):
logits = self(x)
# ...
self.valid_metrics.update(logits, y)
def on_validation_epoch_end(self):
# use log_dict instead of log
# metrics are logged with keys: val_Accuracy, val_Precision and val_Recall
output = self.valid_metrics.compute()
self.log_dict(output)
# remember to reset metrics at the end of the epoch
self.valid_metrics.reset()
.. note::
`MetricCollection` as default assumes that all the metrics in the collection
have the same call signature. If this is not the case, input that should be
given to different metrics can given as keyword arguments to the collection.
An additional advantage of using the ``MetricCollection`` object is that it will
automatically try to reduce the computations needed by finding groups of metrics
that share the same underlying metric state. If such a group of metrics is found
only one of them is actually updated and the updated state will be broadcasted to
the rest of the metrics within the group. In the example above, this will lead to
a 2-3x lower computational cost compared to disabling this feature in the case of
the validation metrics where only ``update`` is called (this feature does not work
in combination with ``forward``). However, this speedup comes with a fixed cost upfront,
where the state-groups have to be determined after the first update. In case the groups
are known beforehand, these can also be set manually to avoid this extra cost of the
dynamic search. See the *compute_groups* argument in the class docs below for more
information on this topic.
.. autoclass:: torchmetrics.MetricCollection
:exclude-members: update, compute, forward
***************
Metric wrappers
***************
In some cases it is beneficial to transform the output of one metric in some way or add additional logic. For this we
have implemented a few *Wrapper* metrics. Wrapper metrics always take another :class:`~torchmetrics.Metric` or (
:class:`~torchmetrics.MetricCollection`) as input and wraps it in some way. A good example of this is the
:class:`~torchmetrics.wrappers.ClasswiseWrapper` that allows for easy altering the output of certain classification
metrics to also include label information.
.. testcode::
from torchmetrics.classification import MulticlassAccuracy
from torchmetrics.wrappers import ClasswiseWrapper
# creating metrics
base_metric = MulticlassAccuracy(num_classes=3, average=None)
wrapped_metric = ClasswiseWrapper(base_metric, labels=["cat", "dog", "fish"])
# sample prediction and GT
target = torch.tensor([0, 2, 0, 2, 0, 1, 0, 2])
preds = torch.tensor([2, 1, 2, 0, 1, 2, 2, 2])
# showing the metric results
print(base_metric(preds, target)) # this returns a simple tensor without label info
print(wrapped_metric(preds, target)) # this returns a dict with label info
.. testoutput::
:options: +NORMALIZE_WHITESPACE
tensor([0.0000, 0.0000, 0.3333])
{'multiclassaccuracy_cat': tensor(0.),
'multiclassaccuracy_dog': tensor(0.),
'multiclassaccuracy_fish': tensor(0.3333)}
Another good example of wrappers is the :class:`~torchmetrics.wrappers.BootStrapper` that allows for easy bootstrapping
of metrics e.g. computation of confidence intervals by resampling of input data.
.. testcode::
from torchmetrics.classification import MulticlassAccuracy
from torchmetrics.wrappers import BootStrapper
# creating metrics
wrapped_metric = BootStrapper(MulticlassAccuracy(num_classes=3))
# sample prediction and GT
target = torch.tensor([0, 2, 0, 2, 0, 1, 0, 2])
preds = torch.tensor([2, 1, 2, 0, 1, 2, 2, 2])
# showing the metric results
print(wrapped_metric(preds, target)) # this returns a dict with label info
.. testoutput::
:options: +NORMALIZE_WHITESPACE
{'mean': tensor(0.1476), 'std': tensor(0.0613)}
You can see all implemented wrappers under the wrapper section of the API docs.
****************************
Module vs Functional Metrics
****************************
The functional metrics follow the simple paradigm input in, output out.
This means they don't provide any advanced mechanisms for syncing across DDP nodes or aggregation over batches.
They simply compute the metric value based on the given inputs.
Also, the integration within other parts of PyTorch Lightning will never be as tight as with the Module-based interface.
If you look for just computing the values, the functional metrics are the way to go.
However, if you are looking for the best integration and user experience, please consider also using the Module interface.
*****************************
Metrics and differentiability
*****************************
Metrics support backpropagation, if all computations involved in the metric calculation
are differentiable. All modular metric classes have the property ``is_differentiable`` that determines
if a metric is differentiable or not.
However, note that the cached state is detached from the computational
graph and cannot be back-propagated. Not doing this would mean storing the computational
graph for each update call, which can lead to out-of-memory errors.
In practice this means that:
.. code-block:: python
MyMetric.is_differentiable # returns True if metric is differentiable
metric = MyMetric()
val = metric(pred, target) # this value can be back-propagated
val = metric.compute() # this value cannot be back-propagated
A functional metric is differentiable if its corresponding modular metric is differentiable.
***************************************
Metrics and hyperparameter optimization
***************************************
If you want to directly optimize a metric it needs to support backpropagation (see section above).
However, if you are just interested in using a metric for hyperparameter tuning and are not sure
if the metric should be maximized or minimized, all modular metric classes have the ``higher_is_better``
property that can be used to determine this:
.. code-block:: python
# returns True because accuracy is optimal when it is maximized
torchmetrics.classification.Accuracy.higher_is_better
# returns False because the mean squared error is optimal when it is minimized
torchmetrics.MeanSquaredError.higher_is_better
.. _Metric kwargs:
************************
Advanced metric settings
************************
The following is a list of additional arguments that can be given to any metric class (in the ``**kwargs`` argument)
that will alter how metric states are stored and synced.
If you are running metrics on GPU and are encountering that you are running out of GPU VRAM then the following
argument can help:
- ``compute_on_cpu``: will automatically move the metric states to cpu after calling ``update``, making sure that
GPU memory is not filling up. The consequence will be that the ``compute`` method will be called on CPU instead
of GPU. Only applies to metric states that are lists.
- ``compute_with_cache``: This argument indicates if the result after calling the ``compute`` method should be cached.
By default this is ``True`` meaning that repeated calls to ``compute`` (with no change to the metric state in between)
does not recompute the metric but just returns the cache. By setting it to ``False`` the metric will be recomputed
every time ``compute`` is called, but it can also help clean up a bit of memory.
If you are running in a distributed environment, TorchMetrics will automatically take care of the distributed
synchronization for you. However, the following three keyword arguments can be given to any metric class for
further control over the distributed aggregation:
- ``sync_on_compute``: This argument is an ``bool`` that indicates if the metrics should automatically sync between
devices whenever the ``compute`` method is called. By default this is ``True``, but by setting this to ``False``
you can manually control when the synchronization happens.
- ``dist_sync_on_step``: This argument is ``bool`` that indicates if the metric should synchronize between
different devices every time ``forward`` is called. Setting this to ``True`` is in general not recommended
as synchronization is an expensive operation to do after each batch.
- ``process_group``: By default we synchronize across the *world* i.e. all processes being computed on. You
can provide an ``torch._C._distributed_c10d.ProcessGroup`` in this argument to specify exactly what
devices should be synchronized over.
- ``dist_sync_fn``: By default we use :func:`torch.distributed.all_gather` to perform the synchronization between
devices. Provide another callable function for this argument to perform custom distributed synchronization.
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/pages/implement.rst | .. _implement:
.. testsetup:: *
from typing import Optional, Sequence, Union
from torch import Tensor
#####################
Implementing a Metric
#####################
While we strive to include as many metrics as possible in ``torchmetrics``, we cannot include them all. Therefore, we
have made it easy to implement your own metric and possible contribute it to ``torchmetrics``. This page will guide
you through the process. If you afterwards are interested in contributing your metric to ``torchmetrics``, please
read the `contribution guidelines <https://lightning.ai/docs/torchmetrics/latest/generated/CONTRIBUTING.html>`_ and
see this :ref:`section <contributing metric>`.
**************
Base interface
**************
To implement your own custom metric, subclass the base :class:`~torchmetrics.Metric` class and implement the following
methods:
- ``__init__()``: Each state variable should be called using ``self.add_state(...)``.
- ``update()``: Any code needed to update the state given any inputs to the metric.
- ``compute()``: Computes a final value from the state of the metric.
We provide the remaining interface, such as ``reset()`` that will make sure to correctly reset all metric
states that have been added using ``add_state``. You should therefore not implement ``reset()`` yourself, only in rare
cases where not all the state variables should be reset to their default value. Adding metric states with ``add_state``
will make sure that states are correctly synchronized in distributed settings (DDP). To see how metric states are
synchronized across distributed processes, refer to :meth:`~torchmetrics.Metric.add_state()` docs from the base
:class:`~torchmetrics.Metric` class.
Below is a basic implementation of a custom accuracy metric. In the ``__init__`` method we add the metric states
``correct`` and ``total``, which will be used to accumulate the number of correct predictions and the total number
of predictions, respectively. In the ``update`` method we update the metric states based on the inputs to the metric.
Finally, in the ``compute`` method we compute the final metric value based on the metric states.
.. testcode::
from torchmetrics import Metric
class MyAccuracy(Metric):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum")
self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")
def update(self, preds: Tensor, target: Tensor) -> None:
preds, target = self._input_format(preds, target)
if preds.shape != target.shape:
raise ValueError("preds and target must have the same shape")
self.correct += torch.sum(preds == target)
self.total += target.numel()
def compute(self) -> Tensor:
return self.correct.float() / self.total
A few important things to note:
* The ``dist_reduce_fx`` argument to ``add_state`` is used to specify how the metric states should be reduced between
batches in distributed settings. In this case we use ``"sum"`` to sum the metric states across batches. A couple of
build in options are available: ``"sum"``, ``"mean"``, ``"cat"``, ``"min"`` or ``"max"``, but a custom reduction is
also supported.
* In ``update`` we do not return anything but instead update the metric states in-place.
* In ``compute`` when running in distributed mode, the states would have been synced before the compute method is
called. Thus ``self.correct`` and ``self.total`` will contain the sum of the metric states across all processes.
************************
Working with list states
************************
When initializing metric states with ``add_state``, the ``default`` argument can either be a single tensor (as in the
example above) or an empty list. Most metric will only require a single tensor to accumulate the metric states, but
for some metrics that need access to the individual batch states, it can be useful to use a list of tensors. In the
following example we show how to implement Spearman correlation, which requires access to the individual batch states
because we need to calculate the rank of the predictions and targets.
.. testcode::
from torchmetrics import Metric
from torchmetrics.utilities import dim_zero_cat
class MySpearmanCorrCoef(Metric):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_state("preds", default=[], dist_reduce_fx="cat")
self.add_state("target", default=[], dist_reduce_fx="cat")
def update(self, preds: Tensor, target: Tensor) -> None:
self.preds.append(preds)
self.target.append(target)
def compute(self):
# parse inputs
preds = dim_zero_cat(preds)
target = dim_zero_cat(target)
# some intermediate computation...
r_preds, r_target = _rank_data(preds), _rank_dat(target)
preds_diff = r_preds - r_preds.mean(0)
target_diff = r_target - r_target.mean(0)
cov = (preds_diff * target_diff).mean(0)
preds_std = torch.sqrt((preds_diff * preds_diff).mean(0))
target_std = torch.sqrt((target_diff * target_diff).mean(0))
# finalize the computations
corrcoef = cov / (preds_std * target_std + eps)
return torch.clamp(corrcoef, -1.0, 1.0)
A few important things to note for this example:
* When working with list states, the ``dist_reduce_fx`` argument to ``add_state`` should be set to ``"cat"`` to
concatenate the list of tensors across batches.
* When working with list states, The ``update(...)`` method should append the batch states to the list.
* In the the ``compute`` method the list states behave a bit differently dependeding on weather you are running in
distributed mode or not. In non-distributed mode the list states will be a list of tensors, while in distributed mode
the list have already been concatenated into a single tensor. For this reason, we recommend always using the
``dim_zero_cat`` helper function which will standardize the list states to be a single concatenate tensor regardless
of the mode.
*****************
Metric attributes
*****************
When done implementing your own metric, there are a few properties and attributes that you may want to set to add
additional functionality. The three attributes to consider are: ``is_differentiable``, ``higher_is_better`` and
``full_state_update``. Note that none of them are strictly required to be set for the metric to work.
.. testcode::
from torchmetrics import Metric
class MyMetric(Metric):
# Set to True if the metric is differentiable else set to False
is_differentiable: Optional[bool] = None
# Set to True if the metric reaches it optimal value when the metric is maximized.
# Set to False if it when the metric is minimized.
higher_is_better: Optional[bool] = True
# Set to True if the metric during 'update' requires access to the global metric
# state for its calculations. If not, setting this to False indicates that all
# batch states are independent and we will optimize the runtime of 'forward'
full_state_update: bool = True
**************
Plot interface
**************
From torchmetrics v1.0.0 onwards, we also support plotting of metrics through the ``.plot()`` method. By default this method
will raise `NotImplementedError` but can be implemented by the user to provide a custom plot for the metric.
For any metrics that returns a simple scalar tensor, or a dict of scalar tensors the internal `._plot` method can be
used, that provides the common plotting functionality for most metrics in torchmetrics.
.. testcode::
from torchmetrics import Metric
from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
class MyMetric(Metric):
# set these attributes if you want to use the internal ._plot method
# bounds are automatically added to the generated plot
plot_lower_bound: Optional[float] = None
plot_upper_bound: Optional[float] = None
def plot(
self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
) -> _PLOT_OUT_TYPE:
return self._plot(val, ax)
If the metric returns a more complex output, a custom implementation of the `plot` method is required. For more details
on the plotting API, see the this :ref:`page <plotting>` . In addti
*******************************
Internal implementation details
*******************************
This section briefly describes how metrics work internally. We encourage looking at the source code for more info.
Internally, TorchMetrics wraps the user defined ``update()`` and ``compute()`` method. We do this to automatically
synchronize and reduce metric states across multiple devices. More precisely, calling ``update()`` does the
following internally:
1. Clears computed cache.
2. Calls user-defined ``update()``.
Similarly, calling ``compute()`` does the following internally:
1. Syncs metric states between processes.
2. Reduce gathered metric states.
3. Calls the user defined ``compute()`` method on the gathered metric states.
4. Cache computed result.
From a user's standpoint this has one important side-effect: computed results are cached. This means that no
matter how many times ``compute`` is called after one and another, it will continue to return the same result.
The cache is first emptied on the next call to ``update``.
``forward`` serves the dual purpose of both returning the metric on the current data and updating the internal
metric state for accumulating over multiple batches. The ``forward()`` method achieves this by combining calls
to ``update``, ``compute`` and ``reset``. Depending on the class property ``full_state_update``, ``forward``
can behave in two ways:
1. If ``full_state_update`` is ``True`` it indicates that the metric during ``update`` requires access to the full
metric state and we therefore need to do two calls to ``update`` to secure that the metric is calculated correctly
1. Calls ``update()`` to update the global metric state (for accumulation over multiple batches)
2. Caches the global state.
3. Calls ``reset()`` to clear global metric state.
4. Calls ``update()`` to update local metric state.
5. Calls ``compute()`` to calculate metric for current batch.
6. Restores the global state.
2. If ``full_state_update`` is ``False`` (default) the metric state of one batch is completely independent of the state
of other batches, which means that we only need to call ``update`` once.
1. Caches the global state.
2. Calls ``reset`` the metric to its default state
3. Calls ``update`` to update the state with local batch statistics
4. Calls ``compute`` to calculate the metric for the current batch
5. Reduce the global state and batch state into a single state that becomes the new global state
If implementing your own metric, we recommend trying out the metric with ``full_state_update`` class property set to
both ``True`` and ``False``. If the results are equal, then setting it to ``False`` will usually give the best
performance.
.. autoclass:: torchmetrics.Metric
:noindex:
:members:
.. _contributing metric:
****************************************
Contributing your metric to TorchMetrics
****************************************
Wanting to contribute the metric you have implemented? Great, we are always open to adding more metrics to ``torchmetrics``
as long as they serve a general purpose. However, to keep all our metrics consistent we request that the implementation
and tests gets formatted in the following way:
1. Start by reading our `contribution guidelines <https://lightning.ai/docs/torchmetrics/latest/generated/CONTRIBUTING.html>`_.
2. First implement the functional backend. This takes cares of all the logic that goes into the metric. The code should
be put into a single file placed under ``src/torchmetrics/functional/"domain"/"new_metric".py`` where ``domain`` is the type of
metric (classification, regression, text etc.) and ``new_metric`` is the name of the metric. In this file, there should be the
following three functions:
1. ``_new_metric_update(...)``: everything that has to do with type/shape checking and all logic required before distributed syncing need to go here.
2. ``_new_metric_compute(...)``: all remaining logic.
3. ``new_metric(...)``: essentially wraps the ``_update`` and ``_compute`` private functions into one public function that
makes up the functional interface for the metric.
.. note::
The `functional mean squared error <https://github.com/Lightning-AI/torchmetrics/blob/master/src/torchmetrics/functional/regression/mse.py>`_
metric is a great example of this division of logic.
3. In a corresponding file placed in ``src/torchmetrics/"domain"/"new_metric".py`` create the module interface:
1. Create a new module metric by subclassing ``torchmetrics.Metric``.
2. In the ``__init__`` of the module call ``self.add_state`` for as many metric states are needed for the metric to
proper accumulate metric statistics.
3. The module interface should essentially call the private ``_new_metric_update(...)`` in its `update` method and similarly the
``_new_metric_compute(...)`` function in its ``compute``. No logic should really be implemented in the module interface.
We do this to not have duplicate code to maintain.
.. note::
The module `MeanSquaredError <https://github.com/Lightning-AI/torchmetrics/blob/master/src/torchmetrics/regression/mse.py>`_
metric that corresponds to the above functional example showcases these steps.
4. Remember to add binding to the different relevant ``__init__`` files.
5. Testing is key to keeping ``torchmetrics`` trustworthy. This is why we have a very rigid testing protocol. This means
that we in most cases require the metric to be tested against some other common framework (``sklearn``, ``scipy`` etc).
1. Create a testing file in ``tests/unittests/"domain"/test_"new_metric".py``. Only one file is needed as it is intended to test
both the functional and module interface.
2. In that file, start by defining a number of test inputs that your metric should be evaluated on.
3. Create a testclass ``class NewMetric(MetricTester)`` that inherits from ``tests.helpers.testers.MetricTester``.
This testclass should essentially implement the ``test_"new_metric"_class`` and ``test_"new_metric"_fn`` methods that
respectively tests the module interface and the functional interface.
4. The testclass should be parameterized (using ``@pytest.mark.parametrize``) by the different test inputs defined initially.
Additionally, the ``test_"new_metric"_class`` method should also be parameterized with an ``ddp`` parameter such that it gets
tested in a distributed setting. If your metric has additional parameters, then make sure to also parameterize these
such that different combinations of inputs and parameters gets tested.
5. (optional) If your metric raises any exception, please add tests that showcase this.
.. note::
The `test file for MSE <https://github.com/Lightning-AI/torchmetrics/blob/master/tests/unittests/regression/test_mean_error.py>`_
metric shows how to implement such tests.
If you only can figure out part of the steps, do not fear to send a PR. We will much rather receive working
metrics that are not formatted exactly like our codebase, than not receiving any. Formatting can always be applied.
We will gladly guide and/or help implement the remaining :]
| 0 |
public_repos/torchmetrics/docs/source | public_repos/torchmetrics/docs/source/pages/plotting.rst | .. _plotting:
.. testsetup:: *
import torch
import matplotlib
import matplotlib.pyplot as plt
import torchmetrics
########
Plotting
########
.. note::
The visualization/plotting interface of Torchmetrics requires ``matplotlib`` to be installed. Install with either
``pip install matplotlib`` or ``pip install 'torchmetrics[visual]'``. If the latter option is chosen the
`Scienceplot package <https://github.com/garrettj403/SciencePlots>`_ is also installed and all plots in
Torchmetrics will default to using that style.
Torchmetrics comes with built-in support for quick visualization of your metrics, by simply using the ``.plot`` method
that all modular metrics implement. This method provides a consistent interface for basic plotting of all metrics.
.. code-block:: python
metric = AnyMetricYouLike()
for _ in range(num_updates):
metric.update(preds[i], target[i])
fig, ax = metric.plot()
``.plot`` will always return two objects: ``fig`` is an instance of :class:`~matplotlib.figure.Figure` which contains
figure level attributes and `ax` is an instance of :class:`~matplotlib.axes.Axes` that contains all the elements of the
plot. These two objects allow to change attributes of the plot after it is created. For example, if you want to make
the fontsize of the x-axis a bit bigger and give the figure a nice title and finally save it on the above example, it
could be do like this:
.. code-block:: python
ax.set_fontsize(fs=20)
fig.set_title("This is a nice plot")
fig.savefig("my_awesome_plot.png")
If you want to include a Torchmetrics plot in a bigger figure that has subfigures and subaxes, all ``.plot`` methods
support an optional `ax` argument where you can pass in the subaxes you want the plot to be inserted into:
.. code-block:: python
# combine plotting of two metrics into one figure
fig, ax = plt.subplots(nrows=1, ncols=2)
metric1 = Metric1()
metric2 = Metric2()
for _ in range(num_updates):
metric1.update(preds[i], target[i])
metric2.update(preds[i], target[i])
metric1.plot(ax=ax[0])
metric2.plot(ax=ax[1])
**********************
Plotting a single step
**********************
At the most basic level the ``.plot`` method can be used to plot the value from a single step. This can be done in two
ways:
* Either ``.plot`` method is called with no input, and internally ``metric.compute()`` is called and that value is plotted
* ``.plot`` is called on a single returned value by the metric, for example from ``metric.forward()``
In both cases it will generate a plot like this (Accuracy as an example):
.. code-block:: python
metric = torchmetrics.Accuracy(task="binary")
for _ in range(num_updates):
metric.update(torch.rand(10,), torch.randint(2, (10,)))
fig, ax = metric.plot()
.. plot:: pyplots/binary_accuracy.py
:scale: 100
:include-source: false
A single point plot is not that informative in itself, but if available we will try to include additional information
such as the lower and upper bounds the particular metric can take and if the metric should be minimized or maximized
to be optimal. This is true for all metrics that return a scalar tensor.
Some metrics return multiple values (such as an tensor with multiple elements or a dict of scalar tensors), and in
that case calling ``.plot`` will return a figure similar to this:
.. code-block:: python
metric = torchmetrics.Accuracy(task="multiclass", num_classes=3, average=None)
for _ in range(num_updates):
metric.update(torch.randint(3, (10,)), torch.randint(3, (10,)))
fig, ax = metric.plot()
.. plot:: pyplots/multiclass_accuracy.py
:scale: 100
:include-source: false
Here, each element is assumed to be an independent metric and plotted as its own point for comparing. The above is true
for all metrics that return a scalar tensor, but if the metric returns a tensor with multiple elements then the
``.plot`` method will return a specialized plot for that particular metric. Take for example the ``ConfusionMatrix``
metric:
.. code-block:: python
metric = torchmetrics.ConfusionMatrix(task="multiclass", num_classes=3)
for _ in range(num_updates):
metric.update(torch.randint(3, (10,)), torch.randint(3, (10,)))
fig, ax = metric.plot()
.. plot:: pyplots//confusion_matrix.py
:scale: 100
:include-source: false
If you prefer to use the functional interface of Torchmetrics, you can also plot the values returned by the functional.
However, you would still need to initialize the corresponding metric class to get the information about the metric:
.. code-block:: python
plot_class = torchmetrics.Accuracy(task="multiclass", num_classes=3)
value = torchmetrics.functional.accuracy(
torch.randint(3, (10,)), torch.randint(3, (10,)), num_classes=3
)
fig, ax = plot_class.plot(value)
********************
Plotting multi steps
********************
In the above examples we have only plotted a single step/single value, but it is also possible to plot multiple steps
from the same metric. This is often the case when training a machine learning model, where you are tracking one or
multiple metrics that you want to plot as they are changing over time. This can be done by providing a sequence of outputs from
any metric, computed using ``metric.forward`` or ``metric.compute``. For example, if we want to plot the accuracy of
a model over time, we could do it like this:
.. code-block:: python
metric = torchmetrics.Accuracy(task="binary")
values = [ ]
for step in range(num_steps):
for _ in range(num_updates):
metric.update(preds(step), target(step))
values.append(metric.compute()) # save value
metric.reset()
fig, ax = metric.plot(values)
.. plot:: pyplots/binary_accuracy_multistep.py
:scale: 100
:include-source: false
Do note that metrics that do not return simple scalar tensors, such as `ConfusionMatrix`, `ROC` that have specialized
visualization does not support plotting multiple steps, out of the box and the user needs to manually plot the values
for each step.
********************************
Plotting a collection of metrics
********************************
``MetricCollection`` also supports `.plot` method and by default it works by just returning a collection of plots for
all its members. Thus, instead of returning a single (fig, ax) pair, calling `.plot` method of ``MetricCollection`` will
return a sequence of such pairs, one for each member in the collection. In the following example we are forming a
collection of binary classification metrics and redirecting the output of ``.plot`` to different subplots:
.. code-block:: python
collection = torchmetrics.MetricCollection(
torchmetrics.Accuracy(task="binary"),
torchmetrics.Recall(task="binary"),
torchmetrics.Precision(task="binary"),
)
fig, ax = plt.subplots(nrows=1, ncols=3)
values = [ ]
for step in range(num_steps):
for _ in range(num_updates):
collection.update(preds(step), target(step))
values.append(collection.compute())
collection.reset()
collection.plot(val=values, ax=ax)
.. plot:: pyplots/binary_accuracy_multistep.py
:scale: 100
:include-source: false
However, the ``plot`` method of ``MetricCollection`` also supports an additional argument called ``together`` that will
automatically try to plot all the metrics in the collection together in the same plot (with appropriate labels). This
is only possible if all the metrics in the collection return a scalar tensor.
.. code-block:: python
collection = torchmetrics.MetricCollection(
torchmetrics.Accuracy(task="binary"),
torchmetrics.Recall(task="binary"),
torchmetrics.Precision(task="binary"),
)
values = [ ]
fig, ax = plt.subplots(figsize=(6.8, 4.8))
for step in range(num_steps):
for _ in range(num_updates):
collection.update(preds(step), target(step))
values.append(collection.compute())
collection.reset()
collection.plot(val=values, together=True)
.. plot:: pyplots/collection_binary_together.py
:scale: 100
:include-source: false
***************
Advance example
***************
In the following we are going to show how to use the ``.plot`` method to create a more advanced plot. We are going to
combine the functionality of several metrics using ``MetricCollection`` and plot them together. In addition we are going
to rely on ``MetricTracker`` to keep track of the metrics over multiple steps.
.. code-block:: python
# Define collection that is a mix of metrics that return a scalar tensors and not
confmat = torchmetrics.ConfusionMatrix(task="binary")
roc = torchmetrics.ROC(task="binary")
collection = torchmetrics.MetricCollection(
torchmetrics.Accuracy(task="binary"),
torchmetrics.Recall(task="binary"),
torchmetrics.Precision(task="binary"),
confmat,
roc,
)
# Define tracker over the collection to easy keep track of the metrics over multiple steps
tracker = torchmetrics.wrappers.MetricTracker(collection)
# Run "training" loop
for step in range(num_steps):
tracker.increment()
for _ in range(N):
tracker.update(preds(step), target(step))
# Extract all metrics from all steps
all_results = tracker.compute_all()
# Construct a single figure with appropriate layout for all metrics
fig = plt.figure(layout="constrained")
ax1 = plt.subplot(2, 2, 1)
ax2 = plt.subplot(2, 2, 2)
ax3 = plt.subplot(2, 2, (3, 4))
# ConfusionMatrix and ROC we just plot the last step, notice how we call the plot method of those metrics
confmat.plot(val=all_results[-1]['BinaryConfusionMatrix'], ax=ax1)
roc.plot(all_results[-1]["BinaryROC"], ax=ax2)
# For the remaining we plot the full history, but we need to extract the scalar values from the results
scalar_results = [
{k: v for k, v in ar.items() if isinstance(v, torch.Tensor) and v.numel() == 1} for ar in all_results
]
tracker.plot(val=scalar_results, ax=ax3)
.. plot:: pyplots/tracker_binary.py
:scale: 100
:include-source: false
| 0 |
public_repos/torchmetrics/docs | public_repos/torchmetrics/docs/paper_JOSS/paper.md | ---
title: TorchMetrics - Measuring Reproducibility in PyTorch
tags:
- python
- deep learning
- pytorch
authors:
- name: Nicki Skafte Detlefsen
affiliation: '1,2'
orcid: 0000-0002-8133-682X
- name: Jiri Borovec
affiliation: '1'
orcid: 0000-0001-7437-824X
- name: Justus Schock
affiliation: '1,3'
orcid: 0000-0003-0512-3053
- name: Ananya Harsh Jha
affiliation: '1'
- name: Teddy Koker
affiliation: '1'
- name: Luca Di Liello
affiliation: '4'
- name: Daniel Stancl
affiliation: '5'
- name: Changsheng Quan
affiliation: '6'
- name: Maxim Grechkin
affiliation: '7'
- name: William Falcon
affiliation: '1,8'
affiliations:
- name: Grid AI Labs
index: 1
- name: Technical University of Denmark
index: 2
- name: University Hospital Düsseldorf
index: 3
- name: University of Trento
index: 4
- name: Charles University
index: 5
- name: Zhejiang University
index: 6
- name: Independent Researcher
index: 7
- name: New York University
index: 8
date: 08 Dec 2021
bibliography: paper.bib
---
# Summary
A main problem with reproducing machine learning publications is the variance of metric implementations across papers. A lack of standardization leads to different behavior in mechanisms such as checkpointing, learning rate schedulers or early stopping, that will influence the reported results. For example, a complex metric such as Fréchet inception distance (FID) for synthetic image quality evaluation [@fid] will differ based on the specific interpolation method used.
There have been a few attempts at tackling the reproducibility issues. Papers With Code [@papers_with_code] links research code with its corresponding paper. Similarly, arXiv [@arxiv] recently added a code and data section that links both official and community code to papers. However, these methods rely on the paper code to be made publicly accessible which is not always possible. Our approach is to provide the de-facto reference implementation for metrics. This approach enables proprietary work to still be comparable as long as they’ve used our reference implementations.
We introduce TorchMetrics, a general-purpose metrics package that covers a wide variety of tasks and domains used in the machine learning community. TorchMetrics provides standard classification and regression metrics; and domain-specific metrics for audio, computer vision, natural language processing, and information retrieval. Our process for adding a new metric is as follows, first we integrate a well-tested and established third-party library. Once we’ve verified the implementations and written tests for them, we re-implement them in native PyTorch [@pytorch] to enable hardware acceleration and remove any bottlenecks in inter-device transfer.
# Statement of need
Currently, there is no standard, widely-adopted metrics library for native PyTorch. Some native PyTorch libraries support domain-specific metrics such as Transformers [@transformers] for calculating NLP-specific metrics. However, no library exists that covers multiple domains. PyTorch users, therefore, often rely on non-PyTorch packages such as Scikit-learn [@scikit_learn] for computing even simple metrics such as accuracy, F1, or AUROC metrics.
However, while Scikit-learn is considered the gold standard for computing metrics in regression and classification, it relies on the core assumption that all predictions and targets are available simultaneously. This contradicts the typical workflow in a modern deep learning training/evaluation loop where data comes in batches. Therefore, the metric needs to be calculated in an online fashion. It is important to note that, in general, it is not possible to calculate a global metric as its average or sum of the metric calculated per batch.
TorchMetrics solves this problem by introducing stateful metrics that can calculate metric values on a stream of data alongside the classical functional and stateless metrics provided by other packages like Scikit-learn. We do this with an effortless `update` and `compute` interface, well known from packages such as Keras [@keras]. The `update` function takes in a batch of predictions and targets and updates the internal state. For example, for a metric such as accuracy, the internal states are simply the number of correctly classified samples and the total observed number of samples. When all batches have been passed to the `update` method, the `compute` method can get the accumulated accuracy over all the batches. In addition to `update` and `compute`, each metric also has a `forward` method (as any other `torch.nn.Module`) that can be used to both get the metric on the current batch of data and accumulate global state. This enables the user to get fine-grained info about the metric on the individual batch and the global metric of how well their model is doing.
```python
# Minimal example showcasing the TorchMetrics interface
import torch
from torch import tensor, Tensor
# base class all modular metrics inherit from
from torchmetrics import Metric
class Accuracy(Metric):
def __init__(self):
super().__init__()
# `self.add_state` defines the states of the metric
# that should be accumulated and will automatically
# be synchronized between devices
self.add_state("correct", default=tensor(0), dist_reduce_fx="sum")
self.add_state("total", default=tensor(0), dist_reduce_fx="sum")
def update(self, preds: Tensor, target: Tensor) -> None:
# update takes `preds` and `target` and accumulate the current
# stream of data into the global states for later
self.correct += torch.sum(preds == target)
self.total += target.numel()
def compute(self) -> Tensor:
# compute takes the accumulated states
# and returns the final metric value
return self.correct / self.total
```
Another core feature of TorchMetrics is its ability to scale to multiple devices seamlessly. Modern deep learning models are often trained on hundreds of devices such as GPUs or TPUs (see @large_example1; @large_example2 for examples). This scale introduces the need to synchronize metrics across machines to get the correct value during training and evaluation. In distributed environments, TorchMetrics automatically accumulates across devices before reporting the calculated metric to the user.
In addition to stateful metrics (called modular metrics in TorchMetrics), we also support a functional interface that works similar to Scikit-learn. This interface provides simple Python functions that take as input PyTorch Tensors and return the corresponding metric as a PyTorch Tensor. These can be used when metrics are evaluated on single devices, and no accumulation is needed, making them very fast to compute.
TorchMetrics exhibits high test coverage on the various configurations, including all three major OS platforms (Linux, macOS, and Windows), and various Python, CUDA, and PyTorch versions. We test both minimum and latest package requirements for all combinations of OS and Python versions and include additional tests for each PyTorch version from 1.3 up to future development versions. On every pull request and merge to master, we run a full test suite. All standard tests run on CPU. In addition, we run all tests on a multi-GPU setting which reflects realistic Deep Learning workloads. For usability, we have auto-generated HTML documentation (hosted at [readthedocs](https://torchmetrics.readthedocs.io/en/stable/)) from the source code which updates in real-time with new merged pull requests.
TorchMetrics is released under the Apache 2.0 license. The source code is available at https://github.com/Lightning-AI/torchmetrics.
# Acknowledgement
The TorchMetrics team thanks Thomas Chaton, Ethan Harris, Carlos Mocholí, Sean Narenthiran, Adrian Wälchli, and Ananth Subramaniam for contributing ideas, participating in discussions on API design, and completing Pull Request reviews. We also thank all of our open-source contributors for reporting and resolving issues with this package. We are grateful to the PyTorch Lightning team for their ongoing and dedicated support of this project, and Grid.ai for providing computing resources and cloud credits needed to run our Continuous Integrations.
# References
| 0 |
public_repos/torchmetrics/docs | public_repos/torchmetrics/docs/paper_JOSS/paper.bib | @misc{reproducibility,
title={Enabling End-To-End Machine Learning Replicability: A Case Study in Educational Data Mining},
author={Josh Gardner and Yuming Yang and Ryan Baker and Christopher Brooks},
year={2018},
eprint={1806.05208},
archivePrefix={arXiv},
primaryClass={cs.CY}
}
@inproceedings{fid,
title={GANs Trained by a Two Time-Scale Update Rule Converge to a Local {N}ash Equilibrium},
volume = {30},
url = {https://proceedings.neurips.cc/paper/2017/hash/8a1d694707eb0fefe65871369074926d-Abstract.html},
booktitle = {Advances in Neural Information Processing Systems},
publisher = {Curran Associates, Inc.},
author = {Heusel, Martin and Ramsauer, Hubert and Unterthiner, Thomas and Nessler, Bernhard and Hochreiter, Sepp},
pages={6629--6640},
year = {2017},
}
@misc{papers_with_code,
title = {Papers With Code},
author = {},
howpublished = {\url{https://paperswithcode.com/}},
note = {Accessed: 2021-12-01}
}
@misc{arxiv,
title = {Arxiv},
author = {},
howpublished = {\url{https://arxiv.org/}},
note = {Accessed: 2021-12-16}
}
@incollection{pytorch,
title = {PyTorch: An Imperative Style, High-Performance Deep Learning Library},
author = {Paszke, Adam and Gross, Sam and Massa, Francisco and Lerer, Adam and Bradbury, James and Chanan, Gregory and Killeen, Trevor and Lin, Zeming and Gimelshein, Natalia and Antiga, Luca and Desmaison, Alban and Kopf, Andreas and Yang, Edward and DeVito, Zachary and Raison, Martin and Tejani, Alykhan and Chilamkurthy, Sasank and Steiner, Benoit and Fang, Lu and Bai, Junjie and Chintala, Soumith},
booktitle = {Advances in Neural Information Processing Systems 32},
editor = {H. Wallach and H. Larochelle and A. Beygelzimer and F. d\textquotesingle Alch\'{e}-Buc and E. Fox and R. Garnett},
pages = {8024--8035},
year = {2019},
publisher = {Curran Associates, Inc.},
url={http://papers.neurips.cc/paper/9015-pytorch-an-imperative-style-high-performance-deep-learning-library.pdf}
}
@inproceedings{transformers,
title = "Transformers: State-of-the-Art Natural Language Processing",
author = "Thomas Wolf and Lysandre Debut and Victor Sanh and Julien Chaumond and Clement Delangue and Anthony Moi and Pierric Cistac and Tim Rault and Rémi Louf and Morgan Funtowicz and Joe Davison and Sam Shleifer and Patrick von Platen and Clara Ma and Yacine Jernite and Julien Plu and Canwen Xu and Teven Le Scao and Sylvain Gugger and Mariama Drame and Quentin Lhoest and Alexander M. Rush",
booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations",
month = oct,
year = "2020",
address = "Online",
publisher = "Association for Computational Linguistics",
url = "https://www.aclweb.org/anthology/2020.emnlp-demos.6",
pages = "38--45"
}
@article{scikit_learn,
title={Scikit-learn: Machine Learning in {P}ython},
author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
journal={Journal of Machine Learning Research},
volume={12},
pages={2825--2830},
year={2011}
}
@misc{keras,
title={Keras},
author={Chollet, François and others},
year={2015},
publisher={GitHub},
howpublished={\url{https://github.com/fchollet/keras}},
}
@misc{large_example1,
title={Scaling Vision Transformers},
author={Xiaohua Zhai and Alexander Kolesnikov and Neil Houlsby and Lucas Beyer},
year={2021},
eprint={2106.04560},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
@misc{large_example2,
title={RoBERTa: A Robustly Optimized BERT Pretraining Approach},
author={Yinhan Liu and Myle Ott and Naman Goyal and Jingfei Du and Mandar Joshi and Danqi Chen and Omer Levy and Mike Lewis and Luke Zettlemoyer and Veselin Stoyanov},
year={2019},
eprint={1907.11692},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
| 0 |
public_repos | public_repos/twitter-finetune/app.py | import langchain
import streamlit as st
from langchain.prompts import ChatPromptTemplate
from langchain.chat_models import ChatOpenAI
from langchain.schema.output_parser import StrOutputParser
from langchain.callbacks.tracers.langchain import wait_for_all_tracers
from langchain.callbacks.tracers.run_collector import RunCollectorCallbackHandler
from langchain.schema.runnable import RunnableConfig
from langsmith import Client
from streamlit_feedback import streamlit_feedback
client = Client()
if "run_id" not in st.session_state:
st.session_state.run_id = None
run_collector = RunCollectorCallbackHandler()
runnable_config = RunnableConfig(
callbacks=[run_collector],
tags=["Streamlit Chat"],
)
normal_chain = (
ChatPromptTemplate.from_messages([("system", "write a tweet about {topic} in the style of Elon Musk") ])
| ChatOpenAI()
| StrOutputParser()
)
chain = (
ChatPromptTemplate.from_messages([("system", "write a tweet about {topic}") ])
| ChatOpenAI(model="ft:gpt-3.5-turbo-0613:langchain::7qqjIosa")
| StrOutputParser()
)
def generate_tweet_normal(topic):
result = normal_chain.invoke({"topic": topic})
wait_for_all_tracers()
return result
def generate_tweet(topic):
result = chain.invoke({"topic": topic}, config=runnable_config)
run = run_collector.traced_runs[0]
run_collector.traced_runs = []
st.session_state.run_id = run.id
wait_for_all_tracers()
return result
col1, col2 = st.columns([1, 6]) # Adjust the ratio for desired layout
# Display the smaller image in the first column
col1.image("elon.jpeg") # Adjust width as needed
# Display the title in the second column
col2.title("Elon Musk Tweet Generator")
st.info("This generator was finetuned on tweets by Elon Musk to imitate his style. Source code [here](https://github.com/langchain-ai/twitter-finetune)\n\nTwo tweets will be generated: one using a finetuned model, one useing a prompted model. Afterwards, you can provide feedback about whether the finetuned model performed better!")
topic = st.text_input("Enter a topic:")
if 'show_tweets' not in st.session_state:
st.session_state.show_tweets = None
if st.button("Generate Tweets"):
if topic:
col3, col4 = st.columns([6, 6])
tweet = generate_tweet(topic)
col3.markdown("### Finetuned Tweet:")
col3.write(f"🐦: {tweet}")
col3.markdown("---") # Add a horizontal line for separation
feedback = streamlit_feedback(
feedback_type="thumbs",
key=f"feedback_{st.session_state.run_id}",
align="flex-start"
)
scores = {"👍": 1, "👎": 0}
if feedback:
score = scores[feedback["score"]]
feedback = client.create_feedback(st.session_state.run_id, "user_score", score=score)
st.session_state.feedback = {"feedback_id": str(feedback.id), "score": score}
tweet = generate_tweet_normal(topic)
col4.markdown("### Prompted Tweet:")
col4.write(f"🐦: {tweet}")
col4.markdown("---") # Add a horizontal line for separation
else:
st.warning("Please enter a topic before generating a tweet.")
| 0 |
public_repos | public_repos/twitter-finetune/requirements.txt | openai
langchain
streamlit
streamlit_feedback
| 0 |
public_repos | public_repos/twitter-finetune/README.md | # Twitter Finetune
This repo shows how to finetune GPT-3.5-Turbo on tweets. Specifically, Elon Musk's tweets.
In this example, data is first exported from Twitter using [Apify](https://apify.com/).
A copy of this data can be found in [dataset_twitter-scraper_2023-08-23_22-13-19-740.json](dataset_twitter-scraper_2023-08-23_22-13-19-740.json).
This data is then loaded to a format with which it can be used to finetune a GPT-3.5-Turbo model, and is then used to do exactly that. This can be done by running `python ingest.py`.
A Streamlit app is this created to compare this finetuned model to a prompted GPT-3.5-Turbo model.
This can be run with `streamlit run app.py`.
Access the final app hosted on Streamlit [here](https://elon-twitter-clone.streamlit.app/).
| 0 |
public_repos | public_repos/twitter-finetune/dataset_twitter-scraper_2023-08-23_22-13-19-740.json | [{
"username": "elonmusk",
"user_id": "44196397",
"id": "1519480761749016577",
"conversation_id": "1519480761749016577",
"full_text": "Next I’m buying Coca-Cola to put the cocaine back in",
"reply_count": 187291,
"retweet_count": 648962,
"favorite_count": 4596262,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1519480761749016577",
"created_at": "2022-04-28T00:56:58.000Z",
"quote_count": 171980,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1518623997054918657",
"conversation_id": "1518623997054918657",
"full_text": "I hope that even my worst critics remain on Twitter, because that is what free speech means",
"reply_count": 174468,
"retweet_count": 351409,
"favorite_count": 3105543,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1518623997054918657",
"created_at": "2022-04-25T16:12:30.000Z",
"quote_count": 70717,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1519495072802390016",
"conversation_id": "1519495072802390016",
"full_text": "Let’s make Twitter maximum fun!",
"reply_count": 110542,
"retweet_count": 184310,
"favorite_count": 2542681,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1519495072802390016",
"created_at": "2022-04-28T01:53:50.000Z",
"quote_count": 34654,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1518677066325053441",
"conversation_id": "1518677066325053441",
"full_text": "🚀💫♥️ Yesss!!! ♥️💫🚀 https://t.co/0T9HzUHuh6",
"reply_count": 145150,
"retweet_count": 330889,
"favorite_count": 2505986,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FRNsuSFWUAUW6aP.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1518677066325053441",
"created_at": "2022-04-25T19:43:22.000Z",
"quote_count": 61362,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1519495982723084290",
"conversation_id": "1519495982723084290",
"full_text": "Listen, I can’t do miracles ok https://t.co/z7dvLMUXy8",
"reply_count": 74894,
"retweet_count": 202182,
"favorite_count": 2473727,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FRZViwWX0AMsqQ1.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1519495982723084290",
"created_at": "2022-04-28T01:57:27.000Z",
"quote_count": 25525,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1585841080431321088",
"conversation_id": "1585841080431321088",
"full_text": "the bird is freed",
"reply_count": 137792,
"retweet_count": 330476,
"favorite_count": 2370568,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1585841080431321088",
"created_at": "2022-10-28T03:49:11.000Z",
"quote_count": 52481,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1586104694421659648",
"conversation_id": "1586104694421659648",
"full_text": "Comedy is now legal on Twitter",
"reply_count": 87869,
"retweet_count": 236840,
"favorite_count": 2274201,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1586104694421659648",
"created_at": "2022-10-28T21:16:42.000Z",
"quote_count": 39559,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1593459801966538755",
"conversation_id": "1593459801966538755",
"full_text": "https://t.co/rbwbsLA1ZG",
"reply_count": 67716,
"retweet_count": 218714,
"favorite_count": 2030318,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Fh0bPd7VQAAU31D.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1593459801966538755",
"created_at": "2022-11-18T04:23:16.000Z",
"quote_count": 165205,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1523465632502906880",
"conversation_id": "1523465632502906880",
"full_text": "If I die under mysterious circumstances, it’s been nice knowin ya",
"reply_count": 142816,
"retweet_count": 164576,
"favorite_count": 1814691,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1523465632502906880",
"created_at": "2022-05-09T00:51:26.000Z",
"quote_count": 40125,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1587894226695884800",
"conversation_id": "1587894226695884800",
"full_text": "https://t.co/kGncG7Hs3M",
"reply_count": 71915,
"retweet_count": 167091,
"favorite_count": 1796047,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FglVYVmXkAIWB5w.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1587894226695884800",
"created_at": "2022-11-02T19:47:39.000Z",
"quote_count": 63550,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1236029449042198528",
"conversation_id": "1236029449042198528",
"full_text": "The coronavirus panic is dumb",
"reply_count": 39483,
"retweet_count": 267574,
"favorite_count": 1453833,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1236029449042198528",
"created_at": "2020-03-06T20:42:39.000Z",
"quote_count": 38185,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1519020176884305920",
"conversation_id": "1519020176884305920",
"full_text": "The extreme antibody reaction from those who fear free speech says it all",
"reply_count": 76483,
"retweet_count": 182948,
"favorite_count": 1586156,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1519020176884305920",
"created_at": "2022-04-26T18:26:46.000Z",
"quote_count": 17843,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1685096284275802112",
"conversation_id": "1685096284275802112",
"full_text": "https://t.co/XEydRiST9D",
"reply_count": 129650,
"retweet_count": 100921,
"favorite_count": 1672309,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/F2KqI_ZXUAAGRCD.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1685096284275802112",
"created_at": "2023-07-29T01:13:56.000Z",
"view_count": 153952239,
"quote_count": 65149,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1519735033950470144",
"conversation_id": "1519735033950470144",
"full_text": "https://t.co/Q9OjlJhi7f",
"reply_count": 88482,
"retweet_count": 199755,
"favorite_count": 1498481,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FRcu9TeXEAMjvTM.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1519735033950470144",
"created_at": "2022-04-28T17:47:22.000Z",
"quote_count": 43234,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1519415674111672325",
"conversation_id": "1519415674111672325",
"full_text": "For Twitter to deserve public trust, it must be politically neutral, which effectively means upsetting the far right and the far left equally",
"reply_count": 77096,
"retweet_count": 137275,
"favorite_count": 1489409,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1519415674111672325",
"created_at": "2022-04-27T20:38:20.000Z",
"quote_count": 28306,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1479236333516165121",
"conversation_id": "1479236333516165121",
"full_text": "Starlinks with “lasers” deployed to orbit https://t.co/Y1eg9gl7sJ",
"reply_count": 12544,
"retweet_count": 9849,
"favorite_count": 915843,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FIdNmXtVkAEF0Ss.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1479236333516165121",
"created_at": "2022-01-06T23:39:59.000Z",
"quote_count": 1185,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1670234980776132608",
"conversation_id": "1670234980776132608",
"full_text": "Oh hi lol https://t.co/pLxkLDu0Qs",
"reply_count": 56500,
"retweet_count": 125873,
"favorite_count": 1546285,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Fy3d3Q4XsAAPSAN.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1670234980776132608",
"created_at": "2023-06-18T01:00:25.000Z",
"view_count": 80352350,
"quote_count": 9952,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1519469891455234048",
"conversation_id": "1519469891455234048",
"full_text": "Twitter DMs should have end to end encryption like Signal, so no one can spy on or hack your messages",
"reply_count": 40662,
"retweet_count": 101908,
"favorite_count": 1403300,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1519469891455234048",
"created_at": "2022-04-28T00:13:47.000Z",
"quote_count": 16661,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1625368108461613057",
"conversation_id": "1625368108461613057",
"full_text": "https://t.co/iZUukCVrl5",
"reply_count": 46125,
"retweet_count": 80611,
"favorite_count": 1436396,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Fo53ramacAAigCq.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1625368108461613057",
"created_at": "2023-02-14T05:35:29.000Z",
"view_count": 177548664,
"quote_count": 20288,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1517707521343082496",
"conversation_id": "1517707521343082496",
"full_text": "in case u need to lose a boner fast https://t.co/fcHiaXKCJi",
"reply_count": 68690,
"retweet_count": 128285,
"favorite_count": 1353674,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FQ_68lnWQAIuYMM.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1517707521343082496",
"created_at": "2022-04-23T03:30:45.000Z",
"quote_count": 30414,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1531647849599057921",
"conversation_id": "1531647849599057921",
"full_text": "https://t.co/G83vCrHHJf",
"reply_count": 44573,
"retweet_count": 128520,
"favorite_count": 1349498,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FUGBmevWYAM-V_M.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1531647849599057921",
"created_at": "2022-05-31T14:44:38.000Z",
"quote_count": 21742,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1594191387519373313",
"conversation_id": "1594191387519373313",
"full_text": "Twitter is ALIVE",
"reply_count": 86483,
"retweet_count": 106216,
"favorite_count": 1377837,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1594191387519373313",
"created_at": "2022-11-20T04:50:20.000Z",
"quote_count": 21561,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1667289678612156416",
"conversation_id": "1667289678612156416",
"full_text": "https://t.co/g9gS4MUIVL",
"reply_count": 37176,
"retweet_count": 178234,
"favorite_count": 1383503,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FyNnICoaUAEE9Xv.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1667289678612156416",
"created_at": "2023-06-09T21:56:50.000Z",
"view_count": 87691832,
"quote_count": 13850,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1585341984679469056",
"conversation_id": "1585341984679469056",
"full_text": "Entering Twitter HQ – let that sink in! https://t.co/D68z4K2wq7",
"reply_count": 65658,
"retweet_count": 172649,
"favorite_count": 1331840,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/ext_tw_video_thumb/1585341912877146112/pu/img/DwJ7wlGIe9iryk6N.jpg",
"type": "video",
"video_url": "https://video.twimg.com/ext_tw_video/1585341912877146112/pu/vid/1920x1080/aeoVUvTgj4wHShhN.mp4?tag=14"
}
],
"url": "https://twitter.com/elonmusk/status/1585341984679469056",
"created_at": "2022-10-26T18:45:58.000Z",
"view_count": 48607062,
"quote_count": 42432,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1521202951230046210",
"conversation_id": "1521202951230046210",
"full_text": "As I was saying … https://t.co/tsGz6fCWuW",
"reply_count": 52348,
"retweet_count": 97069,
"favorite_count": 1273109,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FRxmBNeXwAMVTOg.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1521202951230046210",
"created_at": "2022-05-02T19:00:20.000Z",
"quote_count": 9562,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1588750686006947840",
"conversation_id": "1588750686006947840",
"full_text": "Trash me all day, but it’ll cost $8",
"reply_count": 104121,
"retweet_count": 89130,
"favorite_count": 1300597,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1588750686006947840",
"created_at": "2022-11-05T04:30:55.000Z",
"quote_count": 28347,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1053390822991790083",
"conversation_id": "1053390822991790083",
"full_text": "Had to been done ur welcome https://t.co/7jT0f9lqIS",
"reply_count": 15864,
"retweet_count": 322101,
"favorite_count": 1102018,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Dp5lXiYUUAAngKq.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1053390822991790083",
"created_at": "2018-10-19T21:01:57.000Z",
"quote_count": 24554,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1590755506112823296",
"conversation_id": "1590755506112823296",
"full_text": "I love when people complain about Twitter … on Twitter 🤣🤣",
"reply_count": 78232,
"retweet_count": 101956,
"favorite_count": 1268496,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1590755506112823296",
"created_at": "2022-11-10T17:17:22.000Z",
"quote_count": 28192,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1601894132573605888",
"conversation_id": "1601894132573605888",
"full_text": "My pronouns are Prosecute/Fauci",
"reply_count": 110524,
"retweet_count": 180237,
"favorite_count": 1231419,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1601894132573605888",
"created_at": "2022-12-11T10:58:17.000Z",
"quote_count": 34573,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1625695877326340102",
"conversation_id": "1625695877326340102",
"full_text": "The new CEO of Twitter is amazing https://t.co/yBqWFUDIQH",
"reply_count": 42614,
"retweet_count": 87988,
"favorite_count": 1240934,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Fo-hx39aIAABMKW.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1625695877326340102",
"created_at": "2023-02-15T03:17:55.000Z",
"view_count": 140213026,
"quote_count": 14042,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1601624795585486848",
"conversation_id": "1601624795585486848",
"full_text": "🇲🇦🇲🇦 Congrats Morocco!! 🇲🇦🇲🇦",
"reply_count": 32666,
"retweet_count": 132562,
"favorite_count": 1219545,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1601624795585486848",
"created_at": "2022-12-10T17:08:02.000Z",
"quote_count": 12875,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1607997591870124032",
"conversation_id": "1607997591870124032",
"full_text": "I’m not brainwashed!! https://t.co/4kx61uu4yy",
"reply_count": 71411,
"retweet_count": 151179,
"favorite_count": 1188252,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FlDBSYAXgAAlX8i.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1607997591870124032",
"created_at": "2022-12-28T07:11:15.000Z",
"view_count": 130353016,
"quote_count": 39375,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1503287788652871680",
"conversation_id": "1503287788652871680",
"full_text": "https://t.co/Gw6xaw1u0N",
"reply_count": 30439,
"retweet_count": 137446,
"favorite_count": 1141043,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FNzARriXsAMoSur.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1503287788652871680",
"created_at": "2022-03-14T08:31:53.000Z",
"quote_count": 24278,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1514720245113577473",
"conversation_id": "1514720245113577473",
"full_text": "i♥️u",
"reply_count": 84542,
"retweet_count": 79423,
"favorite_count": 1139093,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1514720245113577473",
"created_at": "2022-04-14T21:40:23.000Z",
"quote_count": 15750,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1520017094007476224",
"conversation_id": "1520017094007476224",
"full_text": "The far left hates everyone, themselves included!",
"reply_count": 59438,
"retweet_count": 114302,
"favorite_count": 1128704,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1520017094007476224",
"created_at": "2022-04-29T12:28:10.000Z",
"quote_count": 16725,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1530380264966434823",
"conversation_id": "1530380264966434823",
"full_text": "https://t.co/USLO967YsJ",
"reply_count": 35224,
"retweet_count": 92904,
"favorite_count": 1146612,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FT0AuTZWAAEgQHU.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1530380264966434823",
"created_at": "2022-05-28T02:47:42.000Z",
"quote_count": 8393,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1523658010241155073",
"conversation_id": "1523658010241155073",
"full_text": "Chocolate milk is insanely good. Just had some.",
"reply_count": 68723,
"retweet_count": 71066,
"favorite_count": 1090118,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1523658010241155073",
"created_at": "2022-05-09T13:35:52.000Z",
"quote_count": 14543,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1511982702819520512",
"conversation_id": "1511982702819520512",
"full_text": "https://t.co/TW2lLQakE5",
"reply_count": 31984,
"retweet_count": 103366,
"favorite_count": 1088637,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FPukQSkXEAAtaQb.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1511982702819520512",
"created_at": "2022-04-07T08:22:22.000Z",
"quote_count": 11547,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1688485935816581120",
"conversation_id": "1688485935816581120",
"full_text": "https://t.co/hDSTKPdQnG",
"reply_count": 29410,
"retweet_count": 67082,
"favorite_count": 1176975,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/F261AH-WUAAuyrT.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1688485935816581120",
"created_at": "2023-08-07T09:43:12.000Z",
"view_count": 66638614,
"quote_count": 4715,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1546344529460174849",
"conversation_id": "1546344529460174849",
"full_text": "https://t.co/JcLMee61wj",
"reply_count": 36837,
"retweet_count": 120770,
"favorite_count": 1088822,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FXW4J4xXgAAXFKs.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1546344529460174849",
"created_at": "2022-07-11T04:04:00.000Z",
"quote_count": 16457,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1686050455468621831",
"conversation_id": "1686050455468621831",
"full_text": "I ♥️ Canada https://t.co/95321VIi8r",
"reply_count": 73993,
"retweet_count": 102243,
"favorite_count": 1156524,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/F2YN81pXMAAjF1e.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1686050455468621831",
"created_at": "2023-07-31T16:25:28.000Z",
"view_count": 130861294,
"quote_count": 51439,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1520650036865949696",
"conversation_id": "1520650036865949696",
"full_text": "Since I’ve been asked a lot:\n\nBuy stock in several companies that make products & services that *you* believe in.\n\nOnly sell if you think their products & services are trending worse. Don’t panic when the market does.\n\nThis will serve you well in the long-term.",
"reply_count": 42044,
"retweet_count": 104025,
"favorite_count": 1056890,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1520650036865949696",
"created_at": "2022-05-01T06:23:15.000Z",
"quote_count": 9050,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1587297137099931649",
"conversation_id": "1587297137099931649",
"full_text": "Halloween with my Mom https://t.co/xOAgNeeiNN",
"reply_count": 36632,
"retweet_count": 44968,
"favorite_count": 1073096,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Fgc2U1AXkAA99Ay.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1587297137099931649",
"created_at": "2022-11-01T04:15:02.000Z",
"quote_count": 6724,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1388693126206918658",
"conversation_id": "1388693126206918658",
"full_text": "I love Art Deco",
"reply_count": 25352,
"retweet_count": 11784,
"favorite_count": 758325,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1388693126206918658",
"created_at": "2021-05-02T03:13:36.000Z",
"quote_count": 3020,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1685384125836849153",
"conversation_id": "1685384125836849153",
"full_text": "https://t.co/5YdlVQifRn",
"reply_count": 38306,
"retweet_count": 56775,
"favorite_count": 1120840,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/F2Ov7dOWcAAylqk.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1685384125836849153",
"created_at": "2023-07-29T20:17:43.000Z",
"view_count": 77682952,
"quote_count": 10273,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1524883482836623373",
"conversation_id": "1524883482836623373",
"full_text": "Biden’s mistake is that he thinks he was elected to transform the country, but actually everyone just wanted less drama",
"reply_count": 58436,
"retweet_count": 88667,
"favorite_count": 1035375,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1524883482836623373",
"created_at": "2022-05-12T22:45:27.000Z",
"quote_count": 13152,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1587627120355934208",
"conversation_id": "1587627120355934208",
"full_text": "To all complainers, please continue complaining, but it will cost $8",
"reply_count": 77567,
"retweet_count": 80134,
"favorite_count": 1051207,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1587627120355934208",
"created_at": "2022-11-02T02:06:16.000Z",
"quote_count": 29667,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1594500655724609536",
"conversation_id": "1594500655724609536",
"full_text": "And lead us not into temptation … https://t.co/8qNOXzwXS9",
"reply_count": 67690,
"retweet_count": 86645,
"favorite_count": 1041472,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FiDN441XEAEq5lc.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1594500655724609536",
"created_at": "2022-11-21T01:19:15.000Z",
"quote_count": 26030,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1587911540770222081",
"conversation_id": "1587647032457449473",
"full_text": "@AOC Your feedback is appreciated, now pay $8",
"reply_count": 43326,
"retweet_count": 75097,
"favorite_count": 1028618,
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"id_str": "138203134",
"name": "Alexandria Ocasio-Cortez",
"screen_name": "AOC",
"profile": "https://twitter.com/AOC"
}
],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1587911540770222081",
"created_at": "2022-11-02T20:56:27.000Z",
"quote_count": 17086,
"is_quote_tweet": false,
"replying_to_tweet": "https://twitter.com/AOC/status/1587647032457449473",
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1625377144137461761",
"conversation_id": "1625377144137461761",
"full_text": "There are no coincidences https://t.co/92Ny452J9B",
"reply_count": 25034,
"retweet_count": 87106,
"favorite_count": 1034478,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Fo5_5eWaMAMEPaf.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1625377144137461761",
"created_at": "2023-02-14T06:11:23.000Z",
"view_count": 115414305,
"quote_count": 11381,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1608828315581976576",
"conversation_id": "1608828315581976576",
"full_text": "https://t.co/v1rrSsdwdg",
"reply_count": 56860,
"retweet_count": 137588,
"favorite_count": 984592,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FlO00p-aYAE5h8J.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1608828315581976576",
"created_at": "2022-12-30T14:12:15.000Z",
"view_count": 88845731,
"quote_count": 15482,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1587297730631696384",
"conversation_id": "1587297730631696384",
"full_text": "😉 https://t.co/eaIYaDRBnu",
"reply_count": 33970,
"retweet_count": 67582,
"favorite_count": 969459,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Fgc23kFXkAEJOas.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1587297730631696384",
"created_at": "2022-11-01T04:17:24.000Z",
"quote_count": 7822,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1357236825589432322",
"conversation_id": "1357236825589432322",
"full_text": "ur welcome https://t.co/e2KF57KLxb",
"reply_count": 21387,
"retweet_count": 129294,
"favorite_count": 906408,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/EtXfpgGWYAEIa7y.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1357236825589432322",
"created_at": "2021-02-04T07:57:30.000Z",
"quote_count": 18283,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1595207476936413187",
"conversation_id": "1595207476936413187",
"full_text": "Wasn’t Twitter supposed to die by now or something … ?",
"reply_count": 65614,
"retweet_count": 64613,
"favorite_count": 932862,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1595207476936413187",
"created_at": "2022-11-23T00:07:54.000Z",
"quote_count": 12541,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1585966869122457600",
"conversation_id": "1585966869122457600",
"full_text": "🎶 let the good times roll 🎶",
"reply_count": 44899,
"retweet_count": 82648,
"favorite_count": 942793,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1585966869122457600",
"created_at": "2022-10-28T12:09:02.000Z",
"quote_count": 7638,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1604650028999405568",
"conversation_id": "1604650028999405568",
"full_text": "Those who want power are the ones who least deserve it",
"reply_count": 89824,
"retweet_count": 92573,
"favorite_count": 945701,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1604650028999405568",
"created_at": "2022-12-19T01:29:14.000Z",
"view_count": 103726233,
"quote_count": 26405,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1594131768298315777",
"conversation_id": "1594131768298315777",
"full_text": "The people have spoken. \n\nTrump will be reinstated.\n\nVox Populi, Vox Dei.",
"reply_count": 128348,
"retweet_count": 118481,
"favorite_count": 913495,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1594131768298315777",
"created_at": "2022-11-20T00:53:25.000Z",
"quote_count": 39411,
"is_quote_tweet": true,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"quoted_tweet": {
"username": "elonmusk",
"user_id": "44196397",
"id": "1593767953706921985",
"conversation_id": "1593767953706921985",
"full_text": "Reinstate former President Trump",
"reply_count": 210109,
"retweet_count": 213875,
"favorite_count": 794653,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1593767953706921985",
"created_at": "2022-11-19T00:47:45.000Z",
"#sort_index": "1694472769204387754",
"quote_count": 75130,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false
},
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1593767953706921985",
"conversation_id": "1593767953706921985",
"full_text": "Reinstate former President Trump",
"reply_count": 210109,
"retweet_count": 213875,
"favorite_count": 794653,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1593767953706921985",
"created_at": "2022-11-19T00:47:45.000Z",
"quote_count": 75130,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1587129795732770824",
"conversation_id": "1587129795732770824",
"full_text": "If I had a dollar for every time someone asked me if Trump is coming back on this platform, Twitter would be minting money!",
"reply_count": 69021,
"retweet_count": 55275,
"favorite_count": 907907,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1587129795732770824",
"created_at": "2022-10-31T17:10:05.000Z",
"quote_count": 6873,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1511011921495011328",
"conversation_id": "1511011921495011328",
"full_text": "Oh hi lol",
"reply_count": 64749,
"retweet_count": 50654,
"favorite_count": 884878,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1511011921495011328",
"created_at": "2022-04-04T16:04:49.000Z",
"quote_count": 10090,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1683378289031761920",
"conversation_id": "1683378289031761920",
"full_text": "Our headquarters tonight https://t.co/GO6yY8R7fO",
"reply_count": 48576,
"retweet_count": 74788,
"favorite_count": 943571,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/F1yPk5VXoAA3rGZ.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1683378289031761920",
"created_at": "2023-07-24T07:27:14.000Z",
"view_count": 110928423,
"quote_count": 20062,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1347978218494513152",
"conversation_id": "1347978218494513152",
"full_text": "My 14-year-old son, Saxon, said he feels like 2021 will be a good year. I agree. Let us all make it so.",
"reply_count": 26148,
"retweet_count": 57425,
"favorite_count": 841624,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1347978218494513152",
"created_at": "2021-01-09T18:47:06.000Z",
"quote_count": 10610,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1641858340752875535",
"conversation_id": "1641858340752875535",
"full_text": "https://t.co/qviPxhX7n8",
"reply_count": 49591,
"retweet_count": 41093,
"favorite_count": 918203,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FskNdX5WYAkmETe.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1641858340752875535",
"created_at": "2023-03-31T17:41:47.000Z",
"view_count": 77587609,
"quote_count": 10737,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1514564966564651008",
"conversation_id": "1514564966564651008",
"full_text": "I made an offer \nhttps://t.co/VvreuPMeLu",
"reply_count": 75744,
"retweet_count": 101232,
"favorite_count": 864685,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [
{
"url": "https://t.co/VvreuPMeLu",
"expanded_url": "https://www.sec.gov/Archives/edgar/data/0001418091/000110465922045641/tm2212748d1_sc13da.htm",
"display_url": "sec.gov/Archives/edgar…"
}
],
"media": [],
"url": "https://twitter.com/elonmusk/status/1514564966564651008",
"created_at": "2022-04-14T11:23:21.000Z",
"quote_count": 30137,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1597405399040217088",
"conversation_id": "1597405399040217088",
"full_text": "This is a battle for the future of civilization. If free speech is lost even in America, tyranny is all that lies ahead.",
"reply_count": 82874,
"retweet_count": 136750,
"favorite_count": 878560,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1597405399040217088",
"created_at": "2022-11-29T01:41:40.000Z",
"quote_count": 16765,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1609254628113420290",
"conversation_id": "1609254628113420290",
"full_text": "Sometimes it’s just better to make pizza at home",
"reply_count": 51068,
"retweet_count": 42308,
"favorite_count": 804635,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1609254628113420290",
"created_at": "2022-12-31T18:26:16.000Z",
"view_count": 81906590,
"quote_count": 7397,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1349286488618491904",
"conversation_id": "1349286488618491904",
"full_text": "Legalize comedy",
"reply_count": 16426,
"retweet_count": 75729,
"favorite_count": 804936,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1349286488618491904",
"created_at": "2021-01-13T09:25:42.000Z",
"quote_count": 8341,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1618371072486936578",
"conversation_id": "1618371072486936578",
"full_text": "Changed my name to Mr. Tweet, now Twitter won’t let me change it back 🤣",
"reply_count": 61260,
"retweet_count": 53130,
"favorite_count": 882792,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1618371072486936578",
"created_at": "2023-01-25T22:11:46.000Z",
"view_count": 82457457,
"quote_count": 11770,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1642962756906418176",
"conversation_id": "1642962756906418176",
"full_text": "https://t.co/wmN5WxUhfQ",
"reply_count": 31801,
"retweet_count": 80651,
"favorite_count": 887233,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Fsz562paMAAB_nP.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1642962756906418176",
"created_at": "2023-04-03T18:50:20.000Z",
"view_count": 76577794,
"quote_count": 16600,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1680423042873278465",
"conversation_id": "1680423042873278465",
"full_text": "https://t.co/LCXD4QPsNW",
"reply_count": 21342,
"retweet_count": 79920,
"favorite_count": 901835,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/F1IP2Z9WYAA-AR0.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1680423042873278465",
"created_at": "2023-07-16T03:44:08.000Z",
"view_count": 95252197,
"quote_count": 8094,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1374617643446063105",
"conversation_id": "1374617643446063105",
"full_text": "You can now buy a Tesla with Bitcoin",
"reply_count": 32923,
"retweet_count": 100977,
"favorite_count": 816205,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1374617643446063105",
"created_at": "2021-03-24T07:02:40.000Z",
"quote_count": 21989,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1666964082363371520",
"conversation_id": "1666964082363371520",
"full_text": "https://t.co/kf7VYDgOra",
"reply_count": 21723,
"retweet_count": 102762,
"favorite_count": 874592,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FyI-_vraEAEfW6O.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1666964082363371520",
"created_at": "2023-06-09T00:23:02.000Z",
"view_count": 75132462,
"quote_count": 8403,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1266811094527508481",
"conversation_id": "1266811094527508481",
"full_text": "5 mins to T-0",
"reply_count": 15420,
"retweet_count": 44012,
"favorite_count": 766204,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1266811094527508481",
"created_at": "2020-05-30T19:17:55.000Z",
"quote_count": 3961,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1597165510595989504",
"conversation_id": "1597165510595989504",
"full_text": "My bedside table https://t.co/sIdRYJcLTK",
"reply_count": 85849,
"retweet_count": 53759,
"favorite_count": 851738,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FipFkIsVsAAM0O_.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1597165510595989504",
"created_at": "2022-11-28T09:48:26.000Z",
"quote_count": 28524,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1517215066550116354",
"conversation_id": "1517215066550116354",
"full_text": "If our twitter bid succeeds, we will defeat the spam bots or die trying!",
"reply_count": 32433,
"retweet_count": 69710,
"favorite_count": 833196,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1517215066550116354",
"created_at": "2022-04-21T18:53:55.000Z",
"quote_count": 12602,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1276396101872922625",
"conversation_id": "1276396101872922625",
"full_text": "https://t.co/e9dPKVSjjl",
"reply_count": 5811,
"retweet_count": 116826,
"favorite_count": 777176,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/EbarfO6U4AA-7c5.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1276396101872922625",
"created_at": "2020-06-26T06:05:19.000Z",
"quote_count": 7287,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1559691922725281800",
"conversation_id": "1559690651687608321",
"full_text": "Also, I’m buying Manchester United ur welcome",
"reply_count": 54593,
"retweet_count": 112817,
"favorite_count": 847886,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1559691922725281800",
"created_at": "2022-08-17T00:01:46.000Z",
"quote_count": 52581,
"is_quote_tweet": false,
"replying_to_tweet": "https://twitter.com/elonmusk/status/1559690651687608321",
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1519036983137509376",
"conversation_id": "1519020176884305920",
"full_text": "By “free speech”, I simply mean that which matches the law. \n\nI am against censorship that goes far beyond the law. \n\nIf people want less free speech, they will ask government to pass laws to that effect.\n\nTherefore, going beyond the law is contrary to the will of the people.",
"reply_count": 58411,
"retweet_count": 85586,
"favorite_count": 804143,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1519036983137509376",
"created_at": "2022-04-26T19:33:33.000Z",
"quote_count": 16481,
"is_quote_tweet": false,
"replying_to_tweet": "https://twitter.com/elonmusk/status/1519020176884305920",
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1526997132858822658",
"conversation_id": "1526997132858822658",
"full_text": "In the past I voted Democrat, because they were (mostly) the kindness party.\n\nBut they have become the party of division & hate, so I can no longer support them and will vote Republican.\n\nNow, watch their dirty tricks campaign against me unfold … 🍿",
"reply_count": 106371,
"retweet_count": 119882,
"favorite_count": 804876,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1526997132858822658",
"created_at": "2022-05-18T18:44:21.000Z",
"quote_count": 32796,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1688022163574439937",
"conversation_id": "1688022163574439937",
"full_text": "If you were unfairly treated by your employer due to posting or liking something on this platform, we will fund your legal bill.\n\nNo limit. \n\nPlease let us know.",
"reply_count": 46614,
"retweet_count": 142357,
"favorite_count": 867887,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1688022163574439937",
"created_at": "2023-08-06T03:00:20.000Z",
"view_count": 137457648,
"quote_count": 27757,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1432818021836357634",
"conversation_id": "1432818021836357634",
"full_text": "https://t.co/YUt6Ltz2B6",
"reply_count": 6742,
"retweet_count": 13738,
"favorite_count": 515958,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/E-JkZaKVIAcbTdW.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1432818021836357634",
"created_at": "2021-08-31T21:30:11.000Z",
"quote_count": 788,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1649052609590992901",
"conversation_id": "1649052609590992901",
"full_text": "https://t.co/vX3M7B3J1G",
"reply_count": 40115,
"retweet_count": 74183,
"favorite_count": 838276,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/ext_tw_video_thumb/1649047801446400000/pu/img/e2X_U3_Ti1mhf0fD.jpg",
"type": "video",
"video_url": "https://video.twimg.com/ext_tw_video/1649047801446400000/pu/vid/540x634/iek2j2lOnDvsuctV.mp4?tag=12"
}
],
"url": "https://twitter.com/elonmusk/status/1649052609590992901",
"created_at": "2023-04-20T14:09:14.000Z",
"view_count": 95752230,
"quote_count": 9531,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1597336812732575744",
"conversation_id": "1597336812732575744",
"full_text": "The Twitter Files on free speech suppression soon to be published on Twitter itself. The public deserves to know what really happened …",
"reply_count": 45806,
"retweet_count": 122369,
"favorite_count": 810965,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1597336812732575744",
"created_at": "2022-11-28T21:09:07.000Z",
"quote_count": 14868,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1361252063926251521",
"conversation_id": "1361252063926251521",
"full_text": "https://t.co/w11m1IAG0z",
"reply_count": 10498,
"retweet_count": 68594,
"favorite_count": 756594,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/EuQjiWeXAAEYUts.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1361252063926251521",
"created_at": "2021-02-15T09:52:37.000Z",
"quote_count": 5088,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1672582593638957056",
"conversation_id": "1672582593638957056",
"full_text": "Don’t even trust nobody https://t.co/VHa1zVGI71",
"reply_count": 22047,
"retweet_count": 72713,
"favorite_count": 832630,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FzY0_SvaIAAb9Xr.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1672582593638957056",
"created_at": "2023-06-24T12:29:00.000Z",
"view_count": 69581275,
"quote_count": 4599,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1686058966705487875",
"conversation_id": "1686058966705487875",
"full_text": "Wow, I’m glad so many people love Canada too 🤗 https://t.co/5oOL05zawB",
"reply_count": 35449,
"retweet_count": 44669,
"favorite_count": 846460,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/F2YVsVIXwBMdxRO.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1686058966705487875",
"created_at": "2023-07-31T16:59:17.000Z",
"view_count": 65689425,
"quote_count": 8190,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1662654838398697472",
"conversation_id": "1662654838398697472",
"full_text": "Sorry this app takes up so much space https://t.co/bCCfcOhNJt",
"reply_count": 48357,
"retweet_count": 63774,
"favorite_count": 825999,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FxLvvm1XoAEkCaK.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1662654838398697472",
"created_at": "2023-05-28T02:59:38.000Z",
"view_count": 104719593,
"quote_count": 14271,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1525305145239781377",
"conversation_id": "1525305145239781377",
"full_text": "The bots are angry at being counted 🤣",
"reply_count": 33782,
"retweet_count": 52651,
"favorite_count": 778264,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1525305145239781377",
"created_at": "2022-05-14T02:41:00.000Z",
"quote_count": 5713,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1520021098934554624",
"conversation_id": "1520017094007476224",
"full_text": "But I’m no fan of the far right either. \n\nLet’s have less hate and more love.",
"reply_count": 40853,
"retweet_count": 44229,
"favorite_count": 771649,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1520021098934554624",
"created_at": "2022-04-29T12:44:05.000Z",
"quote_count": 6144,
"is_quote_tweet": false,
"replying_to_tweet": "https://twitter.com/elonmusk/status/1520017094007476224",
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1607590239874211847",
"conversation_id": "1607590239874211847",
"full_text": "Some nights … https://t.co/BLAUsJr4wb",
"reply_count": 41223,
"retweet_count": 47150,
"favorite_count": 777302,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Fk9Oy_iWIAEx8Qd.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1607590239874211847",
"created_at": "2022-12-27T04:12:35.000Z",
"view_count": 74451033,
"quote_count": 10569,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1518614732839735304",
"conversation_id": "1518614732839735304",
"full_text": "And be my love in the rain",
"reply_count": 38409,
"retweet_count": 49713,
"favorite_count": 766115,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1518614732839735304",
"created_at": "2022-04-25T15:35:41.000Z",
"quote_count": 6798,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1497701484003213317",
"conversation_id": "1497543633293266944",
"full_text": "@FedorovMykhailo Starlink service is now active in Ukraine. More terminals en route.",
"reply_count": 26104,
"retweet_count": 127689,
"favorite_count": 769963,
"hashtags": [],
"symbols": [],
"user_mentions": [
{
"id_str": "1331528215899344896",
"name": "Mykhailo Fedorov",
"screen_name": "FedorovMykhailo",
"profile": "https://twitter.com/FedorovMykhailo"
}
],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1497701484003213317",
"created_at": "2022-02-26T22:33:54.000Z",
"quote_count": 23725,
"is_quote_tweet": false,
"replying_to_tweet": "https://twitter.com/FedorovMykhailo/status/1497543633293266944",
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1505100708256825347",
"conversation_id": "1505100708256825347",
"full_text": "https://t.co/qZSX2up9W0",
"reply_count": 25006,
"retweet_count": 63264,
"favorite_count": 752723,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FOMxHZwXEAIreox.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1505100708256825347",
"created_at": "2022-03-19T08:35:46.000Z",
"quote_count": 4722,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1658960642445910017",
"conversation_id": "1658960642445910017",
"full_text": "https://t.co/FxOptt5Rgb",
"reply_count": 30576,
"retweet_count": 54781,
"favorite_count": 792357,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/FwXP5iKWcAEecKA.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1658960642445910017",
"created_at": "2023-05-17T22:20:13.000Z",
"view_count": 66684167,
"quote_count": 5027,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1358319935978496001",
"conversation_id": "1358319935978496001",
"full_text": "So … it’s finally come to this … https://t.co/Gf0Rg2QOaF",
"reply_count": 27511,
"retweet_count": 83980,
"favorite_count": 720596,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Etm4yFZUcAAoN5u.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1358319935978496001",
"created_at": "2021-02-07T07:41:23.000Z",
"quote_count": 7616,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1129274835173908481",
"conversation_id": "1129274835173908481",
"full_text": "And I am forever grateful https://t.co/kU1pT8t0yv",
"reply_count": 2904,
"retweet_count": 117714,
"favorite_count": 667576,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/D6v9ed6UwAAoKg2.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1129274835173908481",
"created_at": "2019-05-17T06:37:56.000Z",
"quote_count": 3819,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1647629006089461761",
"conversation_id": "1647629006089461761",
"full_text": "Launch attempt tomorrow https://t.co/czFsQ53Xsa",
"reply_count": 26620,
"retweet_count": 51862,
"favorite_count": 783936,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Ft2N2IxX0AkIbLf.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1647629006089461761",
"created_at": "2023-04-16T15:52:21.000Z",
"view_count": 75845428,
"quote_count": 4885,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1375033483148451842",
"conversation_id": "1375033483148451842",
"full_text": "If there’s ever a scandal about me, *please* call it Elongate",
"reply_count": 20973,
"retweet_count": 53774,
"favorite_count": 723756,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [],
"url": "https://twitter.com/elonmusk/status/1375033483148451842",
"created_at": "2021-03-25T10:35:03.000Z",
"quote_count": 8794,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1677470862436450308",
"conversation_id": "1677470862436450308",
"full_text": "Just drove Cybertruck around Austin! https://t.co/QN19Agqa7R",
"reply_count": 49034,
"retweet_count": 48651,
"favorite_count": 792030,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/F0eS2dyXgAAIqng.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1677470862436450308",
"created_at": "2023-07-08T00:13:14.000Z",
"view_count": 75117791,
"quote_count": 7125,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
},
{
"username": "elonmusk",
"user_id": "44196397",
"id": "1629598417159692288",
"conversation_id": "1629598417159692288",
"full_text": "https://t.co/5wIbOXFs1e",
"reply_count": 14937,
"retweet_count": 67980,
"favorite_count": 774099,
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [
{
"media_url": "https://pbs.twimg.com/media/Fp1_H34WwAI3n1j.jpg",
"type": "photo"
}
],
"url": "https://twitter.com/elonmusk/status/1629598417159692288",
"created_at": "2023-02-25T21:45:13.000Z",
"view_count": 96013117,
"quote_count": 6278,
"is_quote_tweet": false,
"is_retweet": false,
"is_pinned": false,
"is_truncated": false,
"startUrl": "https://twitter.com/elonmusk/with_replies"
}] | 0 |
public_repos | public_repos/twitter-finetune/ingest.py | import json
from langchain.schema import AIMessage
from langchain.adapters.openai import convert_message_to_dict
import time
import openai
from io import BytesIO
if __name__ == "__main__":
with open('dataset_twitter-scraper_2023-08-23_22-13-19-740.json') as f:
data = json.load(f)
tweets = [d["full_text"] for d in data if "t.co" not in d['full_text']]
messages = [AIMessage(content=t) for t in tweets]
system_message = {"role": "system", "content": "write a tweet"}
data = [[system_message, convert_message_to_dict(m)] for m in messages]
my_file = BytesIO()
for m in data:
my_file.write((json.dumps({"messages": m}) + "\n").encode('utf-8'))
my_file.seek(0)
training_file = openai.File.create(
file=my_file,
purpose='fine-tune'
)
while True:
try:
job = openai.FineTuningJob.create(training_file=training_file.id, model="gpt-3.5-turbo")
except Exception as e:
print(e)
print("Trying again in ten seconds....")
time.sleep(10)
start = time.time()
while True:
ftj = openai.FineTuningJob.retrieve(job.id)
if ftj.fine_tuned_model is None:
print(f"Waiting for fine-tuning to complete... Elapsed: {time.time() - start}", end="\r", flush=True)
time.sleep(10)
else:
print("\n")
print(ftj.fine_tuned_model, flush=True)
break
| 0 |
public_repos | public_repos/numpy-stubs/.flake8 | # Some PEP8 deviations are considered irrelevant to stub files:
# (error counts as of 2017-05-22)
# 17952 E704 multiple statements on one line (def)
# 12197 E301 expected 1 blank line
# 7155 E302 expected 2 blank lines
# 1463 F401 imported but unused
# 967 E701 multiple statements on one line (colon)
# 457 F811 redefinition
# 390 E305 expected 2 blank lines
# 4 E741 ambiguous variable name
# Nice-to-haves ignored for now
# 2307 E501 line too long
# Other ignored warnings
# W504 line break after binary operator
[flake8]
ignore = F401, F403, F405, F811, E301, E302, E305, E501, E701, E704, E741, B303, W504 | 0 |
public_repos | public_repos/numpy-stubs/setup.cfg | # Ignore the following errors (for stubs):
# E301 expected 1 blank line, found 0
# E302 expected 2 blank lines, found 1
# E305 expected 2 blank lines after class or function definition, found 1
# E701 multiple statements on one line (colon)
# E704 multiple statements on one line (def)
[flake8]
ignore = E301, E302, E305, E701, E704
exclude = .git,__pycache__,tests/reveal
| 0 |
public_repos | public_repos/numpy-stubs/setup.py | from setuptools import setup
import os
def find_stubs(package):
stubs = []
for root, dirs, files in os.walk(package):
for file in files:
path = os.path.join(root, file).replace(package + os.sep, "", 1)
stubs.append(path)
return {package: stubs}
setup(
name="numpy-stubs",
maintainer="NumPy Developers",
maintainer_email="numpy-discussion@python.org",
description="PEP 561 type stubs for numpy",
url="http://www.numpy.org",
license="BSD",
version="0.0.1",
packages=["numpy-stubs"],
# PEP 561 requires these
install_requires=[
"numpy>=1.16.0",
'typing_extensions>=3.7.4; python_version<"3.8"',
],
package_data=find_stubs("numpy-stubs"),
zip_safe=False,
)
| 0 |
public_repos | public_repos/numpy-stubs/.travis.yml | language: python
matrix:
include:
- python: 3.8
dist: xenial
- python: 3.7
dist: xenial
- python: 3.6
dist: xenial
notifications:
email: false
install:
- pip install -r test-requirements.txt
- pip install .
script:
- flake8
- black --check .
- py.test
cache:
directories:
- "$HOME/.cache/pip"
| 0 |
public_repos | public_repos/numpy-stubs/runtests.py | #!/usr/bin/env python
import argparse
import ast
import importlib
import os
import subprocess
import sys
import pytest
STUBS_ROOT = os.path.dirname(os.path.abspath(__file__))
# Technically "public" functions (they don't start with an underscore)
# that we don't want to include.
BLACKLIST = {
"numpy": {
# Stdlib modules in the namespace by accident
"absolute_import",
"division",
"print_function",
"warnings",
# Accidentally public, deprecated, or shouldn't be used
"Tester",
"add_docstring",
"add_newdoc",
"add_newdoc_ufunc",
"core",
"fastCopyAndTranspose",
"get_array_wrap",
"int_asbuffer",
"oldnumeric",
"safe_eval",
"set_numeric_ops",
"test",
# Builtins
"bool",
"complex",
"float",
"int",
"long",
"object",
"str",
"unicode",
# Should use numpy_financial instead
"fv",
"ipmt",
"irr",
"mirr",
"nper",
"npv",
"pmt",
"ppmt",
"pv",
"rate",
# More standard names should be preferred
"alltrue", # all
"sometrue", # any
}
}
class FindAttributes(ast.NodeVisitor):
"""Find top-level attributes/functions/classes in the stubs.
Do this by walking the stubs ast. See e.g.
https://greentreesnakes.readthedocs.io/en/latest/index.html
for more information on working with Python's ast.
"""
def __init__(self):
self.attributes = set()
def visit_FunctionDef(self, node):
if node.name == "__getattr__":
# Not really a module member.
return
self.attributes.add(node.name)
# Do not call self.generic_visit; we are only interested in
# top-level functions.
return
def visit_ClassDef(self, node):
if not node.name.startswith("_"):
self.attributes.add(node.name)
return
def visit_AnnAssign(self, node):
self.attributes.add(node.target.id)
def find_missing(module_name):
module_path = os.path.join(
STUBS_ROOT,
module_name.replace("numpy", "numpy-stubs").replace(".", os.sep),
"__init__.pyi",
)
module = importlib.import_module(module_name)
module_attributes = {
attribute for attribute in dir(module) if not attribute.startswith("_")
}
if os.path.isfile(module_path):
with open(module_path) as f:
tree = ast.parse(f.read())
ast_visitor = FindAttributes()
ast_visitor.visit(tree)
stubs_attributes = ast_visitor.attributes
else:
# No stubs for this module yet.
stubs_attributes = set()
blacklist = BLACKLIST.get(module_name, set())
missing = module_attributes - stubs_attributes - blacklist
print("\n".join(sorted(missing)))
def run_pytest(argv):
subprocess.run(
[sys.executable, "-m", "pip", "install", STUBS_ROOT],
capture_output=True,
check=True,
)
return pytest.main([STUBS_ROOT] + argv)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--find-missing")
args, remaining_argv = parser.parse_known_args()
if args.find_missing is not None:
find_missing(args.find_missing)
sys.exit(0)
sys.exit(run_pytest(remaining_argv))
if __name__ == "__main__":
main()
| 0 |
public_repos | public_repos/numpy-stubs/test-requirements.txt | black==18.9b0
flake8==3.7.9
flake8-pyi==18.3.1
pytest==4.0.0
mypy==0.770
| 0 |
public_repos | public_repos/numpy-stubs/README.md | **These stubs have been merged into NumPy, and all further development will happen in the NumPy main repo. We welcome your contributions there!**
| 0 |
public_repos | public_repos/numpy-stubs/LICENSE | Copyright (c) 2005-2017, NumPy Developers.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the NumPy Developers nor the names of any
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| 0 |
public_repos/numpy-stubs | public_repos/numpy-stubs/numpy-stubs/__init__.pyi | import builtins
import sys
import datetime as dt
from abc import abstractmethod
from numpy.core._internal import _ctypes
from numpy.typing import ArrayLike, DtypeLike, _Shape, _ShapeLike
from typing import (
Any,
ByteString,
Callable,
Container,
Callable,
Dict,
Generic,
IO,
Iterable,
List,
Mapping,
Optional,
overload,
Sequence,
Sized,
SupportsAbs,
SupportsComplex,
SupportsFloat,
SupportsInt,
Text,
Tuple,
Type,
TypeVar,
Union,
)
if sys.version_info[0] < 3:
class SupportsBytes: ...
else:
from typing import SupportsBytes
if sys.version_info >= (3, 8):
from typing import Literal, Protocol
else:
from typing_extensions import Literal, Protocol
# TODO: remove when the full numpy namespace is defined
def __getattr__(name: str) -> Any: ...
_NdArraySubClass = TypeVar("_NdArraySubClass", bound=ndarray)
class dtype:
names: Optional[Tuple[str, ...]]
def __init__(self, obj: DtypeLike, align: bool = ..., copy: bool = ...) -> None: ...
def __eq__(self, other: DtypeLike) -> bool: ...
def __ne__(self, other: DtypeLike) -> bool: ...
def __gt__(self, other: DtypeLike) -> bool: ...
def __ge__(self, other: DtypeLike) -> bool: ...
def __lt__(self, other: DtypeLike) -> bool: ...
def __le__(self, other: DtypeLike) -> bool: ...
@property
def alignment(self) -> int: ...
@property
def base(self) -> dtype: ...
@property
def byteorder(self) -> str: ...
@property
def char(self) -> str: ...
@property
def descr(self) -> List[Union[Tuple[str, str], Tuple[str, str, _Shape]]]: ...
@property
def fields(
self,
) -> Optional[Mapping[str, Union[Tuple[dtype, int], Tuple[dtype, int, Any]]]]: ...
@property
def flags(self) -> int: ...
@property
def hasobject(self) -> bool: ...
@property
def isbuiltin(self) -> int: ...
@property
def isnative(self) -> bool: ...
@property
def isalignedstruct(self) -> bool: ...
@property
def itemsize(self) -> int: ...
@property
def kind(self) -> str: ...
@property
def metadata(self) -> Optional[Mapping[str, Any]]: ...
@property
def name(self) -> str: ...
@property
def num(self) -> int: ...
@property
def shape(self) -> _Shape: ...
@property
def ndim(self) -> int: ...
@property
def subdtype(self) -> Optional[Tuple[dtype, _Shape]]: ...
def newbyteorder(self, new_order: str = ...) -> dtype: ...
# Leave str and type for end to avoid having to use `builtins.str`
# everywhere. See https://github.com/python/mypy/issues/3775
@property
def str(self) -> builtins.str: ...
@property
def type(self) -> Type[generic]: ...
_Dtype = dtype # to avoid name conflicts with ndarray.dtype
class _flagsobj:
aligned: bool
updateifcopy: bool
writeable: bool
writebackifcopy: bool
@property
def behaved(self) -> bool: ...
@property
def c_contiguous(self) -> bool: ...
@property
def carray(self) -> bool: ...
@property
def contiguous(self) -> bool: ...
@property
def f_contiguous(self) -> bool: ...
@property
def farray(self) -> bool: ...
@property
def fnc(self) -> bool: ...
@property
def forc(self) -> bool: ...
@property
def fortran(self) -> bool: ...
@property
def num(self) -> int: ...
@property
def owndata(self) -> bool: ...
def __getitem__(self, key: str) -> bool: ...
def __setitem__(self, key: str, value: bool) -> None: ...
_FlatIterSelf = TypeVar("_FlatIterSelf", bound=flatiter)
class flatiter(Generic[_ArraySelf]):
@property
def base(self) -> _ArraySelf: ...
@property
def coords(self) -> _Shape: ...
@property
def index(self) -> int: ...
def copy(self) -> _ArraySelf: ...
def __iter__(self: _FlatIterSelf) -> _FlatIterSelf: ...
def __next__(self) -> generic: ...
_ArraySelf = TypeVar("_ArraySelf", bound=_ArrayOrScalarCommon)
class _ArrayOrScalarCommon(
SupportsInt, SupportsFloat, SupportsComplex, SupportsBytes, SupportsAbs[Any]
):
@property
def T(self: _ArraySelf) -> _ArraySelf: ...
@property
def base(self) -> Optional[ndarray]: ...
@property
def dtype(self) -> _Dtype: ...
@property
def data(self) -> memoryview: ...
@property
def flags(self) -> _flagsobj: ...
@property
def size(self) -> int: ...
@property
def itemsize(self) -> int: ...
@property
def nbytes(self) -> int: ...
@property
def ndim(self) -> int: ...
@property
def shape(self) -> _Shape: ...
@property
def strides(self) -> _Shape: ...
def __array__(self, __dtype: DtypeLike = ...) -> ndarray: ...
def __int__(self) -> int: ...
def __float__(self) -> float: ...
def __complex__(self) -> complex: ...
if sys.version_info[0] < 3:
def __oct__(self) -> str: ...
def __hex__(self) -> str: ...
def __nonzero__(self) -> bool: ...
def __unicode__(self) -> Text: ...
else:
def __bool__(self) -> bool: ...
def __bytes__(self) -> bytes: ...
def __str__(self) -> str: ...
def __repr__(self) -> str: ...
def __copy__(self: _ArraySelf, order: str = ...) -> _ArraySelf: ...
def __deepcopy__(self: _ArraySelf, memo: dict) -> _ArraySelf: ...
def __lt__(self, other): ...
def __le__(self, other): ...
def __eq__(self, other): ...
def __ne__(self, other): ...
def __gt__(self, other): ...
def __ge__(self, other): ...
def __add__(self, other): ...
def __radd__(self, other): ...
def __iadd__(self, other): ...
def __sub__(self, other): ...
def __rsub__(self, other): ...
def __isub__(self, other): ...
def __mul__(self, other): ...
def __rmul__(self, other): ...
def __imul__(self, other): ...
if sys.version_info[0] < 3:
def __div__(self, other): ...
def __rdiv__(self, other): ...
def __idiv__(self, other): ...
def __truediv__(self, other): ...
def __rtruediv__(self, other): ...
def __itruediv__(self, other): ...
def __floordiv__(self, other): ...
def __rfloordiv__(self, other): ...
def __ifloordiv__(self, other): ...
def __mod__(self, other): ...
def __rmod__(self, other): ...
def __imod__(self, other): ...
def __divmod__(self, other): ...
def __rdivmod__(self, other): ...
# NumPy's __pow__ doesn't handle a third argument
def __pow__(self, other): ...
def __rpow__(self, other): ...
def __ipow__(self, other): ...
def __lshift__(self, other): ...
def __rlshift__(self, other): ...
def __ilshift__(self, other): ...
def __rshift__(self, other): ...
def __rrshift__(self, other): ...
def __irshift__(self, other): ...
def __and__(self, other): ...
def __rand__(self, other): ...
def __iand__(self, other): ...
def __xor__(self, other): ...
def __rxor__(self, other): ...
def __ixor__(self, other): ...
def __or__(self, other): ...
def __ror__(self, other): ...
def __ior__(self, other): ...
if sys.version_info[:2] >= (3, 5):
def __matmul__(self, other): ...
def __rmatmul__(self, other): ...
def __neg__(self: _ArraySelf) -> _ArraySelf: ...
def __pos__(self: _ArraySelf) -> _ArraySelf: ...
def __abs__(self: _ArraySelf) -> _ArraySelf: ...
def __invert__(self: _ArraySelf) -> _ArraySelf: ...
# TODO(shoyer): remove when all methods are defined
def __getattr__(self, name) -> Any: ...
_BufferType = Union[ndarray, bytes, bytearray, memoryview]
class ndarray(_ArrayOrScalarCommon, Iterable, Sized, Container):
@property
def real(self: _ArraySelf) -> _ArraySelf: ...
@real.setter
def real(self, value: ArrayLike) -> None: ...
@property
def imag(self: _ArraySelf) -> _ArraySelf: ...
@imag.setter
def imag(self, value: ArrayLike) -> None: ...
def __new__(
cls: Type[_ArraySelf],
shape: Sequence[int],
dtype: DtypeLike = ...,
buffer: _BufferType = ...,
offset: int = ...,
strides: _ShapeLike = ...,
order: Optional[str] = ...,
) -> _ArraySelf: ...
@property
def dtype(self) -> _Dtype: ...
@property
def ctypes(self) -> _ctypes: ...
@property
def shape(self) -> _Shape: ...
@shape.setter
def shape(self, value: _ShapeLike): ...
@property
def flat(self: _ArraySelf) -> flatiter[_ArraySelf]: ...
@property
def strides(self) -> _Shape: ...
@strides.setter
def strides(self, value: _ShapeLike): ...
# Array conversion
@overload
def item(self, *args: int) -> Any: ...
@overload
def item(self, args: Tuple[int, ...]) -> Any: ...
def tolist(self) -> List[Any]: ...
@overload
def itemset(self, __value: Any) -> None: ...
@overload
def itemset(self, __item: _ShapeLike, __value: Any) -> None: ...
def tostring(self, order: Optional[str] = ...) -> bytes: ...
def tobytes(self, order: Optional[str] = ...) -> bytes: ...
def tofile(
self, fid: Union[IO[bytes], str], sep: str = ..., format: str = ...
) -> None: ...
def dump(self, file: str) -> None: ...
def dumps(self) -> bytes: ...
def astype(
self: _ArraySelf,
dtype: DtypeLike,
order: str = ...,
casting: str = ...,
subok: bool = ...,
copy: bool = ...,
) -> _ArraySelf: ...
def byteswap(self: _ArraySelf, inplace: bool = ...) -> _ArraySelf: ...
def copy(self: _ArraySelf, order: str = ...) -> _ArraySelf: ...
@overload
def view(self, type: Type[_NdArraySubClass]) -> _NdArraySubClass: ...
@overload
def view(self: _ArraySelf, dtype: DtypeLike = ...) -> _ArraySelf: ...
@overload
def view(
self, dtype: DtypeLike, type: Type[_NdArraySubClass]
) -> _NdArraySubClass: ...
def getfield(
self: _ArraySelf, dtype: DtypeLike, offset: int = ...
) -> _ArraySelf: ...
def setflags(
self, write: bool = ..., align: bool = ..., uic: bool = ...
) -> None: ...
def fill(self, value: Any) -> None: ...
# Shape manipulation
@overload
def reshape(
self: _ArraySelf, shape: Sequence[int], *, order: str = ...
) -> _ArraySelf: ...
@overload
def reshape(self: _ArraySelf, *shape: int, order: str = ...) -> _ArraySelf: ...
@overload
def resize(self, new_shape: Sequence[int], *, refcheck: bool = ...) -> None: ...
@overload
def resize(self, *new_shape: int, refcheck: bool = ...) -> None: ...
@overload
def transpose(self: _ArraySelf, axes: Sequence[int]) -> _ArraySelf: ...
@overload
def transpose(self: _ArraySelf, *axes: int) -> _ArraySelf: ...
def swapaxes(self: _ArraySelf, axis1: int, axis2: int) -> _ArraySelf: ...
def flatten(self: _ArraySelf, order: str = ...) -> _ArraySelf: ...
def ravel(self: _ArraySelf, order: str = ...) -> _ArraySelf: ...
def squeeze(
self: _ArraySelf, axis: Union[int, Tuple[int, ...]] = ...
) -> _ArraySelf: ...
# Many of these special methods are irrelevant currently, since protocols
# aren't supported yet. That said, I'm adding them for completeness.
# https://docs.python.org/3/reference/datamodel.html
def __len__(self) -> int: ...
def __getitem__(self, key) -> Any: ...
def __setitem__(self, key, value): ...
def __iter__(self) -> Any: ...
def __contains__(self, key) -> bool: ...
def __index__(self) -> int: ...
# NOTE: while `np.generic` is not technically an instance of `ABCMeta`,
# the `@abstractmethod` decorator is herein used to (forcefully) deny
# the creation of `np.generic` instances.
# The `# type: ignore` comments are necessary to silence mypy errors regarding
# the missing `ABCMeta` metaclass.
# See https://github.com/numpy/numpy-stubs/pull/80 for more details.
class generic(_ArrayOrScalarCommon):
@abstractmethod
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
@property
def base(self) -> None: ...
class _real_generic(generic): # type: ignore
@property
def real(self: _ArraySelf) -> _ArraySelf: ...
@property
def imag(self: _ArraySelf) -> _ArraySelf: ...
class number(generic): ... # type: ignore
class bool_(_real_generic):
def __init__(self, value: object = ...) -> None: ...
class object_(generic):
def __init__(self, value: object = ...) -> None: ...
class datetime64:
@overload
def __init__(
self, _data: Union[datetime64, str, dt.datetime] = ..., _format: str = ...
) -> None: ...
@overload
def __init__(self, _data: int, _format: str) -> None: ...
def __add__(self, other: Union[timedelta64, int]) -> datetime64: ...
def __sub__(self, other: Union[timedelta64, datetime64, int]) -> timedelta64: ...
class integer(number, _real_generic): ... # type: ignore
class signedinteger(integer): ... # type: ignore
class int8(signedinteger):
def __init__(self, value: SupportsInt = ...) -> None: ...
class int16(signedinteger):
def __init__(self, value: SupportsInt = ...) -> None: ...
class int32(signedinteger):
def __init__(self, value: SupportsInt = ...) -> None: ...
class int64(signedinteger):
def __init__(self, value: SupportsInt = ...) -> None: ...
class timedelta64(signedinteger):
def __init__(self, _data: Any = ..., _format: str = ...) -> None: ...
@overload
def __add__(self, other: Union[timedelta64, int]) -> timedelta64: ...
@overload
def __add__(self, other: datetime64) -> datetime64: ...
def __sub__(self, other: Union[timedelta64, int]) -> timedelta64: ...
if sys.version_info[0] < 3:
@overload
def __div__(self, other: timedelta64) -> float: ...
@overload
def __div__(self, other: float) -> timedelta64: ...
@overload
def __truediv__(self, other: timedelta64) -> float: ...
@overload
def __truediv__(self, other: float) -> timedelta64: ...
def __mod__(self, other: timedelta64) -> timedelta64: ...
class unsignedinteger(integer): ... # type: ignore
class uint8(unsignedinteger):
def __init__(self, value: SupportsInt = ...) -> None: ...
class uint16(unsignedinteger):
def __init__(self, value: SupportsInt = ...) -> None: ...
class uint32(unsignedinteger):
def __init__(self, value: SupportsInt = ...) -> None: ...
class uint64(unsignedinteger):
def __init__(self, value: SupportsInt = ...) -> None: ...
class inexact(number): ... # type: ignore
class floating(inexact, _real_generic): ... # type: ignore
class float16(floating):
def __init__(self, value: SupportsFloat = ...) -> None: ...
class float32(floating):
def __init__(self, value: SupportsFloat = ...) -> None: ...
class float64(floating):
def __init__(self, value: SupportsFloat = ...) -> None: ...
class complexfloating(inexact): ... # type: ignore
class complex64(complexfloating):
def __init__(
self, value: Union[SupportsInt, SupportsFloat, SupportsComplex] = ...
) -> None: ...
@property
def real(self) -> float32: ...
@property
def imag(self) -> float32: ...
class complex128(complexfloating):
def __init__(
self, value: Union[SupportsInt, SupportsFloat, SupportsComplex] = ...
) -> None: ...
@property
def real(self) -> float64: ...
@property
def imag(self) -> float64: ...
class flexible(_real_generic): ... # type: ignore
class void(flexible):
def __init__(self, value: Union[int, integer, bool_, bytes, bytes_]): ...
class character(_real_generic): ... # type: ignore
class bytes_(character):
@overload
def __init__(self, value: object = ...) -> None: ...
@overload
def __init__(
self, value: object, encoding: str = ..., errors: str = ...
) -> None: ...
class str_(character):
@overload
def __init__(self, value: object = ...) -> None: ...
@overload
def __init__(
self, value: object, encoding: str = ..., errors: str = ...
) -> None: ...
# TODO(alan): Platform dependent types
# longcomplex, longdouble, longfloat
# bytes, short, intc, intp, longlong
# half, single, double, longdouble
# uint_, int_, float_, complex_
# float128, complex256
# float96
def array(
object: object,
dtype: DtypeLike = ...,
copy: bool = ...,
subok: bool = ...,
ndmin: int = ...,
) -> ndarray: ...
def zeros(
shape: _ShapeLike, dtype: DtypeLike = ..., order: Optional[str] = ...
) -> ndarray: ...
def ones(
shape: _ShapeLike, dtype: DtypeLike = ..., order: Optional[str] = ...
) -> ndarray: ...
def empty(
shape: _ShapeLike, dtype: DtypeLike = ..., order: Optional[str] = ...
) -> ndarray: ...
def zeros_like(
a: ArrayLike,
dtype: DtypeLike = ...,
order: str = ...,
subok: bool = ...,
shape: Optional[Union[int, Sequence[int]]] = ...,
) -> ndarray: ...
def ones_like(
a: ArrayLike,
dtype: DtypeLike = ...,
order: str = ...,
subok: bool = ...,
shape: Optional[_ShapeLike] = ...,
) -> ndarray: ...
def empty_like(
a: ArrayLike,
dtype: DtypeLike = ...,
order: str = ...,
subok: bool = ...,
shape: Optional[_ShapeLike] = ...,
) -> ndarray: ...
def full(
shape: _ShapeLike, fill_value: Any, dtype: DtypeLike = ..., order: str = ...
) -> ndarray: ...
def full_like(
a: ArrayLike,
fill_value: Any,
dtype: DtypeLike = ...,
order: str = ...,
subok: bool = ...,
shape: Optional[_ShapeLike] = ...,
) -> ndarray: ...
def count_nonzero(
a: ArrayLike, axis: Optional[Union[int, Tuple[int], Tuple[int, int]]] = ...
) -> Union[int, ndarray]: ...
def isfortran(a: ndarray) -> bool: ...
def argwhere(a: ArrayLike) -> ndarray: ...
def flatnonzero(a: ArrayLike) -> ndarray: ...
def correlate(a: ArrayLike, v: ArrayLike, mode: str = ...) -> ndarray: ...
def convolve(a: ArrayLike, v: ArrayLike, mode: str = ...) -> ndarray: ...
def outer(a: ArrayLike, b: ArrayLike, out: ndarray = ...) -> ndarray: ...
def tensordot(
a: ArrayLike,
b: ArrayLike,
axes: Union[
int, Tuple[int, int], Tuple[Tuple[int, int], ...], Tuple[List[int, int], ...]
] = ...,
) -> ndarray: ...
def roll(
a: ArrayLike,
shift: Union[int, Tuple[int, ...]],
axis: Optional[Union[int, Tuple[int, ...]]] = ...,
) -> ndarray: ...
def rollaxis(a: ArrayLike, axis: int, start: int = ...) -> ndarray: ...
def moveaxis(
a: ndarray,
source: Union[int, Sequence[int]],
destination: Union[int, Sequence[int]],
) -> ndarray: ...
def cross(
a: ArrayLike,
b: ArrayLike,
axisa: int = ...,
axisb: int = ...,
axisc: int = ...,
axis: Optional[int] = ...,
) -> ndarray: ...
def indices(
dimensions: Sequence[int], dtype: dtype = ..., sparse: bool = ...
) -> Union[ndarray, Tuple[ndarray, ...]]: ...
def fromfunction(function: Callable, shape: Tuple[int, int], **kwargs) -> Any: ...
def isscalar(element: Any) -> bool: ...
def binary_repr(num: int, width: Optional[int] = ...) -> str: ...
def base_repr(number: int, base: int = ..., padding: int = ...) -> str: ...
def identity(n: int, dtype: DtypeLike = ...) -> ndarray: ...
def allclose(
a: ArrayLike,
b: ArrayLike,
rtol: float = ...,
atol: float = ...,
equal_nan: bool = ...,
) -> bool: ...
def isclose(
a: ArrayLike,
b: ArrayLike,
rtol: float = ...,
atol: float = ...,
equal_nan: bool = ...,
) -> Union[bool_, ndarray]: ...
def array_equal(a1: ArrayLike, a2: ArrayLike) -> bool: ...
def array_equiv(a1: ArrayLike, a2: ArrayLike) -> bool: ...
#
# Constants
#
Inf: float
Infinity: float
NAN: float
NINF: float
NZERO: float
NaN: float
PINF: float
PZERO: float
e: float
euler_gamma: float
inf: float
infty: float
nan: float
pi: float
ALLOW_THREADS: int
BUFSIZE: int
CLIP: int
ERR_CALL: int
ERR_DEFAULT: int
ERR_IGNORE: int
ERR_LOG: int
ERR_PRINT: int
ERR_RAISE: int
ERR_WARN: int
FLOATING_POINT_SUPPORT: int
FPE_DIVIDEBYZERO: int
FPE_INVALID: int
FPE_OVERFLOW: int
FPE_UNDERFLOW: int
MAXDIMS: int
MAY_SHARE_BOUNDS: int
MAY_SHARE_EXACT: int
RAISE: int
SHIFT_DIVIDEBYZERO: int
SHIFT_INVALID: int
SHIFT_OVERFLOW: int
SHIFT_UNDERFLOW: int
UFUNC_BUFSIZE_DEFAULT: int
WRAP: int
little_endian: int
tracemalloc_domain: int
class ufunc:
@property
def __name__(self) -> str: ...
def __call__(
self,
*args: ArrayLike,
out: Optional[Union[ndarray, Tuple[ndarray, ...]]] = ...,
where: Optional[ndarray] = ...,
# The list should be a list of tuples of ints, but since we
# don't know the signature it would need to be
# Tuple[int, ...]. But, since List is invariant something like
# e.g. List[Tuple[int, int]] isn't a subtype of
# List[Tuple[int, ...]], so we can't type precisely here.
axes: List[Any] = ...,
axis: int = ...,
keepdims: bool = ...,
# TODO: make this precise when we can use Literal.
casting: str = ...,
# TODO: make this precise when we can use Literal.
order: Optional[str] = ...,
dtype: DtypeLike = ...,
subok: bool = ...,
signature: Union[str, Tuple[str]] = ...,
# In reality this should be a length of list 3 containing an
# int, an int, and a callable, but there's no way to express
# that.
extobj: List[Union[int, Callable]] = ...,
) -> Union[ndarray, generic]: ...
@property
def nin(self) -> int: ...
@property
def nout(self) -> int: ...
@property
def nargs(self) -> int: ...
@property
def ntypes(self) -> int: ...
@property
def types(self) -> List[str]: ...
# Broad return type because it has to encompass things like
#
# >>> np.logical_and.identity is True
# True
# >>> np.add.identity is 0
# True
# >>> np.sin.identity is None
# True
#
# and any user-defined ufuncs.
@property
def identity(self) -> Any: ...
# This is None for ufuncs and a string for gufuncs.
@property
def signature(self) -> Optional[str]: ...
# The next four methods will always exist, but they will just
# raise a ValueError ufuncs with that don't accept two input
# arguments and return one output argument. Because of that we
# can't type them very precisely.
@property
def reduce(self) -> Any: ...
@property
def accumulate(self) -> Any: ...
@property
def reduceat(self) -> Any: ...
@property
def outer(self) -> Any: ...
# Similarly at won't be defined for ufuncs that return multiple
# outputs, so we can't type it very precisely.
@property
def at(self) -> Any: ...
absolute: ufunc
add: ufunc
arccos: ufunc
arccosh: ufunc
arcsin: ufunc
arcsinh: ufunc
arctan2: ufunc
arctan: ufunc
arctanh: ufunc
bitwise_and: ufunc
bitwise_or: ufunc
bitwise_xor: ufunc
cbrt: ufunc
ceil: ufunc
conjugate: ufunc
copysign: ufunc
cos: ufunc
cosh: ufunc
deg2rad: ufunc
degrees: ufunc
divmod: ufunc
equal: ufunc
exp2: ufunc
exp: ufunc
expm1: ufunc
fabs: ufunc
float_power: ufunc
floor: ufunc
floor_divide: ufunc
fmax: ufunc
fmin: ufunc
fmod: ufunc
frexp: ufunc
gcd: ufunc
greater: ufunc
greater_equal: ufunc
heaviside: ufunc
hypot: ufunc
invert: ufunc
isfinite: ufunc
isinf: ufunc
isnan: ufunc
isnat: ufunc
lcm: ufunc
ldexp: ufunc
left_shift: ufunc
less: ufunc
less_equal: ufunc
log10: ufunc
log1p: ufunc
log2: ufunc
log: ufunc
logaddexp2: ufunc
logaddexp: ufunc
logical_and: ufunc
logical_not: ufunc
logical_or: ufunc
logical_xor: ufunc
matmul: ufunc
maximum: ufunc
minimum: ufunc
modf: ufunc
multiply: ufunc
negative: ufunc
nextafter: ufunc
not_equal: ufunc
positive: ufunc
power: ufunc
rad2deg: ufunc
radians: ufunc
reciprocal: ufunc
remainder: ufunc
right_shift: ufunc
rint: ufunc
sign: ufunc
signbit: ufunc
sin: ufunc
sinh: ufunc
spacing: ufunc
sqrt: ufunc
square: ufunc
subtract: ufunc
tan: ufunc
tanh: ufunc
true_divide: ufunc
trunc: ufunc
# Warnings
class ModuleDeprecationWarning(DeprecationWarning): ...
class VisibleDeprecationWarning(UserWarning): ...
class ComplexWarning(RuntimeWarning): ...
class RankWarning(UserWarning): ...
# Errors
class TooHardError(RuntimeError): ...
class AxisError(ValueError, IndexError):
def __init__(
self, axis: int, ndim: Optional[int] = ..., msg_prefix: Optional[str] = ...
) -> None: ...
# Functions from np.core.numerictypes
_DefaultType = TypeVar("_DefaultType")
def maximum_sctype(t: DtypeLike) -> dtype: ...
def issctype(rep: object) -> bool: ...
@overload
def obj2sctype(rep: object) -> Optional[generic]: ...
@overload
def obj2sctype(rep: object, default: None) -> Optional[generic]: ...
@overload
def obj2sctype(
rep: object, default: Type[_DefaultType]
) -> Union[generic, Type[_DefaultType]]: ...
def issubclass_(arg1: object, arg2: Union[object, Tuple[object, ...]]) -> bool: ...
def issubsctype(
arg1: Union[ndarray, DtypeLike], arg2: Union[ndarray, DtypeLike]
) -> bool: ...
def issubdtype(arg1: DtypeLike, arg2: DtypeLike) -> bool: ...
def sctype2char(sctype: object) -> str: ...
def find_common_type(
array_types: Sequence[DtypeLike], scalar_types: Sequence[DtypeLike]
) -> dtype: ...
# Functions from np.core.fromnumeric
_Mode = Literal["raise", "wrap", "clip"]
_Order = Literal["C", "F", "A"]
_PartitionKind = Literal["introselect"]
_SortKind = Literal["quicksort", "mergesort", "heapsort", "stable"]
_Side = Literal["left", "right"]
# Various annotations for scalars
# While dt.datetime and dt.timedelta are not technically part of NumPy,
# they are one of the rare few builtin scalars which serve as valid return types.
# See https://github.com/numpy/numpy-stubs/pull/67#discussion_r412604113.
_ScalarNumpy = Union[generic, dt.datetime, dt.timedelta]
_ScalarBuiltin = Union[str, bytes, dt.date, dt.timedelta, bool, int, float, complex]
_Scalar = Union[_ScalarBuiltin, _ScalarNumpy]
# Integers and booleans can generally be used interchangeably
_ScalarIntOrBool = TypeVar("_ScalarIntOrBool", bound=Union[integer, bool_])
_ScalarGeneric = TypeVar("_ScalarGeneric", bound=generic)
_ScalarGenericDT = TypeVar(
"_ScalarGenericDT", bound=Union[dt.datetime, dt.timedelta, generic]
)
# An array-like object consisting of integers
_Int = Union[int, integer]
_Bool = Union[bool, bool_]
_IntOrBool = Union[_Int, _Bool]
_ArrayLikeIntNested = ArrayLike # TODO: wait for support for recursive types
_ArrayLikeBoolNested = ArrayLike # TODO: wait for support for recursive types
# Integers and booleans can generally be used interchangeably
_ArrayLikeIntOrBool = Union[
_IntOrBool,
ndarray,
Sequence[_IntOrBool],
Sequence[_ArrayLikeIntNested],
Sequence[_ArrayLikeBoolNested],
]
# The signature of take() follows a common theme with its overloads:
# 1. A generic comes in; the same generic comes out
# 2. A scalar comes in; a generic comes out
# 3. An array-like object comes in; some keyword ensures that a generic comes out
# 4. An array-like object comes in; an ndarray or generic comes out
@overload
def take(
a: _ScalarGenericDT,
indices: int,
axis: Optional[int] = ...,
out: Optional[ndarray] = ...,
mode: _Mode = ...,
) -> _ScalarGenericDT: ...
@overload
def take(
a: _Scalar,
indices: int,
axis: Optional[int] = ...,
out: Optional[ndarray] = ...,
mode: _Mode = ...,
) -> _ScalarNumpy: ...
@overload
def take(
a: ArrayLike,
indices: int,
axis: Optional[int] = ...,
out: Optional[ndarray] = ...,
mode: _Mode = ...,
) -> _ScalarNumpy: ...
@overload
def take(
a: ArrayLike,
indices: _ArrayLikeIntOrBool,
axis: Optional[int] = ...,
out: Optional[ndarray] = ...,
mode: _Mode = ...,
) -> Union[_ScalarNumpy, ndarray]: ...
def reshape(a: ArrayLike, newshape: _ShapeLike, order: _Order = ...) -> ndarray: ...
@overload
def choose(
a: _ScalarIntOrBool,
choices: Union[Sequence[ArrayLike], ndarray],
out: Optional[ndarray] = ...,
mode: _Mode = ...,
) -> _ScalarIntOrBool: ...
@overload
def choose(
a: _IntOrBool,
choices: Union[Sequence[ArrayLike], ndarray],
out: Optional[ndarray] = ...,
mode: _Mode = ...,
) -> Union[integer, bool_]: ...
@overload
def choose(
a: _ArrayLikeIntOrBool,
choices: Union[Sequence[ArrayLike], ndarray],
out: Optional[ndarray] = ...,
mode: _Mode = ...,
) -> ndarray: ...
def repeat(
a: ArrayLike, repeats: _ArrayLikeIntOrBool, axis: Optional[int] = ...
) -> ndarray: ...
def put(
a: ndarray, ind: _ArrayLikeIntOrBool, v: ArrayLike, mode: _Mode = ...
) -> None: ...
def swapaxes(
a: Union[Sequence[ArrayLike], ndarray], axis1: int, axis2: int
) -> ndarray: ...
def transpose(
a: ArrayLike, axes: Union[None, Sequence[int], ndarray] = ...
) -> ndarray: ...
def partition(
a: ArrayLike,
kth: _ArrayLikeIntOrBool,
axis: Optional[int] = ...,
kind: _PartitionKind = ...,
order: Union[None, str, Sequence[str]] = ...,
) -> ndarray: ...
@overload
def argpartition(
a: generic,
kth: _ArrayLikeIntOrBool,
axis: Optional[int] = ...,
kind: _PartitionKind = ...,
order: Union[None, str, Sequence[str]] = ...,
) -> integer: ...
@overload
def argpartition(
a: _ScalarBuiltin,
kth: _ArrayLikeIntOrBool,
axis: Optional[int] = ...,
kind: _PartitionKind = ...,
order: Union[None, str, Sequence[str]] = ...,
) -> ndarray: ...
@overload
def argpartition(
a: ArrayLike,
kth: _ArrayLikeIntOrBool,
axis: Optional[int] = ...,
kind: _PartitionKind = ...,
order: Union[None, str, Sequence[str]] = ...,
) -> ndarray: ...
def sort(
a: Union[Sequence[ArrayLike], ndarray],
axis: Optional[int] = ...,
kind: Optional[_SortKind] = ...,
order: Union[None, str, Sequence[str]] = ...,
) -> ndarray: ...
def argsort(
a: Union[Sequence[ArrayLike], ndarray],
axis: Optional[int] = ...,
kind: Optional[_SortKind] = ...,
order: Union[None, str, Sequence[str]] = ...,
) -> ndarray: ...
@overload
def argmax(
a: Union[Sequence[ArrayLike], ndarray],
axis: None = ...,
out: Optional[ndarray] = ...,
) -> integer: ...
@overload
def argmax(
a: Union[Sequence[ArrayLike], ndarray],
axis: int = ...,
out: Optional[ndarray] = ...,
) -> Union[integer, ndarray]: ...
@overload
def argmin(
a: Union[Sequence[ArrayLike], ndarray],
axis: None = ...,
out: Optional[ndarray] = ...,
) -> integer: ...
@overload
def argmin(
a: Union[Sequence[ArrayLike], ndarray],
axis: int = ...,
out: Optional[ndarray] = ...,
) -> Union[integer, ndarray]: ...
@overload
def searchsorted(
a: Union[Sequence[ArrayLike], ndarray],
v: _Scalar,
side: _Side = ...,
sorter: Union[None, Sequence[_IntOrBool], ndarray] = ..., # 1D int array
) -> integer: ...
@overload
def searchsorted(
a: Union[Sequence[ArrayLike], ndarray],
v: ArrayLike,
side: _Side = ...,
sorter: Union[None, Sequence[_IntOrBool], ndarray] = ..., # 1D int array
) -> ndarray: ...
def resize(a: ArrayLike, new_shape: _ShapeLike) -> ndarray: ...
@overload
def squeeze(a: _ScalarGeneric, axis: Optional[_ShapeLike] = ...) -> _ScalarGeneric: ...
@overload
def squeeze(a: ArrayLike, axis: Optional[_ShapeLike] = ...) -> ndarray: ...
def diagonal(
a: Union[Sequence[Sequence[ArrayLike]], ndarray], # >= 2D array
offset: int = ...,
axis1: int = ...,
axis2: int = ...,
) -> ndarray: ...
def trace(
a: Union[Sequence[Sequence[ArrayLike]], ndarray], # >= 2D array
offset: int = ...,
axis1: int = ...,
axis2: int = ...,
dtype: DtypeLike = ...,
out: Optional[ndarray] = ...,
) -> Union[number, ndarray]: ...
def ravel(a: ArrayLike, order: _Order = ...) -> ndarray: ...
def nonzero(a: ArrayLike) -> Tuple[ndarray, ...]: ...
def shape(a: ArrayLike) -> _Shape: ...
def compress(
condition: Union[Sequence[_Bool], ndarray], # 1D bool array
a: ArrayLike,
axis: Optional[int] = ...,
out: Optional[ndarray] = ...,
) -> ndarray: ...
| 0 |
public_repos/numpy-stubs | public_repos/numpy-stubs/numpy-stubs/typing.pyi | import sys
from typing import Any, Dict, List, overload, Sequence, Text, Tuple, Union
from numpy import dtype, ndarray
if sys.version_info >= (3, 8):
from typing import Protocol
else:
from typing_extensions import Protocol
_Shape = Tuple[int, ...]
# Anything that can be coerced to a shape tuple
_ShapeLike = Union[int, Sequence[int]]
_DtypeLikeNested = Any # TODO: wait for support for recursive types
# Anything that can be coerced into numpy.dtype.
# Reference: https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html
DtypeLike = Union[
dtype,
# default data type (float64)
None,
# array-scalar types and generic types
type, # TODO: enumerate these when we add type hints for numpy scalars
# TODO: add a protocol for anything with a dtype attribute
# character codes, type strings or comma-separated fields, e.g., 'float64'
str,
# (flexible_dtype, itemsize)
Tuple[_DtypeLikeNested, int],
# (fixed_dtype, shape)
Tuple[_DtypeLikeNested, _ShapeLike],
# [(field_name, field_dtype, field_shape), ...]
#
# The type here is quite broad because NumPy accepts quite a wide
# range of inputs inside the list; see the tests for some
# examples.
List[Any],
# {'names': ..., 'formats': ..., 'offsets': ..., 'titles': ...,
# 'itemsize': ...}
# TODO: use TypedDict when/if it's officially supported
Dict[
str,
Union[
Sequence[str], # names
Sequence[_DtypeLikeNested], # formats
Sequence[int], # offsets
Sequence[Union[bytes, Text, None]], # titles
int, # itemsize
],
],
# {'field1': ..., 'field2': ..., ...}
Dict[str, Tuple[_DtypeLikeNested, int]],
# (base_dtype, new_dtype)
Tuple[_DtypeLikeNested, _DtypeLikeNested],
]
class _SupportsArray(Protocol):
@overload
def __array__(self, __dtype: DtypeLike = ...) -> ndarray: ...
@overload
def __array__(self, dtype: DtypeLike = ...) -> ndarray: ...
ArrayLike = Union[bool, int, float, complex, _SupportsArray, Sequence]
| 0 |
public_repos/numpy-stubs/numpy-stubs | public_repos/numpy-stubs/numpy-stubs/core/_internal.pyi | from typing import Any
# TODO: add better annotations when ctypes is stubbed out
class _ctypes:
@property
def data(self) -> int: ...
@property
def shape(self) -> Any: ...
@property
def strides(self) -> Any: ...
def data_as(self, obj: Any) -> Any: ...
def shape_as(self, obj: Any) -> Any: ...
def strides_as(self, obj: Any) -> Any: ...
def get_data(self) -> int: ...
def get_shape(self) -> Any: ...
def get_strides(self) -> Any: ...
def get_as_parameter(self) -> Any: ...
| 0 |
public_repos/numpy-stubs | public_repos/numpy-stubs/tests/test_stubs.py | import importlib.util
import itertools
import os
import re
from collections import defaultdict
import pytest
from mypy import api
TESTS_DIR = os.path.dirname(__file__)
PASS_DIR = os.path.join(TESTS_DIR, "pass")
FAIL_DIR = os.path.join(TESTS_DIR, "fail")
REVEAL_DIR = os.path.join(TESTS_DIR, "reveal")
def get_test_cases(directory):
for root, _, files in os.walk(directory):
for fname in files:
if os.path.splitext(fname)[-1] == ".py":
fullpath = os.path.join(root, fname)
# Use relative path for nice py.test name
relpath = os.path.relpath(fullpath, start=directory)
yield pytest.param(
fullpath,
# Manually specify a name for the test
id=relpath,
)
@pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
def test_success(path):
stdout, stderr, exitcode = api.run([path])
assert exitcode == 0, stdout
assert re.match(r"Success: no issues found in \d+ source files?", stdout.strip())
@pytest.mark.parametrize("path", get_test_cases(FAIL_DIR))
def test_fail(path):
stdout, stderr, exitcode = api.run([path])
assert exitcode != 0
with open(path) as fin:
lines = fin.readlines()
errors = defaultdict(lambda: "")
error_lines = stdout.rstrip("\n").split("\n")
assert re.match(
r"Found \d+ errors? in \d+ files? \(checked \d+ source files?\)",
error_lines[-1].strip(),
)
for error_line in error_lines[:-1]:
error_line = error_line.strip()
if not error_line:
continue
lineno = int(error_line.split(":")[1])
errors[lineno] += error_line
for i, line in enumerate(lines):
lineno = i + 1
if " E:" not in line and lineno not in errors:
continue
target_line = lines[lineno - 1]
if "# E:" in target_line:
marker = target_line.split("# E:")[-1].strip()
assert lineno in errors, f'Extra error "{marker}"'
assert marker in errors[lineno]
else:
pytest.fail(f"Error {repr(errors[lineno])} not found")
@pytest.mark.parametrize("path", get_test_cases(REVEAL_DIR))
def test_reveal(path):
stdout, stderr, exitcode = api.run([path])
with open(path) as fin:
lines = fin.readlines()
for error_line in stdout.split("\n"):
error_line = error_line.strip()
if not error_line:
continue
lineno = int(error_line.split(":")[1])
assert "Revealed type is" in error_line
marker = lines[lineno - 1].split("# E:")[-1].strip()
assert marker in error_line
@pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
def test_code_runs(path):
path_without_extension, _ = os.path.splitext(path)
dirname, filename = path.split(os.sep)[-2:]
spec = importlib.util.spec_from_file_location(f"{dirname}.{filename}", path)
test_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(test_module)
| 0 |
public_repos/numpy-stubs | public_repos/numpy-stubs/tests/README.md | Testing
=======
There are three main directories of tests right now:
- `pass/` which contain Python files that must pass `mypy` checking with
no type errors
- `fail/` which contain Python files that must *fail* `mypy` checking
with the annotated errors
- `reveal/` which contain Python files that must output the correct
types with `reveal_type`
`fail` and `reveal` are annotated with comments that specify what error
`mypy` threw and what type should be revealed respectively. The format
looks like:
```python
bad_function # E: <error message>
reveal_type(x) # E: <type name>
```
Right now, the error messages and types are must be **contained within
corresponding mypy message**.
## Running the tests
To setup your test environment, cd into the root of the repo and run:
```
pip install -r test-requirements.txt
```
To run the tests, do
```
python runtests.py
```
from the repo root. To run `mypy` on a specific file (which can be
useful for debugging), you can also run:
```
pip install . # Make sure stubs are installed; runtests does this for you
mypy <file_path>
```
Note that it is assumed that all of these commands target the same
underlying Python interpreter. To ensure you're using the intended version of
Python you can use `python -m` versions of these commands instead:
```
python -m pip install -r test-requirements.txt
python -m pip install .
python -m mypy <file_path>
```
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/fail/numerictypes.py | import numpy as np
# Techincally this works, but probably shouldn't. See
#
# https://github.com/numpy/numpy/issues/16366
#
np.maximum_sctype(1) # E: incompatible type "int"
np.issubsctype(1, np.int64) # E: incompatible type "int"
np.issubdtype(1, np.int64) # E: incompatible type "int"
np.find_common_type(np.int64, np.int64) # E: incompatible type "Type[int64]"
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/fail/scalars.py | import numpy as np
# Construction
np.float32(3j) # E: incompatible type
# Technically the following examples are valid NumPy code. But they
# are not considered a best practice, and people who wish to use the
# stubs should instead do
#
# np.array([1.0, 0.0, 0.0], dtype=np.float32)
# np.array([], dtype=np.complex64)
#
# See e.g. the discussion on the mailing list
#
# https://mail.python.org/pipermail/numpy-discussion/2020-April/080566.html
#
# and the issue
#
# https://github.com/numpy/numpy-stubs/issues/41
#
# for more context.
np.float32([1.0, 0.0, 0.0]) # E: incompatible type
np.complex64([]) # E: incompatible type
np.complex64(1, 2) # E: Too many arguments
# TODO: protocols (can't check for non-existent protocols w/ __getattr__)
np.datetime64(0) # E: non-matching overload
dt_64 = np.datetime64(0, "D")
td_64 = np.timedelta64(1, "h")
dt_64 + dt_64 # E: Unsupported operand types
td_64 - dt_64 # E: Unsupported operand types
td_64 / dt_64 # E: No overload
td_64 % 1 # E: Unsupported operand types
td_64 % dt_64 # E: Unsupported operand types
class A:
def __float__(self):
return 1.0
np.int8(A()) # E: incompatible type
np.int16(A()) # E: incompatible type
np.int32(A()) # E: incompatible type
np.int64(A()) # E: incompatible type
np.uint8(A()) # E: incompatible type
np.uint16(A()) # E: incompatible type
np.uint32(A()) # E: incompatible type
np.uint64(A()) # E: incompatible type
np.void("test") # E: incompatible type
np.generic(1) # E: Cannot instantiate abstract class
np.number(1) # E: Cannot instantiate abstract class
np.integer(1) # E: Cannot instantiate abstract class
np.signedinteger(1) # E: Cannot instantiate abstract class
np.unsignedinteger(1) # E: Cannot instantiate abstract class
np.inexact(1) # E: Cannot instantiate abstract class
np.floating(1) # E: Cannot instantiate abstract class
np.complexfloating(1) # E: Cannot instantiate abstract class
np.character("test") # E: Cannot instantiate abstract class
np.flexible(b"test") # E: Cannot instantiate abstract class
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/fail/simple.py | """Simple expression that should fail with mypy."""
import numpy as np
# Array creation routines checks
np.zeros("test") # E: incompatible type
np.zeros() # E: Too few arguments
np.ones("test") # E: incompatible type
np.ones() # E: Too few arguments
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/fail/warnings_and_errors.py | import numpy as np
np.AxisError(1.0) # E: Argument 1 to "AxisError" has incompatible type
np.AxisError(1, ndim=2.0) # E: Argument "ndim" to "AxisError" has incompatible type
np.AxisError(
2, msg_prefix=404 # E: Argument "msg_prefix" to "AxisError" has incompatible type
)
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/fail/ufuncs.py | import numpy as np
np.sin.nin + "foo" # E: Unsupported operand types
np.sin(1, foo="bar") # E: Unexpected keyword argument
np.sin(1, extobj=["foo", "foo", "foo"]) # E: incompatible type
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/fail/fromnumeric.py | """Tests for :mod:`numpy.core.fromnumeric`."""
import numpy as np
A = np.array(True, ndmin=2, dtype=bool)
A.setflags(write=False)
a = np.bool_(True)
np.take(a, None) # E: No overload variant of "take" matches argument type
np.take(a, axis=1.0) # E: No overload variant of "take" matches argument type
np.take(A, out=1) # E: No overload variant of "take" matches argument type
np.take(A, mode="bob") # E: No overload variant of "take" matches argument type
np.reshape(a, None) # E: Argument 2 to "reshape" has incompatible type
np.reshape(A, 1, order="bob") # E: Argument "order" to "reshape" has incompatible type
np.choose(a, None) # E: No overload variant of "choose" matches argument type
np.choose(a, out=1.0) # E: No overload variant of "choose" matches argument type
np.choose(A, mode="bob") # E: No overload variant of "choose" matches argument type
np.repeat(a, None) # E: Argument 2 to "repeat" has incompatible type
np.repeat(A, 1, axis=1.0) # E: Argument "axis" to "repeat" has incompatible type
np.swapaxes(a, 0, 0) # E: Argument 1 to "swapaxes" has incompatible type
np.swapaxes(A, None, 1) # E: Argument 2 to "swapaxes" has incompatible type
np.swapaxes(A, 1, [0]) # E: Argument 3 to "swapaxes" has incompatible type
np.transpose(a, axes=1) # E: Argument "axes" to "transpose" has incompatible type
np.transpose(A, axes=1.0) # E: Argument "axes" to "transpose" has incompatible type
np.partition(a, None) # E: Argument 2 to "partition" has incompatible type
np.partition(
a, 0, axis="bob" # E: Argument "axis" to "partition" has incompatible type
)
np.partition(
A, 0, kind="bob" # E: Argument "kind" to "partition" has incompatible type
)
np.partition(
A, 0, order=range(5) # E: Argument "order" to "partition" has incompatible type
)
np.argpartition( # E: No overload variant of "argpartition" matches argument type
a, None
)
np.argpartition( # E: No overload variant of "argpartition" matches argument type
a, 0, axis="bob"
)
np.argpartition( # E: No overload variant of "argpartition" matches argument type
A, 0, kind="bob"
)
np.argpartition(
A, 0, order=range(5) # E: Argument "order" to "argpartition" has incompatible type
)
np.sort(a) # E: Argument 1 to "sort" has incompatible type
np.sort(A, axis="bob") # E: Argument "axis" to "sort" has incompatible type
np.sort(A, kind="bob") # E: Argument "kind" to "sort" has incompatible type
np.sort(A, order=range(5)) # E: Argument "order" to "sort" has incompatible type
np.argsort(a) # E: Argument 1 to "argsort" has incompatible type
np.argsort(A, axis="bob") # E: Argument "axis" to "argsort" has incompatible type
np.argsort(A, kind="bob") # E: Argument "kind" to "argsort" has incompatible type
np.argsort(A, order=range(5)) # E: Argument "order" to "argsort" has incompatible type
np.argmax(a) # E: No overload variant of "argmax" matches argument type
np.argmax(A, axis="bob") # E: No overload variant of "argmax" matches argument type
np.argmax(A, kind="bob") # E: No overload variant of "argmax" matches argument type
np.argmin(a) # E: No overload variant of "argmin" matches argument type
np.argmin(A, axis="bob") # E: No overload variant of "argmin" matches argument type
np.argmin(A, kind="bob") # E: No overload variant of "argmin" matches argument type
np.searchsorted(a, 0) # E: No overload variant of "searchsorted" matches argument type
np.searchsorted( # E: No overload variant of "searchsorted" matches argument type
A[0], 0, side="bob"
)
np.searchsorted( # E: No overload variant of "searchsorted" matches argument type
A[0], 0, sorter=1.0
)
np.resize(A, 1.0) # E: Argument 2 to "resize" has incompatible type
np.squeeze(A, 1.0) # E: No overload variant of "squeeze" matches argument type
np.diagonal(a) # E: Argument 1 to "diagonal" has incompatible type
np.diagonal(A, offset=None) # E: Argument "offset" to "diagonal" has incompatible type
np.diagonal(A, axis1="bob") # E: Argument "axis1" to "diagonal" has incompatible type
np.diagonal(A, axis2=[]) # E: Argument "axis2" to "diagonal" has incompatible type
np.trace(a) # E: Argument 1 to "trace" has incompatible type
np.trace(A, offset=None) # E: Argument "offset" to "trace" has incompatible type
np.trace(A, axis1="bob") # E: Argument "axis1" to "trace" has incompatible type
np.trace(A, axis2=[]) # E: Argument "axis2" to "trace" has incompatible type
np.ravel(a, order="bob") # E: Argument "order" to "ravel" has incompatible type
np.compress(True, A) # E: Argument 1 to "compress" has incompatible type
np.compress(
[True], A, axis=1.0 # E: Argument "axis" to "compress" has incompatible type
)
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/fail/ndarray.py | import numpy as np
# Ban setting dtype since mutating the type of the array in place
# makes having ndarray be generic over dtype impossible. Generally
# users should use `ndarray.view` in this situation anyway. See
#
# https://github.com/numpy/numpy-stubs/issues/7
#
# for more context.
float_array = np.array([1.0])
float_array.dtype = np.bool_ # E: Property "dtype" defined in "ndarray" is read-only
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/fail/array_like.py | from typing import Any, TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from numpy.typing import ArrayLike
else:
ArrayLike = Any
class A:
pass
x1: ArrayLike = (i for i in range(10)) # E: Incompatible types in assignment
x2: ArrayLike = A() # E: Incompatible types in assignment
x3: ArrayLike = {1: "foo", 2: "bar"} # E: Incompatible types in assignment
scalar = np.int64(1)
scalar.__array__(dtype=np.float64) # E: Unexpected keyword argument
array = np.array([1])
array.__array__(dtype=np.float64) # E: Unexpected keyword argument
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/pass/numerictypes.py | import numpy as np
np.maximum_sctype("S8")
np.maximum_sctype(object)
np.issctype(object)
np.issctype("S8")
np.obj2sctype(list)
np.obj2sctype(list, default=None)
np.obj2sctype(list, default=np.string_)
np.issubclass_(np.int32, int)
np.issubclass_(np.float64, float)
np.issubclass_(np.float64, (int, float))
np.issubsctype("int64", int)
np.issubsctype(np.array([1]), np.array([1]))
np.issubdtype("S1", np.string_)
np.issubdtype(np.float64, np.float32)
np.sctype2char("S1")
np.sctype2char(list)
np.find_common_type([], [np.int64, np.float32, complex])
np.find_common_type((), (np.int64, np.float32, complex))
np.find_common_type([np.int64, np.float32], [])
np.find_common_type([np.float32], [np.int64, np.float64])
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/pass/scalars.py | import numpy as np
# Construction
class C:
def __complex__(self):
return 3j
class B:
def __int__(self):
return 4
class A:
def __float__(self):
return 4.0
np.complex64(3j)
np.complex64(C())
np.complex128(3j)
np.complex128(C())
np.int8(4)
np.int16(3.4)
np.int32(4)
np.int64(-1)
np.uint8(B())
np.uint32()
np.float16(A())
np.float32(16)
np.float64(3.0)
np.bytes_(b"hello")
np.str_("hello")
# Protocols
float(np.int8(4))
int(np.int16(5))
np.int8(np.float32(6))
# TODO(alan): test after https://github.com/python/typeshed/pull/2004
# complex(np.int32(8))
abs(np.int8(4))
# Array-ish semantics
np.int8().real
np.int16().imag
np.int32().data
np.int64().flags
np.uint8().itemsize * 2
np.uint16().ndim + 1
np.uint32().strides
np.uint64().shape
# Time structures
np.datetime64()
np.datetime64(0, "D")
np.datetime64("2019")
np.datetime64("2019", "D")
np.timedelta64()
np.timedelta64(0)
np.timedelta64(0, "D")
dt_64 = np.datetime64(0, "D")
td_64 = np.timedelta64(1, "h")
dt_64 + td_64
dt_64 - dt_64
dt_64 - td_64
td_64 + td_64
td_64 - td_64
td_64 / 1.0
td_64 / td_64
td_64 % td_64
np.void(1)
np.void(np.int64(1))
np.void(True)
np.void(np.bool_(True))
np.void(b"test")
np.void(np.bytes_("test"))
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/pass/simple.py | """Simple expression that should pass with mypy."""
import operator
import numpy as np
from typing import Iterable # noqa: F401
# Basic checks
array = np.array([1, 2])
def ndarray_func(x):
# type: (np.ndarray) -> np.ndarray
return x
ndarray_func(np.array([1, 2]))
array == 1
array.dtype == float
# Array creation routines checks
ndarray_func(np.zeros([1, 2]))
ndarray_func(np.ones([1, 2]))
ndarray_func(np.empty([1, 2]))
ndarray_func(np.zeros_like(array))
ndarray_func(np.ones_like(array))
ndarray_func(np.empty_like(array))
# Dtype construction
np.dtype(float)
np.dtype(np.float64)
np.dtype(None)
np.dtype("float64")
np.dtype(np.dtype(float))
np.dtype(("U", 10))
np.dtype((np.int32, (2, 2)))
# Define the arguments on the previous line to prevent bidirectional
# type inference in mypy from broadening the types.
two_tuples_dtype = [("R", "u1"), ("G", "u1"), ("B", "u1")]
np.dtype(two_tuples_dtype)
three_tuples_dtype = [("R", "u1", 1)]
np.dtype(three_tuples_dtype)
mixed_tuples_dtype = [("R", "u1"), ("G", np.unicode_, 1)]
np.dtype(mixed_tuples_dtype)
shape_tuple_dtype = [("R", "u1", (2, 2))]
np.dtype(shape_tuple_dtype)
shape_like_dtype = [("R", "u1", (2, 2)), ("G", np.unicode_, 1)]
np.dtype(shape_like_dtype)
object_dtype = [("field1", object)]
np.dtype(object_dtype)
np.dtype({"col1": ("U10", 0), "col2": ("float32", 10)})
np.dtype((np.int32, {"real": (np.int16, 0), "imag": (np.int16, 2)}))
np.dtype((np.int32, (np.int8, 4)))
# Dtype comparision
np.dtype(float) == float
np.dtype(float) != np.float64
np.dtype(float) < None
np.dtype(float) <= "float64"
np.dtype(float) > np.dtype(float)
np.dtype(float) >= np.dtype(("U", 10))
# Iteration and indexing
def iterable_func(x):
# type: (Iterable) -> Iterable
return x
iterable_func(array)
[element for element in array]
iter(array)
zip(array, array)
array[1]
array[:]
array[...]
array[:] = 0
array_2d = np.ones((3, 3))
array_2d[:2, :2]
array_2d[..., 0]
array_2d[:2, :2] = 0
# Other special methods
len(array)
str(array)
array_scalar = np.array(1)
int(array_scalar)
float(array_scalar)
# currently does not work due to https://github.com/python/typeshed/issues/1904
# complex(array_scalar)
bytes(array_scalar)
operator.index(array_scalar)
bool(array_scalar)
# comparisons
array < 1
array <= 1
array == 1
array != 1
array > 1
array >= 1
1 < array
1 <= array
1 == array
1 != array
1 > array
1 >= array
# binary arithmetic
array + 1
1 + array
array += 1
array - 1
1 - array
array -= 1
array * 1
1 * array
array *= 1
array / 1
1 / array
float_array = np.array([1.0, 2.0])
float_array /= 1
array // 1
1 // array
array //= 1
array % 1
1 % array
array %= 1
divmod(array, 1)
divmod(1, array)
array ** 1
1 ** array
array **= 1
array << 1
1 << array
array <<= 1
array >> 1
1 >> array
array >>= 1
array & 1
1 & array
array &= 1
array ^ 1
1 ^ array
array ^= 1
array | 1
1 | array
array |= 1
# unary arithmetic
-array
+array
abs(array)
~array
# Other methods
np.array([1, 2]).transpose()
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/pass/warnings_and_errors.py | import numpy as np
np.AxisError(1)
np.AxisError(1, ndim=2)
np.AxisError(1, ndim=None)
np.AxisError(1, ndim=2, msg_prefix="error")
np.AxisError(1, ndim=2, msg_prefix=None)
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/pass/ufuncs.py | import numpy as np
np.sin(1)
np.sin([1, 2, 3])
np.sin(1, out=np.empty(1))
np.matmul(np.ones((2, 2, 2)), np.ones((2, 2, 2)), axes=[(0, 1), (0, 1), (0, 1)])
np.sin(1, signature="D")
np.sin(1, extobj=[16, 1, lambda: None])
np.sin(1) + np.sin(1)
np.sin.types[0]
np.sin.__name__
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/pass/fromnumeric.py | """Tests for :mod:`numpy.core.fromnumeric`."""
import numpy as np
A = np.array(True, ndmin=2, dtype=bool)
B = np.array(1.0, ndmin=2, dtype=np.float32)
A.setflags(write=False)
B.setflags(write=False)
a = np.bool_(True)
b = np.float32(1.0)
c = 1.0
np.take(a, 0)
np.take(b, 0)
np.take(c, 0)
np.take(A, 0)
np.take(B, 0)
np.take(A, [0])
np.take(B, [0])
np.reshape(a, 1)
np.reshape(b, 1)
np.reshape(c, 1)
np.reshape(A, 1)
np.reshape(B, 1)
np.choose(a, [True, True])
np.choose(A, [1.0, 1.0])
np.repeat(a, 1)
np.repeat(b, 1)
np.repeat(c, 1)
np.repeat(A, 1)
np.repeat(B, 1)
np.swapaxes(A, 0, 0)
np.swapaxes(B, 0, 0)
np.transpose(a)
np.transpose(b)
np.transpose(c)
np.transpose(A)
np.transpose(B)
np.partition(a, 0, axis=None)
np.partition(b, 0, axis=None)
np.partition(c, 0, axis=None)
np.partition(A, 0)
np.partition(B, 0)
np.argpartition(a, 0)
np.argpartition(b, 0)
np.argpartition(c, 0)
np.argpartition(A, 0)
np.argpartition(B, 0)
np.sort(A, 0)
np.sort(B, 0)
np.argsort(A, 0)
np.argsort(B, 0)
np.argmax(A)
np.argmax(B)
np.argmax(A, axis=0)
np.argmax(B, axis=0)
np.argmin(A)
np.argmin(B)
np.argmin(A, axis=0)
np.argmin(B, axis=0)
np.searchsorted(A[0], 0)
np.searchsorted(B[0], 0)
np.searchsorted(A[0], [0])
np.searchsorted(B[0], [0])
np.resize(a, (5, 5))
np.resize(b, (5, 5))
np.resize(c, (5, 5))
np.resize(A, (5, 5))
np.resize(B, (5, 5))
np.squeeze(a)
np.squeeze(b)
np.squeeze(c)
np.squeeze(A)
np.squeeze(B)
np.diagonal(A)
np.diagonal(B)
np.trace(A)
np.trace(B)
np.ravel(a)
np.ravel(b)
np.ravel(c)
np.ravel(A)
np.ravel(B)
np.nonzero(a)
np.nonzero(b)
np.nonzero(c)
np.nonzero(A)
np.nonzero(B)
np.shape(a)
np.shape(b)
np.shape(c)
np.shape(A)
np.shape(B)
np.compress([True], a)
np.compress([True], b)
np.compress([True], c)
np.compress([True], A)
np.compress([True], B)
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/pass/simple_py3.py | import numpy as np
array = np.array([1, 2])
# The @ operator is not in python 2
array @ array
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/pass/ndarray_shape_manipulation.py | import numpy as np
nd1 = np.array([[1, 2], [3, 4]])
# reshape
nd1.reshape(4)
nd1.reshape(2, 2)
nd1.reshape((2, 2))
nd1.reshape((2, 2), order="C")
nd1.reshape(4, order="C")
# resize
nd1.resize()
nd1.resize(4)
nd1.resize(2, 2)
nd1.resize((2, 2))
nd1.resize((2, 2), refcheck=True)
nd1.resize(4, refcheck=True)
nd2 = np.array([[1, 2], [3, 4]])
# transpose
nd2.transpose()
nd2.transpose(1, 0)
nd2.transpose((1, 0))
# swapaxes
nd2.swapaxes(0, 1)
# flatten
nd2.flatten()
nd2.flatten("C")
# ravel
nd2.ravel()
nd2.ravel("C")
# squeeze
nd2.squeeze()
nd3 = np.array([[1, 2]])
nd3.squeeze(0)
nd4 = np.array([[[1, 2]]])
nd4.squeeze((0, 1))
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/pass/ndarray_conversion.py | import os
import tempfile
import numpy as np
nd = np.array([[1, 2], [3, 4]])
scalar_array = np.array(1)
# item
scalar_array.item()
nd.item(1)
nd.item(0, 1)
nd.item((0, 1))
# tolist is pretty simple
# itemset
scalar_array.itemset(3)
nd.itemset(3, 0)
nd.itemset((0, 0), 3)
# tostring/tobytes
nd.tostring()
nd.tostring("C")
nd.tostring(None)
nd.tobytes()
nd.tobytes("C")
nd.tobytes(None)
# tofile
if os.name != "nt":
with tempfile.NamedTemporaryFile(suffix=".txt") as tmp:
nd.tofile(tmp.name)
nd.tofile(tmp.name, "")
nd.tofile(tmp.name, sep="")
nd.tofile(tmp.name, "", "%s")
nd.tofile(tmp.name, format="%s")
nd.tofile(tmp)
# dump is pretty simple
# dumps is pretty simple
# astype
nd.astype("float")
nd.astype(float)
nd.astype(float, "K")
nd.astype(float, order="K")
nd.astype(float, "K", "unsafe")
nd.astype(float, casting="unsafe")
nd.astype(float, "K", "unsafe", True)
nd.astype(float, subok=True)
nd.astype(float, "K", "unsafe", True, True)
nd.astype(float, copy=True)
# byteswap
nd.byteswap()
nd.byteswap(True)
# copy
nd.copy()
nd.copy("C")
# view
nd.view()
nd.view(np.int64)
nd.view(dtype=np.int64)
nd.view(np.int64, np.matrix)
nd.view(type=np.matrix)
# getfield
complex_array = np.array([[1 + 1j, 0], [0, 1 - 1j]], dtype=np.complex128)
complex_array.getfield("float")
complex_array.getfield(float)
complex_array.getfield("float", 8)
complex_array.getfield(float, offset=8)
# setflags
nd.setflags()
nd.setflags(True)
nd.setflags(write=True)
nd.setflags(True, True)
nd.setflags(write=True, align=True)
nd.setflags(True, True, False)
nd.setflags(write=True, align=True, uic=False)
# fill is pretty simple
| 0 |
public_repos/numpy-stubs/tests | public_repos/numpy-stubs/tests/pass/array_like.py | from typing import Any, List, Optional, TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from numpy.typing import ArrayLike, DtypeLike, _SupportsArray
else:
ArrayLike = Any
DtypeLike = Any
_SupportsArray = Any
x1: ArrayLike = True
x2: ArrayLike = 5
x3: ArrayLike = 1.0
x4: ArrayLike = 1 + 1j
x5: ArrayLike = np.int8(1)
x6: ArrayLike = np.float64(1)
x7: ArrayLike = np.complex128(1)
x8: ArrayLike = np.array([1, 2, 3])
x9: ArrayLike = [1, 2, 3]
x10: ArrayLike = (1, 2, 3)
x11: ArrayLike = "foo"
class A:
def __array__(self, dtype: DtypeLike = None) -> np.ndarray:
return np.array([1, 2, 3])
x12: ArrayLike = A()
scalar: _SupportsArray = np.int64(1)
scalar.__array__(np.float64)
array: _SupportsArray = np.array(1)
array.__array__(np.float64)
a: _SupportsArray = A()
a.__array__(np.int64)
a.__array__(dtype=np.int64)
# Escape hatch for when you mean to make something like an object
# array.
object_array_scalar: Any = (i for i in range(10))
np.array(object_array_scalar)
| 0 |