question_id
int64
59.5M
79.4M
creation_date
stringlengths
8
10
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
75,932,638
2023-4-4
https://stackoverflow.com/questions/75932638/finding-non-duplicate-numbers-and-duplicate-numbers-from-a-list
I'm new to coding and struggling a bit with this one. Can anyone show me how to write the pseudocode for a program that finds the non-duplicate numbers and duplicate numbers (as simply as possible.) thanks! ** input:** 56 75 1 46 100 97 75 46 46 Output: Non-duplicates: 56 1 100 97 Duplicates: 75 46 I tried : list = [56, 75, 1, 46, 100, 97, 75, 46, 46] dupes = [] unique = [] for x in list: if x not in dupes: dupes.append(x) else: unique.append(x) print(dupes) print(unique) However, I beleive there might be a more elegant solution (that matches the output.) The exercise I took this from was about sets. I'm not sure if that's too relevant! Thanks
Use count() method: lst = [56, 75, 1, 46, 100, 97, 75, 46, 46] dupes = [] unique = [] for x in lst: if lst.count(x) == 1: unique.append(x) elif x not in dupes: dupes.append(x) print('Non-duplicates:', *unique, sep='\n',) print() print('Duplicates:', *dupes, sep='\n')
3
0
75,933,279
2023-4-4
https://stackoverflow.com/questions/75933279/how-to-improve-pytroch-model
Good evening, I have 4 classes with black and white images each class has 3000 images with a test of 600 images so how to improve this model and that's my full code: data_transform = transforms.Compose([ transforms.Grayscale(num_output_channels=1), transforms.Resize(size=(150, 150)), transforms.ToTensor(), transforms.Normalize(mean=[0.5], std=[0.5]), ]) Loading Images using ImageFolder train_data = datasets.ImageFolder(root=train_dir, transform=data_transform, # Transform the data target_transform=None) # Transform the Label test_data = datasets.ImageFolder(root=test_dir, transform=data_transform, # Transform the data target_transform=None) # Transform the Label train_data, test_data Turn the data to DataLoader BATCH_SIZE = 8 train_dataloader = DataLoader( dataset= train_data, batch_size=BATCH_SIZE, # How many images our model can see at the time num_workers=8, # Number of CPU Cores shuffle=True ) test_dataloader = DataLoader( dataset= test_data, batch_size=BATCH_SIZE, # How many images our model can see at the time num_workers=8, # Number of CPU Cores shuffle=False ) Create class class TingVGG(nn.Module): def __init__(self, input_shape: int, hidden_units: int, output_shape: int) -> None: super().__init__() self.conv_block1 = nn.Sequential( nn.Conv2d(in_channels=input_shape,out_channels=hidden_units,kernel_size=3,stride=1,padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(in_channels=hidden_units, out_channels=hidden_units, kernel_size=3,stride=1,padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(in_channels=hidden_units, out_channels=hidden_units, kernel_size=3,stride=1,padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2) ) self.dropout = nn.Dropout(0.4) self.classifier = nn.Sequential(nn.Flatten(), nn.Linear(in_features=hidden_units*18*18 ,out_features=output_shape)) def forward(self, x: torch.Tensor): x = self.conv_block1(x) x = self.dropout(x) x = self.classifier(x) return x Train the Model # Set random seed torch.manual_seed(42) torch.cuda.manual_seed(42) # Set number of epoches NUM_EPOCHS = 10 # Create and initialize of TinyVGG model_0 = TingVGG(input_shape=1, # Number of channels in the input image (c, h, w) -> 3 hidden_units=128, output_shape=len(train_data.classes)).to(device) # Setup the loss function and optimizer loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(params= model_0.parameters(), lr= 0.001) # Start the timer start_time = time.time() # Train model 0 model_0_results = train(model= model_0, train_dataloader= train_dataloader, test_dataloader= test_dataloader, optimizer= optimizer, loss_fn= loss_fn, epochs= NUM_EPOCHS ) 10%|β–ˆ | 1/10 [02:30<22:37, 150.88s/it] Epoch: 1 | train_loss: 0.3549 | train_acc: 0.8668 | test_loss: 0.3059 | test_acc: 0.8842 20%|β–ˆβ–ˆ | 2/10 [04:57<19:48, 148.59s/it] Epoch: 2 | train_loss: 0.1707 | train_acc: 0.9420 | test_loss: 0.2648 | test_acc: 0.9062 30%|β–ˆβ–ˆβ–ˆ | 3/10 [07:24<17:14, 147.83s/it] Epoch: 3 | train_loss: 0.1153 | train_acc: 0.9627 | test_loss: 0.2790 | test_acc: 0.8962 40%|β–ˆβ–ˆβ–ˆβ–ˆ | 4/10 [09:52<14:46, 147.71s/it] Epoch: 4 | train_loss: 0.0900 | train_acc: 0.9695 | test_loss: 0.2719 | test_acc: 0.8979 50%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 5/10 [12:19<12:18, 147.65s/it] Epoch: 5 | train_loss: 0.0760 | train_acc: 0.9758 | test_loss: 0.2927 | test_acc: 0.8950 60%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 6/10 [14:47<09:50, 147.57s/it] Epoch: 6 | train_loss: 0.0616 | train_acc: 0.9814 | test_loss: 0.3326 | test_acc: 0.8942 70%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 7/10 [17:15<07:23, 147.76s/it] Epoch: 7 | train_loss: 0.0488 | train_acc: 0.9838 | test_loss: 0.3086 | test_acc: 0.8946 80%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 8/10 [19:42<04:55, 147.60s/it] Epoch: 8 | train_loss: 0.0534 | train_acc: 0.9835 | test_loss: 0.3186 | test_acc: 0.9017 90%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 9/10 [22:10<02:27, 147.66s/it] Epoch: 9 | train_loss: 0.0422 | train_acc: 0.9878 | test_loss: 0.3317 | test_acc: 0.9012 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 10/10 [24:38<00:00, 147.80s/it] Epoch: 10 | train_loss: 0.0433 | train_acc: 0.9878 | test_loss: 0.3853 | test_acc: 0.9038 The train and test loss and accuracy Confusion matrix # Import tqdm for progress bar from tqdm.auto import tqdm # 1. Make predictions with trained model y_preds = [] model_0.eval() with torch.inference_mode(): for X, y in tqdm(test_dataloader, desc="Making predictions"): # Send data and targets to target device X, y = X.to(device), y.to(device) # Do the forward pass y_logit = model_0(X) # Turn predictions from logits -> prediction probabilities -> predictions labels y_pred = torch.softmax(y_logit, dim=1).argmax(dim=1) # Put predictions on CPU for evaluation y_preds.append(y_pred.cpu()) # Concatenate list of predictions into a tensor y_pred_tensor = torch.cat(y_preds) from torchmetrics import ConfusionMatrix from mlxtend.plotting import plot_confusion_matrix # 2. Setup confusion matrix instance and compare predictions to targets confmat = ConfusionMatrix(num_classes=len(class_names), task='multiclass') confmat_tensor = confmat(preds=y_pred_tensor, target=torch.Tensor(test_data.targets)) # 3. Plot the confusion matrix fig, ax = plot_confusion_matrix( conf_mat=confmat_tensor.numpy(), # matplotlib likes working with NumPy class_names=class_names, # turn the row and column labels into class names figsize=(10, 7) ); Confusion Result so what should I do?
As @NiccolΓ² Borgioli mentioned, your model is overfitting the training data, so a very simple change that will most likely improve your code is adding weight decay, that modifies the loss function to include a term proportional to the norm of the weights, it makes the weighs tend to zero and reduces overfitting by avoiding weird situations where a lot of non-zero weights just counterbalance each other. In practice you can very simply use: DECAY_STRENGTH = 10**(-3) optimizer = torch.optim.Adam(params= model_0.parameters(), lr= 0.001, weight_decay=DECAY_STRENGTH) If the model still overfits you can increase DECAY_STRENGTH, if it underfits (bad performance even in training) you can decrease it. Always keep in mind that the best way to avoid over-fitting is having a larger training set, so if at all possible (if you have control on the data collection), try increasing the training data. Otherwise you can also try data augmentation as suggested by @NiccolΓ² Borgioli
3
1
75,933,354
2023-4-4
https://stackoverflow.com/questions/75933354/self-as-function-within-class-what-does-it-do
Sorry for the poor title but I'm unsure how better to describe the question. So I recently watched Andrej Kaparthy's build GPT video which is awesome and now trying to reconstruct the code myself I notices that he uses self() as a function and was curious why and what exactly it does. The code is here and I'm curious in particular about the generate function: class BigramLanguageModel(nn.Module): def __init__(self, vocab_size): super().__init__() # each token directly reads off the logits for the next token from a lookup table self.token_embedding_table = nn.Embedding(vocab_size, vocab_size) def forward(self, idx, targets=None): # idx and targets are both (B,T) tensor of integers logits = self.token_embedding_table(idx) # (B,T,C) if targets is None: loss = None else: B, T, C = logits.shape logits = logits.view(B*T, C) targets = targets.view(B*T) loss = F.cross_entropy(logits, targets) return logits, loss def generate(self, idx, max_new_tokens): # idx is (B, T) array of indices in the current context for _ in range(max_new_tokens): # get the predictions logits, loss = self(idx) # focus only on the last time step logits = logits[:, -1, :] # becomes (B, C) # apply softmax to get probabilities probs = F.softmax(logits, dim=-1) # (B, C) # sample from the distribution idx_next = torch.multinomial(probs, num_samples=1) # (B, 1) # append sampled index to the running sequence idx = torch.cat((idx, idx_next), dim=1) # (B, T+1) return idx So to me it seems that he is calling the forward function defined within the class through using the self(). Is that correct? And if so why would he not use forward(idx) instead. Thank you for you help!
Meh, this is pytorch. Remember that you can use the model like this: model(x) to do the model.forward(x). So inside of the model class self(x) will be the basically the same as doing self.forward(x).
4
2
75,932,613
2023-4-4
https://stackoverflow.com/questions/75932613/pydantic-problem-with-declared-types-vs-response-returned-type
I will show you some minimal example: from pydantic import BaseModel class Foo(BaseModel): value: PositiveInt | None = None def some_function(self) -> PositiveInt: return self.value In above example there is problem with type of the returned value of "some_function". The "self.value" is not "PositiveInt" - its "Optional[PositiveInt, None]" - cause I want it during initialization as None - then doing some "_post_init_" (what is not supported right now) and return just "PositiveInt". What do you think, how should I do it? For example I can add "assert self.value" - in this case I will have assertion error when self.value is None. Or maybe just do "return PositiveInt(self.value)" - to prevent some mypy errors? Or maybe there is some internal build-in method for changing the type of returning value? (something like response_type in FastApi - when you need or want to return some data that is not exactly what the type declares) Any ideas? BR! Edit: More details: What if you want to have some checking if value1 or value2 exists and based on it calculate the second one? from pydantic import BaseModel class Foo(BaseModel): value1: PositiveInt | None = None value2: PositiveInt | None = None def post_init_function(self) -> None: if self.value1: self.value2 = 100 elif self.value2: self.value1 = 100 @property def value1(self) -> PositiveInt: return self.PositiveInt foo1 = Foo(value1=10) foo1.post_init_function() # value1 = 10, value2 = 100 foo2 = Foo(value2=5) foo2.post_init_function() # value1 = 100, value2 = 5
Using dataclasses from the default library, I would separate the __init__ parameter that could be None from the field which cannot be None. from dataclasses import dataclass, field @dataclass class Foo: value1: int = field(init=False) value2: int = field(init=False) v1: InitVar[int | None] = None v2: InitVar[int | None] = None def __post_init__(self, v1, v2): if v1 is None and v2 is None: raise ValueError("v1 and v2 cannot both be None") elif v1 is None: self.value1 = 100 self.value2 = v2 else: self.value1 = v1 self.value2 = 100 I am not sure what the equivalent idiom for a Pydantic model would be, though I think this should work with few or no changes for a Pydantic dataclass.
3
1
75,933,081
2023-4-4
https://stackoverflow.com/questions/75933081/where-is-the-giant-cpython-switch-case-statement-moved
Not sure if it's off topic but don't know any better place to ask. In cpython there was a very giant switch case statement for executing each opcode. This switch case previously was placed in the _PyEval_EvalFrameDefault function. Here is the link. The switch case statement starts here. This was a core part of cpython and everyone who was interested in cpython internals, would probably explore it in detail. Recently I was searching for it and I couldn't find it. In this version of _PyEval_EvalFrameDefault I can't find it. It's much shorter than the last one. I even tried to find this switch statement by searching for opcodes in my IDE. But even that didn't helped find where it is. Can anyone who is aware of latest cpython development changes help me? Thanks in advance.
It's in Python/generated_cases.c.h, which gets inserted into _PyEval_EvalFrameDefault with an #include "generated_cases.c.h". As you might guess from the name, generated_cases.c.h is generated code. You can see the code generator in Tools/cases_generator/generate_cases.py
5
6
75,922,697
2023-4-3
https://stackoverflow.com/questions/75922697/anyone-know-how-to-display-a-pandas-dataframe-in-databricks
Previously I had a pandas dataframe that I could display as a table in Databricks using: df.display() Pandas was updated to v2.0.0. today and I am now getting the following error when I run df.display(): AttributeError: 'DataFrame' object has no attribute 'iteritems' Anyone know how I can resolve this? I tried running df.display (without parenthesis) and it gives an output but I am looking for an output in the tabular form.
As a workaround, downgrade to pandas v1.5 %pip install --upgrade pandas==1.5 The answers provided till now used to work prior to 3rd April 2023. As of April 4, with pandas 2.0.0, you are not able to convert a Pandas DataFrame to a Spark DataFrame using the command: spark.createDataFrame(df) Using the above command leads to the error mentioned in the question: AttributeError: 'DataFrame' object has no attribute 'iteritems' The iteritems function seems to have been removed in pandas 2.0.0. From the changelog of pandas 2.0.0: Removed deprecated Series.iteritems(), DataFrame.iteritems(), use obj.items instead While the code written in spark to convert pandas dataframe to a spark dataframe still uses iteritems /databricks/spark/python/pyspark/sql/pandas/conversion.py in createDataFrame(self, data, schema, samplingRatio, verifySchema) 308 warnings.warn(msg) 309 raise --> 310 data = self._convert_from_pandas(data, schema, timezone) 311 return self._create_dataframe(data, schema, samplingRatio, verifySchema) 312 /databricks/spark/python/pyspark/sql/pandas/conversion.py in _convert_from_pandas(self, pdf, schema, timezone) 340 pdf[field.name] = s 341 else: --> 342 for column, series in pdf.iteritems(): 343 s = _check_series_convert_timestamps_tz_local(series, timezone) 344 if s is not series: Looks like we will have to wait for a fix to use Pandas 2.0.0.
3
2
75,926,636
2023-4-4
https://stackoverflow.com/questions/75926636/databricks-issue-while-creating-spark-data-frame-from-pandas
I have a pandas data frame which I want to convert into spark data frame. Usually, I use the below code to create spark data frame from pandas but all of sudden I started to get the below error, I am aware that pandas has removed iteritems() but my current pandas version is 2.0.0 and also I tried to install lesser version and tried to created spark df but I still get the same error. The error invokes inside the spark function. What is the solution for this? which pandas version should I install in order to create spark df. I also tried to change the runtime of cluster databricks and tried re running but I still get the same error. import pandas as pd spark.createDataFrame(pd.DataFrame({'i':[1,2,3],'j':[1,2,3]})) error:- UserWarning: createDataFrame attempted Arrow optimization because 'spark.sql.execution.arrow.pyspark.enabled' is set to true; however, failed by the reason below: 'DataFrame' object has no attribute 'iteritems' Attempting non-optimization as 'spark.sql.execution.arrow.pyspark.fallback.enabled' is set to true. warn(msg) AttributeError: 'DataFrame' object has no attribute 'iteritems'
It's related to the Databricks Runtime (DBR) version used - the Spark versions in up to DBR 12.2 rely on .iteritems function to construct a Spark DataFrame from Pandas DataFrame. This issue was fixed in the Spark 3.4 that is available as DBR 13.x. If you can't upgrade to DBR 13.x, then you need to downgrade the Pandas to latest 1.x version (1.5.3 right now) by using %pip install -U pandas==1.5.3 command in your notebook. Although it's just better to use Pandas version shipped with your DBR - it was tested for compatibility with other packages in DBR.
28
39
75,921,577
2023-4-3
https://stackoverflow.com/questions/75921577/murmur3-hash-compatibility-between-go-and-python
We have two different libraries, one in Python and one in Go that need to compute murmur3 hashes identically. Unfortunately no matter how hard we try, we cannot get the libraries to produce the same result. It appears from this SO question about Java and Python that compatibility isn't necessarily straight forward. Right now we're using the python mmh3 and Go github.com/spaolacci/murmur3 libraries. In Go: hash := murmur3.New128() hash.Write([]byte("chocolate-covered-espresso-beans")) fmt.Println(base64.RawURLEncoding.EncodeToString(hash.Sum(nil))) // Output: cLHSo2nCBxyOezviLM5gwg In Python: name = "chocolate-covered-espresso-beans" hash = mmh3.hash128(name.encode('utf-8'), signed=False).to_bytes(16, byteorder='big', signed=False) print(base64.urlsafe_b64encode(hash).decode('utf-8').strip("=")) # Output: jns74izOYMJwsdKjacIHHA (big byteorder) hash = mmh3.hash128(name.encode('utf-8'), signed=False).to_bytes(16, byteorder='little', signed=False) print(base64.urlsafe_b64encode(hash).decode('utf-8').strip("=")) # Output: HAfCaaPSsXDCYM4s4jt7jg (little byteorder) hash = mmh3.hash_bytes(name.encode('utf-8')) print(base64.urlsafe_b64encode(hash).decode('utf-8').strip("=")) # Output: HAfCaaPSsXDCYM4s4jt7jg In Go, murmur3 returns a uint64 so we assume signed=False in Python; however we also tried signed=True and did not get matching hashes. We're open to different libraries, but are wondering if there is something wrong with either our Go or Python methodologies of computing a base64 encoded hash from a string. Any help appreciated.
That first Python result is almost right. >>> binascii.hexlify(base64.b64decode('jns74izOYMJwsdKjacIHHA==')) b'8e7b3be22cce60c270b1d2a369c2071c' In Go: x, y := murmur3.Sum128([]byte("chocolate-covered-espresso-beans")) fmt.Printf("%x %x\n", x, y) Results in: 70b1d2a369c2071c 8e7b3be22cce60c2 So the order of the two words is flipped. To get the same result in Python, you can try something like: name = "chocolate-covered-espresso-beans" hash = mmh3.hash128(name.encode('utf-8'), signed=False).to_bytes(16, byteorder='big', signed=False) hash = hash[8:] + hash[:8] print(base64.urlsafe_b64encode(hash).decode('utf-8').strip("=")) # cLHSo2nCBxyOezviLM5gwg
4
3
75,919,967
2023-4-3
https://stackoverflow.com/questions/75919967/how-to-benchmark-a-single-function-call-in-python
How to interactively (micro)benchmark a code expression in Python (i.e. the equivalent of @btime/@benchmark in Julia) ? I would like to benchmark interactively an expression (a function call), where the number of times this expression should be evaluated depends on its computational cost / variance.... I have tried timeit.timeit but I have some quesitons: How do I interpret the time output of the following results: >>> a = 2.2 >>> timeit.repeat("round(a)", setup='from __main__ import a; gc.enable()', repeat=5,number=10) [4.631001502275467e-06, 1.3809185475111008e-06, 1.2170057743787766e-06, 1.1718366295099258e-06, 1.1730007827281952e-06] >>> timeit.timeit("round(a)", setup='from __main__ import a; gc.enable()', number=10) 5.741836503148079e-06 >>> timeit.timeit("round(a)", setup='from __main__ import a; gc.enable()') 0.11461802502162755 >>> timeit.Timer('round(a)', setup='from __main__ import a; gc.enable()').autorange() (5000000, 0.4272152939811349) It seems that when I go from number from 1 to 10, the timing remains pretty stable, but then it grows of different order of magnitude.... Does it makes sense a workflow where I first create the Timer object once, and then I modify several times the code to evaluate and benchmark the modified Timer ? E.g. import timeit import gc bclass = timeit.Timer('round(1.1)','gc.enable()', globals=globals()) [...] bclass.stmt = "small_3x2_nash.vertex_enumeration()" bclass.autorange() bclass.stmt = "small_3x2_nash.lemke_howson_enumeration()" bclass.autorange() bclass.stmt = "small_3x2_nash.support_enumeration()" bclass.autorange() (seems this is not possible, as I have tried very different code and the result of the timing remains almost the same)
You can also use the Timer class to enable de GC, as explained in the docs here: https://docs.python.org/3/library/timeit.html#timeit.Timer.timeit And instead of explicit import every variable/function that you want to use from main, you could pass globals() in the Timer arguments. In that way, all the globals variables, functions, etc will be passed to de evaluated function. Python 3.10.10 (main, Mar 5 2023, 22:26:53) [GCC 12.2.1 20230201] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import timeit >>> >>> a = 2.2 >>> >>> t = timeit.Timer('round(a)', globals=globals()) >>> >>> t.timeit(number=1000) 0.00042562399994494626 >>> t.autorange() (5000000, 0.46861540100007915) To enable GC you need also import the gclib import gc t = timeit.Timer('round(a)', 'gc.enable()', globals=globals())
3
3
75,920,424
2023-4-3
https://stackoverflow.com/questions/75920424/how-to-ignore-rev-in-pre-commit-config
Here is a .pre-commit-config.yaml from pre-commit. It will git clone the specified rev of git repo. How can I ignore the rev and always git clone the newest? repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace
you intentionally cannot from the docs pre-commit configuration aims to give a repeatable and fast experience and therefore intentionally doesn't provide facilities for "unpinned latest version" for hook repositories. Instead, pre-commit provides tools to make it easy to upgrade to the latest versions with pre-commit autoupdate. If you need the absolute latest version of a hook (instead of the latest tagged version), pass the --bleeding-edge parameter to autoupdate. pre-commit assumes that the value of rev is an immutable ref (such as a tag or SHA) and will cache based on that. Using a branch name (or HEAD) for the value of rev is not supported and will only represent the state of that mutable ref at the time of hook installation (and will NOT update automatically). disclaimer: I wrote pre-commit
5
12
75,919,378
2023-4-3
https://stackoverflow.com/questions/75919378/how-to-handle-circular-imports-in-sqlalchemy
I'm having an issue with circular imports in SQLAlchemy. I have two files foo.py and bar.py. foo.py defines a SQLAlchemy class Foo, and bar.py defines a class Bar. Both Foo and Bar are each other's foreign keys, so I map them to each other with Mapped["..."] to get type safety, however that means I need to import the actual classes aswell. This is causing a circular import error. What's the best way to handle this issue? What are some general best practices for dealing with circular imports in SQLAlchemy? Can't you have type safety in this case if you use a relationship bidirectionally? # foo.py from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship from .bar import Bar class Foo(Base): __tablename__ = 'foo' id = Column(Integer, primary_key=True) bar_id = Column(Integer, ForeignKey('bar.id')) bar: Mapped["Bar"] = relationship('Bar') # bar.py from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship from .foo import Foo class Bar(Base): __tablename__ = 'bar' id = Column(Integer, primary_key=True) foo_id = Column(Integer, ForeignKey('foo.id')) foo: Mapped["Foo"] = relationship('Foo') Edit: Note that I can't remove the Bar and Foo imports because then Mapped["..."] will raise an undefined error for "..."
you can use TYPE_CHECKING. This constant is False at runtime, but True when mypy (and other type-checking tools) evaluate your code from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from .bar import Bar else: Bar = "Bar" # foo.py from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship class Foo(Base): __tablename__ = 'foo' id = Column(Integer, primary_key=True) bar_id = Column(Integer, ForeignKey('bar.id')) bar: Mapped[Bar] = relationship('Bar')
6
8
75,917,750
2023-4-3
https://stackoverflow.com/questions/75917750/very-slow-aggregate-on-pandas-2-0-dataframe-with-pyarrow-as-dtype-backend
Let's say I have the following dataframe: Code Price AA1 10 AA1 20 BB2 30 And I want to perform the following operation on it: df.groupby("code").aggregate({ "price": "sum" }) I have tried playing with the new pyarrow dtypes introduced in Pandas 2.0 and I created 3 copies, and for each copy I measured execution time (average of 5 executions) of the operation above. Code column dtype Price column dtype Execution time Object float64 2.94 s string[pyarrow] double[pyarrow] 49.5 s string[pyarrow] float64 1.11 s Can anyone explain why applying an aggregate function on a column with double pyarrow dtype is so slow compared to the standard numpy float64 dtype?
https://github.com/pandas-dev/pandas/issues/52070 Looks like groupby for arrow isn't implemented yet - so there's likely a arrow -> numpy happening internally leading to a loss of performance.
5
11
75,913,380
2023-4-2
https://stackoverflow.com/questions/75913380/importerror-cannot-import-name-closed-from-websockets-connection
I installed rasa on a virtual environment on windows. But while I am trying to check either rasa is installed or not, it is showing an error that says- ImportError: cannot import name 'CLOSED' from 'websockets.connection' I have reinstalled rasa, and installed websockets. But still getting the error. Python version is 3.10.2 Can anyone help me to solve this problem?
Try installing websockets version 10.0 like this: pip install websockets==10.0 It should help (it helped me)
6
20
75,907,222
2023-4-1
https://stackoverflow.com/questions/75907222/jupyterlab-extension-gives-a-function-not-found-error
I have issues with jupyter extensions on ArchLinux. In particular, I get the following error: [W 2023-04-01 18:34:36.504 ServerApp] A `_jupyter_server_extension_points` function was not found in jupyter_nbextensions_configurator. Instead, a `_jupyter_server_extension_paths` function was found and will be used for now. This function name will be deprecated in future releases of Jupyter Server. [W 2023-04-01 18:34:36.493 ServerApp] A `_jupyter_server_extension_points` function was not found in notebook_shim. Instead, a `_jupyter_server_extension_paths` function was found and will be used for now. This function name will be deprecated in future releases of Jupyter Server. How can I get rid of this error/warning? I tried removing the functions with Pip, but it did not work. Any ideas?
This is not an error, but a warning aimed at developers of notebook extensions: jupyter_nbextensions_configurator and notebook_shim respectively, not at a user like you. You do not need to do anything. It's worth pointing out that the next version of Jupyter Notebook (v7) will not require jupyter_nbextensions_configurator anymore as it will come with new extension manager (and a completely new extension ecosystem shared with JupyterLab), so there is very little incentive to address this deprecation warning in jupyter_nbextensions_configurator as it will cease to be relevant soon.
8
15
75,907,394
2023-4-1
https://stackoverflow.com/questions/75907394/what-is-the-difference-between-security-and-depends-in-fastapi
This is my code: from fastapi import FastAPI, Depends, Security from fastapi.security import HTTPBearer bearer = HTTPBearer() @app.get("/") async def root(q = Security(bearer)): return {'q': q} @app.get("/Depends") async def root(q = Depends(bearer)): return {'q': q,} Both routes give precisely the same result and act in the same manner. I checked the source code and found that the Security class inherits from the Depedends class. But I have no understanding in what way. Can you please show me the differences and why would I prefer to use Security over Depends.
TL;DR Use Security for security related dependencies as it is thought as a convenience for the devs. Use Depends when more general dependencies are needed. Nevertheless, you may use these two interchangeably (for security related requirements). Original answer The Security class is a more specialized version of Depends. In the source code https://github.com/tiangolo/fastapi/blob/master/fastapi/param_functions.py other types of dependencies are defined, such as Form, Body and File. As their names suggest, they are specialized for a particular task/data. Basically there is no big difference between the two. The Security is more specialized than Depends, so the output is the same. It is more of a convenience for the developer.
4
3
75,902,589
2023-3-31
https://stackoverflow.com/questions/75902589/change-the-shape-of-legend-markers-with-geopandas-geodataframe-plot
I like the convenience of the following syntax to make maps: import geopandas world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) world.plot(column='continent',legend=True,legend_kwds = {'loc':'lower left'}) However, I am looking for a way to change the shape of markers that this produces. By default (with a non-continuous variable), geopandas (or matplotlib) produces filled in circles. I would really like these markers to be filled in rectangles with a thin black border. I have tried using the marker parameter in plot to no success. I have also tried various arguments in legend_kwds.
Using geopandas makes it difficult to find a way to edit the legend's properties or get hold of the legend object. Here is a way to go. First, get the axis from the plot statement: ax = world.plot( ... ) the axis provides access to all the plot components and many functions to manipulate your plot, including the legend. Once you get hold of the legend, you can change its properties as needed. In the code below, the shape of the marker, edge color, edge width are set as required. import geopandas world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) ax = world.plot(figsize=(12,9) ,column='continent',legend=True,legend_kwds = {'loc':'lower left'}) leg1 = ax.get_legend() for ea in leg1.legendHandles: ea.set_marker('s') ea.set_markeredgecolor('k') ea.set_markeredgewidth(0.5) As far as I know, the option legend_kwds in the plot statement does not include the item to set the legend marker's shape.
3
4
75,909,463
2023-4-1
https://stackoverflow.com/questions/75909463/how-to-use-pd-melt-to-unpivot-a-dataframe-where-columns-share-a-prefix
I'm trying to unpivot my data using pd.melt but no success so far. Each row is a business, and the data contains information about the business and multiple reviews. I want my data to have every review as a row. My first 150 columns are in groups of 15, each group column name shares the same pattern reviews/n/ for 0 < n < 9. (reviews/0/text, reviews/0/date, ... , reviews/9/date). The next 65 columns in the dataframe include more data about the business (e.g. business_id, address) that should remain as id_variables. My current data looks like this: business_id address reviews/0/date reviews/0/text reviews/1/date reviews/1/text 12345 01 street 1/1/1990 "abc" 2/2/1995 "def" and my new dataframe should have every review as a row instead of every business, and look like this: business_id address review_number review_date review_text 12345 01 street 0 1/1/1990 "abc" 12345 01 street 1 2/2/1995 "def" I tried using pd.melt but could not succeed in making code that produced something valuable to me.
You can use pandas.wide_to_long() to do what you want. However, you will need to rename your columns from the pattern reviews/N/COL to reviews/COL/N (or something similar) first, as wide_to_long() can only unpivot based on prefixes, whereas in your column names, you have a prefix and a suffix. You could do this manually or e.g. using the re module and an appropriate regex: df = df.rename(columns=lambda x: re.sub('reviews/(\d)/(.*)', r'review_\2\1', x)) After that, your data should look like this (note the changed colnames): business_id address review_date0 review_text0 review_date1 review_text1 12345 01 street 1/1/1990 abc 2/2/1995 def Now you can use pandas.wide_to_long() and use the stubnames parameter to specify the prefix of the columns that should be grouped when you unpivot. df = pd.wide_to_long(df, stubnames=['review_date','review_text'], i=['business_id', 'address'], j='review_number') Finally, call .reset_index() to achieve the result you asked for. Full example: import re import pandas as pd df = pd.DataFrame({'business_id': 12345, 'address': '01 street', 'reviews/0/date': '1/1/1990', 'reviews/0/text': 'abc', 'reviews/1/date': '2/2/1995', 'reviews/1/text': 'def'}, index = [0]) df = df.rename(columns=lambda x: re.sub('reviews/(\d)/(.*)', r'review_\2\1', x)) df = pd.wide_to_long(df, stubnames=['review_date','review_text'], i=['business_id', 'address'], j='review_number').reset_index() Result: business_id address review_number review_date review_text 12345 01 street 0 1/1/1990 abc 12345 01 street 1 2/2/1995 def
4
6
75,908,794
2023-4-1
https://stackoverflow.com/questions/75908794/split-a-csv-file-into-multiple-files-based-on-a-pattern
I have a csv file with the following structure: time,magnitude 0,13517 292.5669,370 620.8469,528 0,377 832.3269,50187 5633.9419,3088 20795.0950,2922 21395.6879,2498 21768.2139,647 21881.2049,194 0,3566 292.5669,370 504.1510,712 1639.4800,287 46709.1749,365 46803.4400,500 I'd like to split this csv file into separate csv files, like the following: File 1: time,magnitude 0,13517 292.5669,370 620.8469,528 File 2: time,magnitude 0,377 832.3269,50187 5633.9419,3088 20795.0950,2922 21395.6879,2498 and so on.. I've read several similar posts (e.g., this, this, or this one), but they all search for specific values in a column and save each groups of values into a separate file. However, in my case, the values of time column are not the same. I'd like to split base on a condition: If time = 0, save that row and all subsequent rows in a new file until the next time =0. Can someone please let me know how to do this?
With pandas, you can use groupby and boolean indexing : #pip install pandas import pandas as pd df = pd.read_csv("input_file.csv", sep=",") # <- change the sep if needed for n, g in df.groupby(df["time"].eq(0).cumsum()): g.to_csv(f"file_{n}.csv", index=False, sep=",") Output : time magnitude # <- file_1.csv 0.0000 13517 292.5669 370 620.8469 528 time magnitude # <- file_2.csv 0.0000 377 832.3269 50187 5633.9419 3088 20795.0950 2922 21395.6879 2498
3
4
75,908,169
2023-4-1
https://stackoverflow.com/questions/75908169/generating-a-column-showing-the-number-of-distinct-values-between-consecutive-da
I have a pandas dataframe with the following format: UserId Date BookId 1 2022-07-15 10 1 2022-07-16 11 1 2022-07-16 12 1 2022-07-17 12 From this table, what I want to obtain is the number of new BookId on each consecutive day for each user. For example, based on the table above, the user read two new books on 2022-07-16, and did not read a new book on 2022-07-17 since s/he read it already on the previous day. Here is the expected outcome: UserId 2022-07-16 2022-07-17 1 2 0 I feel like this task could be done by grouping data by UserId and Date, and then using the apply lambda function. However, I could not manage it. I ended up with the following code, which uses the for loop. Is there a way to achieve this without a loop with a shorter code? df = studentAnswers.groupby('StudentId') df.apply(findObjDiff) def findObjDiff(df): print(df.StudentId.head(3)) dataDict = {} dates = list(df.Date) dates.sort() for d in dates: ixNext = dates.index(d) + 1 if(ixNext > len(dates)): break dateNext = dates[ixNext] objListPrev = set(df[df.Date == d].ObjectiveId) objListNext = set(df[df.Date == dateNext].ObjectiveId) dataDict[df.StudentId] = {dateNext : {'Different': len(objListPrev - objListNext)}} return dataDict
Using duplicated and a pivot_table: (df.assign(count=~df['BookId'].duplicated()) .pivot_table(index='UserId', columns='Date', values='count', aggfunc='sum') .astype(int).reset_index().rename_axis(columns=None) ) Considering only consecutive days for the duplicates: s = df.groupby(pd.to_datetime(df['Date']))['BookId'].agg(set) (df.assign(count=(s-s.shift(1, freq='D')).str.len().to_numpy()) .pivot_table(index='UserId', columns='Date', values='count', aggfunc='sum') .astype(int).reset_index().rename_axis(columns=None) ) Output: UserId 2022-07-15 2022-07-16 2022-07-17 0 1 1 2 0
3
1
75,907,862
2023-4-1
https://stackoverflow.com/questions/75907862/pyside6-wsl2-importerror-libegl-so-1
I'm using isolated with poetry/venv Python: 3.11.2 with Ubuntu WSL2 22.04 python app.py Gives me the following error: Traceback (most recent call last): File "/home/lara/projects/qtapp/app.py", line 4, in <module> from PySide6.QtGui import QGuiApplication ImportError: libEGL.so.1: cannot open shared object file: No such file or directory app.py: from PySide6.QtGui import QGuiApplication from PySide6.QtQml import QQmlApplicationEngine app = QGuiApplication() engine = QQmlApplicationEngine() engine.load("myqmlfile.qml") app.exec() pyproject.toml dependencies [tool.poetry.dependencies] python = ">=3.11,<3.12" pyside6 = "^6.4.3" [tool.poetry.group.dev.dependencies] pytest = "^7.2.2" pytest-cov = "^4.0.0" isort = "^5.12.0" black = "^23.3.0" poethepoet = "^0.19.0"
You can search packages.ubuntu.com to figure out which package provides a certain file. In this case it's libegl1. Install it in WSL with: apt install libegl1
4
8
75,907,155
2023-4-1
https://stackoverflow.com/questions/75907155/is-asyncio-affected-by-the-gil
On this page I read this: Coroutines in the asyncio module are not limited by the Global Interpreter Lock or GIL. But how is this possible if both the asyncio event loop and the threading threads are running in a single Python process with GIL? As far as I understand, the impact of the GIL on asyncio will not be as strong as on threading, because in the case of threading, the interpreter will switch to useless operations, such as time.sleep(). Therefore, when working with asyncio, it is recommended to use asyncio.sleep(). I understand that these tools are designed for slightly different things, threading is more often used to execute "legacy" blocking code for IO-Bound operations, and asyncio for non-blocking code.
There are really two kinds of answers to this, depending on whether you take the GIL as the concrete implementation or the conceptual limitation. The answer is No'ish for the former, and Yes'ish for the latter. No, asyncio concurrency is not bound to the GIL. The GIL exists to synchronise thread concurrency: When more than one thread is active at once, only the thread that owns the GIL may execute Python code. This means that if another thread needs to run, ownership of the GIL must pass from the current executing thread to the other thread. This is realised via preemptive concurrency, meaning the currently executing thread is forcefully paused regularly. As such, the GIL is the mechanism handling the switching of control between the currently executing thread and all other threads. This is a very wasteful mechanism that becomes worse the more threads there are. In contrast, asyncio has its own concurrency synchronisation: async/await provides cooperative concurrency by design. That means the currently executing task can voluntarily yield control to any other waiting task. This allows the asyncio event loop to freely schedule tasks. As such, the GIL is not involved in switching control between the currently executing task and all other tasks. An async framewok such as asyncio can achieve very efficient task switching, regardless of the number of tasks. Yes, asyncio is bound by the GIL. While asyncio can efficiently switch tasks, it cannot run more than one task at any moment. As such, it does not actually avoid the conceptual limitation of the GIL: running more than one operation at once. While asyncio applications avoid the inefficiency of the GIL for many operations, it does not avoid the limitation of the GIL for parallel operations. Notably, solving this limitation would require solving the exact same challenge as for removing the GIL: providing a safe synchronisation when executing Python code in parallel. In addition, asyncio still cannot execute blocking code concurrently as tasks but must fallback to threading for these. Thus, asyncio's backend for executing blocking code concurrently is directly bound by the GIL.
14
21
75,907,397
2023-4-1
https://stackoverflow.com/questions/75907397/create-a-single-column-from-a-pandas-data-frame-with-n-columns
I have a data frame with 3 columns: A, B and C as below: A: 1 2 3 B: 10 20 30 C: 100 200 300 I need to save the values only in a csv file in "one" row like this ( no need to save the column name) 1 2 3 10 20 30 100 200 300 I tried to create a new data frame with only one coumn using pandas, and transpose it, then write it to a csv file. But I couln't figure out how. Could you please help me?
You can use unstack, to_frame and T: (df.unstack().to_frame().T .to_csv('out.csv', header=None, index=None, sep=' ') ) Or, with help of numpy's ravel: (pd.DataFrame([df.to_numpy().ravel('F')]) .to_csv('out.csv', header=None, index=None, sep=' ') ) Output file: 1 2 3 10 20 30 100 200 300
4
2
75,905,429
2023-4-1
https://stackoverflow.com/questions/75905429/django-insert-data-into-child-table-once-the-parent-record-is-created
I am using Django REST Framework and facing a problem during inserting data into the child table. There are 2 models named Card and ContactName that have the following fields. The Card has a relation with ContactName via a foreign key field name card. models.py: class Card(models.Model): image = models.ImageField(upload_to='images', max_length=255, null=True, blank=True) filename = models.CharField(max_length=255, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.filename class ContactName(models.Model): first_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) confidence = models.FloatField(default=0) card = models.ForeignKey(Card, on_delete=models.CASCADE, related_name='contact_name') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.first_name serializers.py file: class ContactNameSerializer(serializers.ModelSerializer): class Meta: model = ContactName fields = ['id', 'first_name', 'last_name', 'confidence', 'card', 'created_at', 'updated_at'] class CardSerializer(serializers.ModelSerializer): contact_name = ContactNameSerializer(many=True, read_only=True) class Meta: model = Card fields = ['id', 'image', 'filename', 'contact_name', 'created_at', 'updated_at'] In ViewSet once the card record is created, I also want to add the following ContactName JSON data into the child table, set the reference (card_id) as an id of that card, and return the newly added record in the response. e.g. [ { "first_name": "John", "last_name": "Doe", "confidence": 0.9 }, { "first_name": "Doe", "last_name": "John", "confidence": 0.5 } ] views.py: class CardViewSet(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = Card.objects.all() serializer_class = CardSerializer def create(self, request): cards_serializer = CardSerializer(data=request.data) if cards_serializer.is_valid(): cards_serializer.save() # insert the record into the child table and set the reference (card_id) as an id json = [ { "first_name": "John", "last_name": "Doe", "confidence": 0.9 }, { "first_name": "Doe", "last_name": "John", "confidence": 0.5 } ] return Response(cards_serializer.data, status=status.HTTP_201_CREATED) else: return Response(cards_serializer.errors, status=status.HTTP_400_BAD_REQUEST) I really appreciate the help. The final response will be something like this: { "id": 10, "image": "/media/abc.jpg", "filename": "abc.jpg", "contact_names": [ { "id": 1, "first_name": "John", "last_name": "Doe", "confidence": 0.9, "card_id": 10 }, { "id": 2, "first_name": "Doe", "last_name": "John", "confidence": 0.5, "card_id": 10 } ] }
Basically you can pass this data to your serializer by Including extra context and by overriding the create method as you are doing in your code: views.py class CardViewSet(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = Card.objects.all() serializer_class = CardSerializer def create(self, request): json = [ { "first_name": "John", "last_name": "Doe", "confidence": 0.9 }, { "first_name": "Doe", "last_name": "John", "confidence": 0.5 } ] serializer = CardSerializer(data=request.data, context={'contacts': json}) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) Also, override the create method on CardSerializer, to first create the instance using the validated data and then use the extra context data to create ContactName objects and assign them to the new Card instance: serializers.py class ContactNameSerializer(serializers.ModelSerializer): class Meta: model = models.ContactName fields = ['id', 'first_name', 'last_name', 'confidence', 'card'] class CardSerializer(serializers.ModelSerializer): contact_name = ContactNameSerializer(many=True, read_only=True) class Meta: model = models.Card fields = ['id', 'image', 'filename', 'contact_name', 'created_at', 'updated_at'] def create(self, validated_data): instance = models.Card.objects.create(**validated_data) contacts = self.context.get('contacts', None) for contact in contacts: models.ContactName.objects.create(**contact, card=instance) return instance A few notes: If you want card_id instead of card on the response data then change your field name (and update the serializer fields): class ContactName(models.Model): ... card_id = models.ForeignKey(Card...) ... Alternatively, you can just override .to_representation, remove the key:pair and reinsert with the new key value. Also, I would change this relationship to a many-to-many in order to avoid ContactName duplicates in your database.
4
1
75,904,780
2023-4-1
https://stackoverflow.com/questions/75904780/takes-long-time-while-building-image-on-python-wit-messaage-building-wheel-for
i have problem while building docker image on python : below execution process takes long time around 20 minutes: Building wheel for pandas (pyproject.toml): still running... Building wheel for pandas (pyproject.toml): still running... Building wheel for pandas (pyproject.toml): still running... Building wheel for pandas (pyproject.toml): still running... Building wheel for pandas (pyproject.toml): still running... Dockerfile: FROM python:3.11.2-buster WORKDIR /app COPY . . RUN pip install -r /app/requirements.txt CMD ["uvicorn", "main:app", "--host=0.0.0.0", "--port=80"] requirement.txt: fastapi uvicorn pydantic[dotenv] requests python-dotenv==0.19.2 pandas==1.4.3 numpy==1.24.2 scikit-learn==1.2.2
There is no building wheel for Pandas==1.4.3 and Python==3.11 so the fallback is to download the source archive (pandas-1.4.3.tar.gz) and build it from scratch. You have 2 options: Downgrade your python version from 3.11 to 3.10 in Dockerfile: FROM python:3.10.10-buster Upgrade the pandas version from 1.4.3 to 1.5.3 in requirements.txt: pandas==1.5.3 In both cases (Python 3.10, Pandas 1.4) or (Python 3.11, Pandas 1.5), there is no compilation time with your requirements.
6
9
75,901,770
2023-3-31
https://stackoverflow.com/questions/75901770/how-do-i-check-the-version-of-python-a-module-supports
I was wondering if there is a generic way to find out if your version of python is supported by a specific module? For example, let us say that I have python 3.11 installed on my computer and I want to install the modules biopython and lru-dict. Going to their respective pypi entries biopython shows this in their Project description: Python Requirements We currently recommend using Python 3.10 from http://www.python.org Biopython is currently supported and tested on the following Python implementations: Python 3.7, 3.8, 3.9, 3.10 and 3.11 – see http://www.python.org PyPy3.7 v7.3.5 – or later, see http://www.pypy.org However, if we check the lru-dict entry, their Project description does not mention Python requirements. I did eventually find out that python 3.11 is not supported by finding a issue on their github page. Is there a simpler way of finding this information out?
No, there is no generic way. If the library has tests you can run them and check, but it might give you false positives as well as false negatives :shrug: The lru-dict has this fragment in their setup.py, which is one of the places you can check for supported versions: 'Programming Language :: C', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: Implementation :: CPython', So as you can see, I don't think they knew about the issue.
4
2
75,896,790
2023-3-31
https://stackoverflow.com/questions/75896790/how-to-drop-duplicate-from-a-pandas-dataframe-with-some-complex-conditions
I am trying to drop duplicates, but based on some conditions. My dataframe looks like this: idx a b c d e f 1 1 ss1 0 25 A B 2 3 ss7 0 25 A B 3 5 ss5 0 12 C D 4 11 im3 0 12 C D 5 5 ss8 0 50 C K 6 9 im8 0 5 F G 7 8 ix6 0 5 F G Rows are considered duplicates if the values of columns d, e and f together match other records in the dataframe subset=['d', 'e', 'f']. For example, rows 1 and 2 are duplicates, rows 3 and 4 are duplicates, and rows 6 and 7 are duplicates. The selection of which row to drop is based on column b. If the value in column b begins with ss for both duplicates (rows 1 and 2), then anyone can be dropped If one of the duplicates begins with ss and the other begins with a different format (rows 3 and 4), then the one that begins with ss should be kept. If both duplicates in column b begin with anything other than ss (rows 6 and 7), then anyone can be selected. Therefore, the expected output should be something like this: idx a b c d e f 2 3 ss7 0 25 A B 3 5 ss5 0 12 C D 5 5 ss8 0 50 C K 7 8 ix6 0 5 F G
Sort by b key first (everything starts by 'ss' is moved to the end) then drop duplicates from ['d', 'e', 'f'] (keep the last): out = (df.sort_values('b', key=lambda x: x.str.startswith('ss')) .drop_duplicates(['d', 'e', 'f'], keep='last').sort_index()) # OR out = (df.sort_values('b', key=lambda x: x.str.startswith('ss')) .groupby(['d', 'e', 'f'], as_index=False).nth(-1).sort_index()) Output: >>> out idx a b c d e f 1 2 3 ss7 0 25 A B 2 3 5 ss5 0 12 C D 4 5 5 ss8 0 50 C K 6 7 8 ix6 0 5 F G
3
3
75,891,371
2023-3-30
https://stackoverflow.com/questions/75891371/keep-only-the-value-in-the-last-non-nan-column-set-all-other-values-to-nan-fas
I want to convert df into df_target, by keeping only the value in the last non-nan column (for each row individually). The other value should be set to nan. The following code already achieves what I want, but is very slow for large DataFrames. Is there any solution that is faster? import pandas as pd data = { 'A': [1, 2, 3, pd.NA, 5], 'B': [pd.NA, pd.NA, pd.NA, 4, 5], 'C': [pd.NA, pd.NA, 3, 4, pd.NA], } df = pd.DataFrame(data) data_target = { 'A': [1, 2, pd.NA, pd.NA,pd.NA], 'B': [pd.NA, pd.NA, pd.NA, pd.NA, 5], 'C': [pd.NA, pd.NA, 3, 4, pd.NA], } df_target = pd.DataFrame(data_target) df_out = df.apply(lambda row: row.where(row.index == row.last_valid_index(), pd.NA), axis=1) print(df_out.equals(df_target))
Do: df.where(df.notnull().iloc[:,::-1].cumsum(axis=1).le(1), pd.NA) The idea is to count (cumsum) the non-NA (notnull) from right to left (.iloc[:,::-1]) on each row (axis=1), then mask everything with >=2 NA as NA Output: A B C 0 1 <NA> <NA> 1 2 <NA> <NA> 2 <NA> <NA> 3 3 <NA> <NA> 4 4 <NA> 5 <NA>
3
3
75,890,154
2023-3-30
https://stackoverflow.com/questions/75890154/unable-to-stream-api-response-in-flask-application-on-google-cloud-application
I'm developing a little testing website using the OpenAI API. I'm trying to stream GPT's response, just like how it's done on https://chat.openai.com/chat. This works just fine when running my Flask application on a local development server, but when I deploy this app to Google Cloud, the response is given in one go, instead of being streamed. I have tried disabling buffering according to https://cloud.google.com/appengine/docs/flexible/how-requests-are-handled?tab=python#x-accel-buffering, but that didn't resolve the issue. I suspect that my issue lies in how I'm configuring my app on Google Cloud (or the lack thereof). This is what I've got going on currently, this works when running the application locally. main.py @app.route('/stream_response', methods=['POST']) def stream_response(): prompt_text = request.form['prompt'] def generate(): for chunk in gpt_model.get_response(prompt_text, stream=True): for choice in chunk['choices']: dictionary: dict = choice['delta'] if 'content' in dictionary: yield dictionary['content'] response = Response(generate(), content_type='text/html') response.headers['X-Accel-Buffering'] = 'no' return response prompt.html <script> function streamResponse() { var promptText = document.getElementById("prompt").value; var xhr = new XMLHttpRequest(); xhr.open("POST", "/stream_response", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onprogress = function () { document.getElementById("response-container").style.display = "block"; document.getElementById("response").innerHTML = xhr.responseText; console.log(xhr.responseText) }; xhr.send("prompt=" + encodeURIComponent(promptText)); } </script> Google Cloud app.yaml runtime: python310 handlers: - url: /.* script: auto Google Cloud deployment process gcloud app deploy
From your app.yaml, it means you're deploying to Google App Engine (GAE) Standard Environment. GAE doesn't support streaming - see doc where it says App Engine does not support streaming responses where data is sent in incremental chunks to the client while a request is being processed. All data from your code is collected as described above and sent as a single HTTP response. Chat UIs also usually require sockets. GAE Standard doesn't support web sockets but GAE Flex does (see docs)
4
4
75,889,507
2023-3-30
https://stackoverflow.com/questions/75889507/filter-and-merge-a-dataframe-in-python-using-pandas
I have a dataframe and I need to filter out who is the owner of which books so we can send them notifications. I am having trouble merging the data in the format I need. Existing dataframe Book Owner The Alchemist marry To Kill a Mockingbird john Lord of the Flies abel Catcher in the Ry marry Alabama julia;marry Invisible Man john I need to create new dataframe that lists the owners in column A and all the books they own in Column B. Desired output Owners Books marry The Alchemist, Catcher in the Ry, Alabama john To Kill a Mockingbird, Invisible Man abel Lord of the Flies julia Alabama I tried creating 2 dfs from and then merging but the results are never accurate. Anyone know a more efficient way to do this? Current code not working: from pathlib import Path import pandas as pd file1 = Path.cwd() / "./bookgrid.xlsx" df1 = pd.read_excel(file1) df2 = pd.read_excel(file1) ##Perfrom the Vlookup Merge merge = pd.merge(df1, df2, how="left") merge.to_excel("./results.xlsx")
You need to split, explode, groupby.agg: (df.assign(Owner=lambda d: d['Owner'].str.split(';')) .explode('Owner') .groupby('Owner', as_index=False, sort=False).agg(', '.join) ) NB. if you need the plural form in the column headers, add .add_suffix('s') or .rename(columns={'Book': 'Books', 'Owner': 'Owners'}). Output: Owner Book 0 marry The Alchemist, Catcher in the Ry, Alabama 1 john To Kill a Mockingbird, Invisible Man 2 abel Lord of the Flies 3 julia Alabama
3
2
75,886,674
2023-3-30
https://stackoverflow.com/questions/75886674/how-to-compute-sentence-level-perplexity-from-hugging-face-language-models
I have a large collection of documents each consisting of ~ 10 sentences. For each document, I wish to find the sentence that maximises perplexity, or equivalently the loss from a fine-tuned causal LM. I have decided to use Hugging Face and the distilgpt2 model for this purpose. I have 2 problems when trying to do in an efficient (vectorized) fashion: The tokenizer required padding to work in batch mode, but when computing the loss on padded input_ids those pad tokens are contributing to the loss. So the loss of a given sentence depends on the length of the longest sentence in the batch which is clearly wrong. When I pass a batch of input IDs to the model and compute the loss, I get a scalar as it (mean?) pools across the batch. I instead need the loss per item, not the pooled one. I made a version that operates on a sentence by sentence basis and while correct, it is extremely slow (I want to process ~ 25m sentences total). Any advice? Minimal example below: # Init tokenizer = AutoTokenizer.from_pretrained("distilgpt2") tokenizer.pad_token = tokenizer.eos_token model = AutoModelForCausalLM.from_pretrained("clm-gpu/checkpoint-138000") segmenter = spacy.load('en_core_web_sm') # That's the part I need to vectorise, surely within a document (bsize ~ 10) # and ideally across documents (bsize as big as my GPU can handle) def select_sentence(sentences): """We pick the sentence that maximizes perplexity""" max_loss, best_index = 0, 0 for i, sentence in enumerate(sentences): encodings = tokenizer(sentence, return_tensors="pt") input_ids = encodings.input_ids loss = lm(input_ids, labels=input_ids).loss.item() if loss > max_loss: max_loss = loss best_index = i return sentences[best_index] for document in documents: sentences = [sentence.text.strip() for sentence in segmenter(document).sents] best_sentence = select_sentence(sentences) write(best_sentence)
If the goal is to compute perplexity and then select the sentences, there's a better way to do the perplexity computation without messing around with tokens/models. Install https://huggingface.co/spaces/evaluate-metric/perplexity: pip install -U evaluate Then: perplexity = evaluate.load("perplexity", module_type="metric") input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"] results = perplexity.compute(model_id='gpt2', add_start_token=False, predictions=input_texts) print(list(results.keys())) [out]: >>>['perplexities', 'mean_perplexity'] print(round(results["mean_perplexity"], 2)) >>>646.75 print(round(results["perplexities"][0], 2)) >>>32.25 Q: That's great but how do I use it for a custom model that can't be fetched with model_id=...? A: For that lets look under the hood, https://huggingface.co/spaces/evaluate-metric/perplexity/blob/main/perplexity.py This is how the code initialize the model: class Perplexity(evaluate.Metric): def _info(self): return evaluate.MetricInfo( module_type="metric", description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { "predictions": datasets.Value("string"), } ), reference_urls=["https://huggingface.co/docs/transformers/perplexity"], ) def _compute( self, predictions, model_id, batch_size: int = 16, add_start_token: bool = True, device=None, max_length=None ): ... model = AutoModelForCausalLM.from_pretrained(model_id) model = model.to(device) tokenizer = AutoTokenizer.from_pretrained(model_id) ... Argh, there's no support for local models! What if we do some simple changes to the code =) See Load a pre-trained model from disk with Huggingface Transformers class Perplexity(evaluate.Metric): def _info(self): return evaluate.MetricInfo( module_type="metric", description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { "predictions": datasets.Value("string"), } ), reference_urls=["https://huggingface.co/docs/transformers/perplexity"], ) def _compute( self, predictions, model_id, batch_size: int = 16, add_start_token: bool = True, device=None, max_length=None, local_file_only: bool = False ): ... model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=local_file_only) model = model.to(device) tokenizer = AutoTokenizer.from_pretrained(model_id, local_files_only=local_file_only) Technically, if you could load a local model that you can load with: AutoModelForCausalLM.from_pretrained("clm-gpu/checkpoint-138000", local_file_only=True) you can should be able the model_id as such after the code change: perplexity.compute(model_id="clm-gpu/checkpoint-138000", add_start_token=False, predictions=input_texts, local_file_only=True) Opened a pull-request: https://huggingface.co/spaces/evaluate-metric/perplexity/discussions/4
8
15
75,886,126
2023-3-30
https://stackoverflow.com/questions/75886126/how-to-filtering-pandas-dataframe-by-multiple-columns
I would like to get values from column n where values in subset of other columns is True. Example, the data frame: t, f = True, False data = [ [t, f, f, '1'], [f, f, f, '2'], [f, t, f, '3'], [f, f, t, '4'] ] df = pd.DataFrame(data, columns=list("abcn")) df as table a b c n 0 True False False 1 1 False False False 2 2 False True False 3 3 False False True 4 columns for search is a and b, and I wish to get records from n where these columns are True, what I tried: fcols = ("a", "b") df[df[[*fcols]] == t].dropna(axis=0, how='all') this is give me right records, but with Nan in the column n a b c n 0 True NaN NaN NaN 2 NaN True NaN NaN I'm feel that I'm more or less close to the solution, but ...
Use any to aggregate the booleans for your boolean indexing: fcols = ("a", "b") out = df[df[[*fcols]].eq(t).any(axis=1)]#.dropna(axis=0, how='all') # dropna not needed Output: a b c n 0 True False False 1 2 False True False 3 Intermediate indexing Series: df[[*fcols]].eq(t).any(axis=1) 0 True 1 False 2 True 3 False dtype: bool
3
3
75,883,361
2023-3-30
https://stackoverflow.com/questions/75883361/python-how-to-access-dataclass-properties-in-list-of-dataclasses
Using python 3.10.4 Hi all, I'm putting together a script where I'm reading a yaml file with k8s cluster info, and I'd like to treat the loaded yaml as dataclasses so I can reference them with . properties. Example yaml: account: 12345 clusters: - name: cluster_1 endpoint: https://cluster_2 certificate: abcdef - name: cluster_1 endpoint: https://cluster_2 certificate: abcdef And here's my script for loading and accessing it: import yaml from dataclasses import dataclass @dataclass class ClusterInfo: _name: str _endpoint: str _certificate: str @dataclass class AWSInfo: _account: int _clusters: list[ClusterInfo] clusters = yaml.safe_load(open('D:\git\clusters.yml', 'r')) a = AWSInfo( _account=clusters['account'], _clusters=clusters['clusters'] ) print(a._account) #prints 12345 print(a._clusters) #prints the dict of both clusters print(a._clusters[0]) #prints the dict of the first cluster #These prints fails with AttributeError: 'dict' object has no attribute '_endpoint' print(a._clusters[0]._endpoint) for c in a._clusters: print(c._endpoint) So my question is: What am I doing wrong on the last prints? How can I access the properties of each member in a dataclass array of dataclass objects?
The dataclasses module doesn't provide built-in support for this use case, i.e. loading YAML data to a nested class model. In such a scenario, I would turn to a ser/de library such as dataclass-wizard, which provides OOTB support for (de)serializing YAML data, via the PyYAML library. Disclaimer: I am the creator and maintener of this library. Step 1: Generate a Dataclass Model Note: I will likely need to make this step easier for generating a dataclass model for YAML data. Perhaps worth creating an issue to look into as time allows. Ideally, usage is from the CLI, however since we have YAML data, it is tricky, because the utility tool expects JSON. So easiest to do this in Python itself, for now: from json import dumps # pip install PyYAML dataclass-wizard from yaml import safe_load from dataclass_wizard.wizard_cli import PyCodeGenerator yaml_string = """ account: 12345 clusters: - name: cluster_1 endpoint: https://cluster_2 certificate: abcdef - name: cluster_1 endpoint: https://cluster_2 certificate: abcdef """ py_code = PyCodeGenerator(experimental=True, file_contents=dumps(safe_load(yaml_string))).py_code print(py_code) Prints: from __future__ import annotations from dataclasses import dataclass from dataclass_wizard import JSONWizard @dataclass class Data(JSONWizard): """ Data dataclass """ account: int clusters: list[Cluster] @dataclass class Cluster: """ Cluster dataclass """ name: str endpoint: str certificate: str Step 2: Use Generated Dataclass Model, alongside YAMLWizard Contents of my_file.yml: account: 12345 clusters: - name: cluster_1 endpoint: https://cluster_5 certificate: abcdef - name: cluster_2 endpoint: https://cluster_7 certificate: xyz Python code: from __future__ import annotations from dataclasses import dataclass from pprint import pprint from dataclass_wizard import YAMLWizard @dataclass class Data(YAMLWizard): account: int clusters: list[Cluster] @dataclass class Cluster: name: str endpoint: str certificate: str data = Data.from_yaml_file('./my_file.yml') pprint(data) for c in data.clusters: print(c.endpoint) Result: Data(account=12345, clusters=[Cluster(name='cluster_1', endpoint='https://cluster_5', certificate='abcdef'), Cluster(name='cluster_2', endpoint='https://cluster_7', certificate='xyz')]) https://cluster_5 https://cluster_7
3
2
75,879,765
2023-3-29
https://stackoverflow.com/questions/75879765/this-account-is-not-available-unable-to-switch-user-in-python-alpine-docker-con
I have a simple Dockerfile FROM python:3.10-alpine # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set arguments ARG USERNAME=jpg ARG USER_DIR=/home/$USERNAME ARG WORK_DIR=$USER_DIR/app # Creating a non-root user RUN adduser -S $USERNAME # Switching the user USER $USERNAME # Create a new directory to keep the project files RUN mkdir $WORK_DIR # Copy local contents into container COPY ./ $WORK_DIR # Setting newly created directory as PWD WORKDIR $WORK_DIR # Adding user's bin path to `PATH` variable ENV PATH "$PATH:$USER_DIR/.local/bin" # Installing pip packages RUN pip install pip -U I built the image using following command docker build . -t test-img:latest After the successfull image build, run the image using docker run -i -t test-img:latest python This gave me an interactive shell, as expected. Also, I tried to pull the user info using getuser(...) function as well Python 3.10.10 (main, Mar 14 2023, 03:01:12) [GCC 12.2.1 20220924] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import getpass >>> getpass.getuser() 'jpg' >>> Then, I moved to another terminal and logged in to the same container as root user. After logged-in, tried to switch the user to jpg (which is defined within the Dockerfile) $ docker exec -it -u root f6dc515bca29 sh /home/jpg/app # su - jpg This account is not available /home/jpg/app # su - "jpg" This account is not available /home/jpg/app # su -l "jpg" This account is not available /home/jpg/app # su -l jpg This account is not available /home/jpg/app # Question How can I switch the user to jpg (or any non-root user) in an alpine-based container from root? Note: It is mandatory to log in as root (-u root) in an exec session because this is to simulate a situation of AWS Fargate containers.
You're getting the This account is not available message because running adduser -S explicitly sets the shell for the account to /sbin/nologin (because you've asked for a system account with -S, the assumption is you don't expect interactive logins for this user). You can explicitly set the shell for the named user: / # adduser -S -s /bin/sh jpg / # su - jpg 710ed667ddb2:~$ whoami jpg ...or, as @tripleee suggests, just drop the -S from your adduser invocation and create a normal user; in this case, the shell will default to /bin/sh.
3
5
75,881,502
2023-3-29
https://stackoverflow.com/questions/75881502/how-can-i-reverse-direction-of-plotlys-colorbar-so-that-small-values-at-top-an
I'm currently using the colorbar on plotly to indicate the depths at which underwater SONAR receivers have been placed. Currently, the colorbar looks like this: However, I think it would make more sense if the bigger values, which indicate greater depth, should be at the bottom and the smaller numbers, which indicate less depth (i.e. the device has been placed closer to surface) should be at the top, but don't know how to do this. The code I've used to create the graph and colorbar consists of the two dictionaries (one specifying data, the other specifying layout). import plotly.offline as off import _tkinter from matplotlib import pyplot as plt from matplotlib import ticker from matplotlib.dates import drange ... data = [ dict( lat = lat_array, lon = lon_array, marker = dict( color = log_depth_array, size = 6, colorbar = dict( title = 'Log Depth', thickness = 10, titleside = "right", outlinecolor = "rgba(68, 68, 68, 0)", ticks = "outside", ticklen = 3, showticksuffix = "last", ticksuffix = " log(meters, 10)", dtick = .1 ), ), mode = 'markers', text = mouseover_text, type = 'scattergeo' ) ] layout = dict( geo = dict( showframe = True, framewidth = 25, scope = 'north america', showland = True, landcolor = "rgb(212, 212, 212)", showocean = True, oceancolor = "rgb(200, 255, 255)", subunitcolor = "rgb(0,0,0)", resolution = 50, projection = dict( type = 'robinson', rotation = dict( lon = -100 ) ), lonaxis = dict( showgrid = True, gridwidth = 0.5, range= [ lon_min-.4, lon_max+.4 ], dtick = 5 ), lataxis = dict ( showgrid = True, gridwidth = 0.5, range= [ lat_min-.4, lat_max+.4 ], dtick = 5 ) ), ) fig = { 'data':data, 'layout':layout } off.iplot(fig) What argument should I add (probably to the colorbar dictionary in the data dictionary) to have the numbers representing greater depth at the bottom of the colorbar?
You can reverse the colorscale, then hardcode the tickvals by passing tickvals = [1, 1.1, ... 3.4], and make the ticktext the opposite: ticktext = ['3.4', '3.3', ... '1']. This will also require you to manually add the text " log(meters, 10)" to the topmost tick. I am not sure why, but there's this strange behavior where the tickvals and ticktext are getting cut off at the top and bottom – you may need to adjust some of the tick starting and ending values. It may have to do with the default padding for colorbars, or perhaps I missed something. import plotly.offline as off import _tkinter from matplotlib import pyplot as plt from matplotlib import ticker from matplotlib.dates import drange import numpy as np import pandas as pd # use some sample data df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv') lat_array, lon_array = df['lat'], df['long'] lat_min, lon_min = min(lat_array), min(lon_array) lat_max, lon_max = max(lat_array), max(lon_array) np.random.seed(42) log_depth_array = np.random.uniform(0,3.3,size=len(df)) tickvals = np.arange(1-0.2,3.5,0.1) ticktext = [str(f"{val:.1f}") for val in tickvals[::-1]] ticktext[-3] = ticktext[-3] + " log(meters, 10)" data = [ dict( lat = lat_array, lon = lon_array, marker = dict( color = log_depth_array, colorscale = 'viridis_r', size = 6, colorbar = dict( title = 'Log Depth', # colorscale = "viridis_r", thickness = 10, titleside = "right", outlinecolor = "rgba(68, 68, 68, 0)", ticks = "outside", tickmode = "array", tickvals = tickvals, ticktext = ticktext, ticklen = 3, ), ), mode = 'markers', # text = mouseover_text, type = 'scattergeo' ) ] layout = dict( geo = dict( showframe = True, framewidth = 25, scope = 'north america', showland = True, landcolor = "rgb(212, 212, 212)", showocean = True, oceancolor = "rgb(200, 255, 255)", subunitcolor = "rgb(0,0,0)", resolution = 50, projection = dict( type = 'robinson', rotation = dict( lon = -100 ) ), lonaxis = dict( showgrid = True, gridwidth = 0, range= [ lon_min-.4, lon_max+.4 ], dtick = 5 ), lataxis = dict ( showgrid = True, gridwidth = 0, range= [ lat_min-.4, lat_max+.4 ], dtick = 5 ) ), ) fig = { 'data':data, 'layout':layout } off.iplot(fig)
5
2
75,881,339
2023-3-29
https://stackoverflow.com/questions/75881339/aggregate-2-subsets-of-a-dataframe-keep-original-index-use-the-first-subset
I have a dataset as such: df0 = (pd.DataFrame({'year_minor_renovation': ['2023', '2025', np.nan, '2026'], 'year_intermediate_renovation': [np.nan, '2025', '2027', '2030'], 'year_major_renovation': ['2030', np.nan, np.nan, np.nan], 'costs_minor_renovation': [1000, 3000, np.nan, 2000], 'costs_intermediate_renovation': [np.nan, 5000, 5000, 10000], 'costs_major_renovation': [75000, np.nan, np.nan, np.nan]})) year_minor_renovation year_intermediate_renovation year_major_renovation costs_minor_renovation costs_intermediate_renovation costs_major_renovation 0 2023 NaN 2030 1000.0 NaN 75000.0 1 2025 2025 NaN 3000.0 5000.0 NaN 2 NaN 2027 NaN NaN 5000.0 NaN 3 2026 2030 NaN 2000.0 10000.0 NaN Each line represents a building to renovate. It can be seen as two concatenated subsets with the same index: Left half df.iloc[:, :3] for the years between 2023 and 2030 when one or multiple renovations need to be done on a specific building (the index) Right half df.iloc[:, 3:] is the costs corresponding What I want Some buildings will need different renovation types at different years (ex: df.iloc[[1]]). I need to agreggate new columns, one per year, with the costs per building, independently of what the type of renovation is. (pd.DataFrame({'2023': [1000, np.nan, np.nan, np.nan], '2024': [np.nan, np.nan, np.nan, np.nan], '2025': [np.nan, 8000, np.nan, np.nan], '2026': [np.nan, np.nan, np.nan, 2000], '2027': [np.nan, np.nan, 5000, np.nan], '2028': [np.nan, np.nan, np.nan, np.nan], '2029': [np.nan, np.nan, np.nan, np.nan], '2030': [75000, np.nan, 5000, 10000]})) 2023 2024 2025 2026 2027 2028 2029 2030 0 1000.0 NaN NaN NaN NaN NaN NaN 75000.0 1 NaN NaN 8000.0 NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN 5000.0 NaN NaN 5000.0 3 NaN NaN NaN 2000.0 NaN NaN NaN 10000.0 What I tried I tried to write a groupby function to create those new columns, but even if the result gives some data I'll need later, it's some kind of too much of a synthesis for what I want at that point: def costs_per_year(df): dfs = [] for i in ['year_minor_renovation', 'year_intermediate_renovation', 'year_major_renovation']: j = 'costs' + str(i[4:]) df_ = (df.groupby(i) .agg({j : 'sum' }) .reset_index() .rename({i:'year'}, axis =1) ) dfs.append(df_) # merge the dataframes merged_df = dfs[0] for df_ in dfs[1:]: merged_df = merged_df.merge(df_, on='year', how='outer') merged_df = (merged_df .set_index('year') .transpose() .reset_index() ) return merged_df year index 2023 2025 2026 2027 2030 0 costs_minor_renovation 1000.0 3000.0 2000.0 NaN NaN 1 costs_intermediate_renovation NaN 5000.0 NaN 5000.0 10000.0 2 costs_major_renovation NaN NaN NaN NaN 750000.0
You can use pd.wide_to_long: out = (pd.wide_to_long(df0.reset_index(), stubnames=['year', 'costs'], i='index', j='var', sep='_', suffix='.*') .dropna().astype({'year': int}) .pivot_table(index='index', columns='year', values='costs', aggfunc='sum') .rename_axis(index=None, columns=None)) out = out.reindex(columns=range(out.columns.min(), out.columns.max()+1)) Output: >>> out 2023 2024 2025 2026 2027 2028 2029 2030 0 1000.0 NaN NaN NaN NaN NaN NaN 75000.0 1 NaN NaN 8000.0 NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN 5000.0 NaN NaN NaN 3 NaN NaN NaN 2000.0 NaN NaN NaN 10000.0 Step by step to better understanding the transformation: # Step 1: flatten your dataframe >>> out = out = pd.wide_to_long(df0.reset_index(), stubnames=['year', 'costs'], i='index', j='var', sep='_', suffix='.*') year costs index var 0 minor_renovation 2023 1000.0 1 minor_renovation 2025 3000.0 2 minor_renovation NaN NaN 3 minor_renovation 2026 2000.0 0 intermediate_renovation NaN NaN 1 intermediate_renovation 2025 5000.0 2 intermediate_renovation 2027 5000.0 3 intermediate_renovation 2030 10000.0 0 major_renovation 2030 75000.0 1 major_renovation NaN NaN 2 major_renovation NaN NaN 3 major_renovation NaN NaN # Step 2: cast year to int >>> out = out.dropna().astype({'year': int}) year costs index var 0 minor_renovation 2023 1000.0 1 minor_renovation 2025 3000.0 3 minor_renovation 2026 2000.0 1 intermediate_renovation 2025 5000.0 2 intermediate_renovation 2027 5000.0 3 intermediate_renovation 2030 10000.0 0 major_renovation 2030 75000.0 # Step 3: reshape your dataframe >>> out = out.pivot_table(index='index', columns='year', values='costs', aggfunc='sum') year 2023 2025 2026 2027 2030 index 0 1000.0 NaN NaN NaN 75000.0 1 NaN 8000.0 NaN NaN NaN 2 NaN NaN NaN 5000.0 NaN 3 NaN NaN 2000.0 NaN 10000.0 # Step 4: rename axis >>> out = out.rename_axis(index=None, columns=None) 2023 2025 2026 2027 2030 0 1000.0 NaN NaN NaN 75000.0 1 NaN 8000.0 NaN NaN NaN 2 NaN NaN NaN 5000.0 NaN 3 NaN NaN 2000.0 NaN 10000.0 # Step 5: add missing columns >>> out = out.reindex(columns=range(out.columns.min(), out.columns.max()+1)) 2023 2024 2025 2026 2027 2028 2029 2030 0 1000.0 NaN NaN NaN NaN NaN NaN 75000.0 1 NaN NaN 8000.0 NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN 5000.0 NaN NaN NaN 3 NaN NaN NaN 2000.0 NaN NaN NaN 10000.0
4
4
75,874,050
2023-3-29
https://stackoverflow.com/questions/75874050/check-whether-boolean-column-contains-only-true-values
Working in Databricks, I've got a dataframe which looks like this: columns = ["a", "b", "c"] data = [(True, True, True), (True, True, True), (True, False, True)] df = spark.createDataFrame(data).toDF(*columns) df.display() I'd like to select only those columns of the dataframe in which not all values are True. In pandas, I would use df['a'].all() to check whether all values of column "a" are True. Unfortunately, I don't find an equivalent in PySpark. I have found a solution for the problem, but it seems much too complicated: df.select(*[column for column in df.columns if df.select(column).distinct().collect() != spark.createDataFrame([True], 'boolean').toDF(column).collect()]) The solution returns what I want: Is there an easier way of doing this in PySpark?
Here is one approach which follows a similar operational model to that of pandas def is_all(c): return (F.sum(F.col(c).astype('int')) == F.count(c)).alias(c) # create a boolean mask, # for e.g in pandas this would similar to df.all(axis=0) mask = df.agg(*[is_all(c) for c in columns]).collect()[0] # Use the boolean mask to filter the columns result = df.select(*[c for c in columns if not mask[c]]) Result +-----+ | b| +-----+ | true| | true| |false| +-----+
4
1
75,847,922
2023-3-26
https://stackoverflow.com/questions/75847922/how-to-do-if-and-else-in-polars-group-by-context
Update: The vectorization rules have since been formalized. The query runs as expected without warning. For a dataframe, the goal is to have the mean of a column - a group_by another column - b given the first value of a in the group is not null, if it is, just return null. The sample dataframe df = pl.DataFrame({"a": [None, 1, 2, 3, 4], "b": [1, 1, 2, 2, 2]}) I tried something like df.group_by("b").agg( pl.when(pl.col("a").first().is_null()).then(None).otherwise(pl.mean("a")) ) The results are as expected but get a warning saying when may not be guaranteed to do its job in group_by context. The predicate 'col("a").first().is_null()' in 'when->then->otherwise' is not a valid aggregation and might produce a different number of rows than the groupby operation would. This behavior is experimental and may be subject to change shape: (2, 2) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ b ┆ literal β”‚ β”‚ --- ┆ --- β”‚ β”‚ i64 ┆ f64 β”‚ β•žβ•β•β•β•β•β•ͺ═════════║ β”‚ 1 ┆ null β”‚ β”‚ 2 ┆ 3.0 β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ May I know why and what could be a better alternative way to do if-else in group_by?
You can use: pl.col("a").is_null().first() instead of: pl.col("a").first().is_null() If we look at both approaches: df.group_by("b", maintain_order=True).agg( pl.col("a"), pl.col("a").is_not_null().alias("yes"), pl.col("a").first().is_not_null().alias("no"), ) shape: (2, 4) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ b ┆ a ┆ yes ┆ no β”‚ β”‚ --- ┆ --- ┆ --- ┆ --- β”‚ β”‚ i64 ┆ list[i64] ┆ list[bool] ┆ bool β”‚ β•žβ•β•β•β•β•β•ͺ═══════════β•ͺ════════════════════β•ͺ═══════║ β”‚ 1 ┆ [null, 1] ┆ [false, true] ┆ false β”‚ β”‚ 2 ┆ [2, 3, 4] ┆ [true, true, true] ┆ true β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ My understanding is, that in the no case, only null and 2 are passed to .is_not_null() - the rest of the inputs have been "silently discarded". polars knows a has lengths of 2 and 3 and expects "boolean masks" of the same length. We can take the .first() value of yes which has the same end result: df.group_by("b", maintain_order=True).agg( pl.col("a"), pl.col("a").is_not_null().first().alias("yes"), pl.col("a").first().is_not_null().alias("no"), ) shape: (2, 4) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ b ┆ a ┆ yes ┆ no β”‚ β”‚ --- ┆ --- ┆ --- ┆ --- β”‚ β”‚ i64 ┆ list[i64] ┆ bool ┆ bool β”‚ β•žβ•β•β•β•β•β•ͺ═══════════β•ͺ═══════β•ͺ═══════║ β”‚ 1 ┆ [null, 1] ┆ false ┆ false β”‚ β”‚ 2 ┆ [2, 3, 4] ┆ true ┆ true β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ But now all of the inputs have been passed to .is_not_null() and the length check passes.
4
4
75,818,269
2023-3-23
https://stackoverflow.com/questions/75818269/polars-fill-nulls-with-the-only-valid-value-within-each-group
Each group only has one valid or not_null value in a random row. How do you fill each group with that value? import polars as pl data = { 'group': ['1', '1', '1', '2', '2', '2', '3', '3', '3'], 'col1': [1, None, None, None, 3, None, None, None, 5], 'col2': ['a', None, None, None, 'b', None, None, None, 'c'], 'col3': [False, None, None, None, True, None, None, None, False] } df = pl.DataFrame(data) shape: (9, 4) β”Œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ group ┆ col1 ┆ col2 ┆ col3 β”‚ β”‚ --- ┆ --- ┆ --- ┆ --- β”‚ β”‚ str ┆ i64 ┆ str ┆ bool β”‚ β•žβ•β•β•β•β•β•β•β•ͺ══════β•ͺ══════β•ͺ═══════║ β”‚ 1 ┆ 1 ┆ a ┆ false β”‚ β”‚ 1 ┆ null ┆ null ┆ null β”‚ β”‚ 1 ┆ null ┆ null ┆ null β”‚ β”‚ 2 ┆ null ┆ null ┆ null β”‚ β”‚ 2 ┆ 3 ┆ b ┆ true β”‚ β”‚ 2 ┆ null ┆ null ┆ null β”‚ β”‚ 3 ┆ null ┆ null ┆ null β”‚ β”‚ 3 ┆ null ┆ null ┆ null β”‚ β”‚ 3 ┆ 5 ┆ c ┆ false β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ Desired output: shape: (9, 4) β”Œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ group ┆ col1 ┆ col2 ┆ col3 β”‚ β”‚ --- ┆ --- ┆ --- ┆ --- β”‚ β”‚ str ┆ i64 ┆ str ┆ bool β”‚ β•žβ•β•β•β•β•β•β•β•ͺ══════β•ͺ══════β•ͺ═══════║ β”‚ 1 ┆ 1 ┆ a ┆ false β”‚ β”‚ 1 ┆ 1 ┆ a ┆ false β”‚ β”‚ 1 ┆ 1 ┆ a ┆ false β”‚ β”‚ 2 ┆ 3 ┆ b ┆ true β”‚ β”‚ 2 ┆ 3 ┆ b ┆ true β”‚ β”‚ 2 ┆ 3 ┆ b ┆ true β”‚ β”‚ 3 ┆ 5 ┆ c ┆ false β”‚ β”‚ 3 ┆ 5 ┆ c ┆ false β”‚ β”‚ 3 ┆ 5 ┆ c ┆ false β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ In pandas, I can do the following for each column import pandas as pd df = pd.DataFrame(data) df.col1 = df.groupby('group').col.apply(lambda x: x.ffill().bfill()) How do you do this in polars, ideally with a window function (.over()) ?
The immediate way to do exactly what you asked is (and it looks the most like your pandas approach): df.with_columns(pl.exclude('group').forward_fill().backward_fill().over('group')) using pl.all() instead of pl.exclude('group') also works but it'll save some theoretical time by not making it look through the group column for the fills. If there's a list of columns you want to do this to (as opposed to all but group) then you can replace the pl.exclude with a generator or list comprehension cols=['col1','col2','col3'] df.with_columns(pl.col(x).forward_fill().backward_fill().over('group') for x in cols) You can even use regex in pl.col as long as you use the ^ and $ anchor. df.with_columns(pl.col("^col\d$").forward_fill().backward_fill().over('group')) Another approach besides forward/backward fills: df.with_columns(pl.col("^col\d$").drop_nulls().first().over('group')) If the first looks a little weird it's because the drop_nulls is going to return a different number of rows than the original df which will cause an error. If the expression is an aggregation (like sum, min, max, etc) then it doesn't complain about getting a different number of rows and, instead, just propagates that answer to all the rows. In this case first is the aggregation which just means the first thing it sees. Since the filter is only returning one thing we just need a way to tell it to propagate that. The different column selection tricks work in this approach too but I'll spare the reader the extra copy/paste Final note: if your next step is to take unique then you should just do it as a df.group_by to start with df \ .group_by('group', maintain_order=True) \ .agg(pl.col("^col\d$").drop_nulls().first())
7
7
75,808,628
2023-3-22
https://stackoverflow.com/questions/75808628/python-polars-group-by-and-indexing-for-time-series-data
I have been developing some codes in pandas, yet I found the executions in pandas are a bit too slow. I then stumbled upon polars, which claims to be blazingly fast and much faster than pandas. I have thus been trying to transfer my existing codes to polars. I am currently working on some stock data, where I have to find out the minimum price of the previous n transaction days. Note that here the transaction dates are discontinuous, since there are Saturdays, Sundays and public holidays. The problem is that polars do not know how to find the previous transaction days, instead polars find the actual previous days. Let's say now we have a DataFrame, and n = 3: df = pl.from_repr(""" β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ Date ┆ Price β”‚ β”‚ --- ┆ --- β”‚ β”‚ date ┆ i64 β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════║ β”‚ 2023-01-01 ┆ 1 β”‚ β”‚ 2023-01-02 ┆ 2 β”‚ β”‚ 2023-01-03 ┆ 3 β”‚ β”‚ 2023-01-05 ┆ 4 β”‚ β”‚ 2023-01-10 ┆ 5 β”‚ β”‚ 2023-01-11 ┆ 6 β”‚ β”‚ 2023-01-12 ┆ 7 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ """) The expected output I get from the following codes using pandas: df.to_pandas().Price.rolling(3).min() 0 NaN 1 NaN 2 1.0 3 2.0 4 3.0 5 4.0 6 5.0 Name: Price, dtype: float64 However, when using polars, since there are no indices, the group by function works differently. It sets the window based on the actual physical dates(continuous) instead of the transaction dates(discontinuous, pandas can handle that with indices), which yields the following results: β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ Date ┆ Price β”‚ β”‚ --- ┆ --- β”‚ β”‚ date ┆ i64 β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════║ β”‚ 2023-01-01 ┆ 1 β”‚ β”‚ 2023-01-02 ┆ 1 β”‚ β”‚ 2023-01-03 ┆ 1 β”‚ β”‚ 2023-01-05 ┆ 3 β”‚ β”‚ 2023-01-10 ┆ 5 β”‚ β”‚ 2023-01-11 ┆ 5 β”‚ β”‚ 2023-01-12 ┆ 5 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ with the following code: df.rolling("Date", period="3d").agg(pl.col("Price").min()) Is there a way to get the desired result, i.e. same as the one in pandas, with the polars library? (Should I manually create an index column???) Or is switching over to polars a bad idea for data like this, since polars advocates for the idea of no indices?
Polars has dedicated .rolling_* expressions, e.g. .rolling_min() df.with_columns(roll = pl.col("Price").rolling_min(3)) shape: (7, 3) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β” β”‚ Date ┆ Price ┆ roll β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ date ┆ i64 ┆ i64 β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════β•ͺ══════║ β”‚ 2023-01-01 ┆ 1 ┆ null β”‚ β”‚ 2023-01-02 ┆ 2 ┆ null β”‚ β”‚ 2023-01-03 ┆ 3 ┆ 1 β”‚ β”‚ 2023-01-05 ┆ 4 ┆ 2 β”‚ β”‚ 2023-01-10 ┆ 5 ┆ 3 β”‚ β”‚ 2023-01-11 ┆ 6 ┆ 4 β”‚ β”‚ 2023-01-12 ┆ 7 ┆ 5 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”˜ For the frame level rolling - you can add an index column as you suggested. It's a bit different as we have to use the "format language" to specify the period - instead of a numeric window size. (df.with_row_index() .rolling("index", period="3i") .agg(pl.col("Price").min()) ) shape: (7, 2) β”Œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ index ┆ Price β”‚ β”‚ --- ┆ --- β”‚ β”‚ u32 ┆ i64 β”‚ β•žβ•β•β•β•β•β•β•β•ͺ═══════║ β”‚ 0 ┆ 1 β”‚ β”‚ 1 ┆ 1 β”‚ β”‚ 2 ┆ 1 β”‚ β”‚ 3 ┆ 2 β”‚ β”‚ 4 ┆ 3 β”‚ β”‚ 5 ┆ 4 β”‚ β”‚ 6 ┆ 5 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ You would also need to combine the result with the original frame, generally with a .join()
3
2
75,850,086
2023-3-26
https://stackoverflow.com/questions/75850086/tensorflow-results-are-not-reproducible-despite-using-tf-random-set-seed
According to a tutorial on Tensorflow I am following, the following code is supposed to give reproducible results, so one can check if the exercise is done correctly. Tensorflow version is 2.11.0. import tensorflow as tf import numpy as np class MyDenseLayer(tf.keras.layers.Layer): def __init__(self, n_output_nodes): super(MyDenseLayer, self).__init__() self.n_output_nodes = n_output_nodes def build(self, input_shape): d = int(input_shape[-1]) # Define and initialize parameters: a weight matrix W and bias b # Note that parameter initialization is random! self.W = self.add_weight("weight", shape=[d, self.n_output_nodes]) # note the dimensionality self.b = self.add_weight("bias", shape=[1, self.n_output_nodes]) # note the dimensionality print("Weight matrix is {}".format(self.W)) print("Bias vector is {}".format(self.b)) def call(self, x): z = tf.add(tf.matmul(x, self.W), self.b) y = tf.sigmoid(z) return y # Since layer parameters are initialized randomly, we will set a random seed for reproducibility tf.random.set_seed(1) layer = MyDenseLayer(3) layer.build((1,2)) print(layer.call(tf.constant([[1.0,2.0]], tf.float32, shape=(1,2)))) However, results are different on each run as the weight and bias values in build get different values every time. It seems to me that tf.random.set_seed has no effect at all, at least it is not generating the reproducible results it should. Full output of two runs: treuss@foo:~/python/tensorflow$ python lab1_1.py 2023-03-26 21:31:16.896212: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2023-03-26 21:31:18.021094: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:18.023462: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:18.023634: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:18.023976: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2023-03-26 21:31:18.024324: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:18.024471: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:18.024617: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:18.455771: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:18.455946: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:18.456125: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:18.456257: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1613] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 4656 MB memory: -> device: 0, name: NVIDIA GeForce GTX 1060 6GB, pci bus id: 0000:01:00.0, compute capability: 6.1 Weight matrix is <tf.Variable 'weight:0' shape=(2, 3) dtype=float32, numpy= array([[ 0.9970403 , -0.672126 , -0.00545013], [ 0.5411365 , -0.8570848 , 0.5970814 ]], dtype=float32)> Bias vector is <tf.Variable 'bias:0' shape=(1, 3) dtype=float32, numpy=array([[-0.9100063, 0.7671951, -0.9659226]], dtype=float32)> tf.Tensor([[0.7630197 0.16532896 0.5554683 ]], shape=(1, 3), dtype=float32) treuss@foo:~/python/tensorflow$ python lab1_1.py 2023-03-26 21:31:21.245548: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2023-03-26 21:31:22.372605: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:22.375021: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:22.375175: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:22.375521: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2023-03-26 21:31:22.375840: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:22.375960: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:22.376067: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:22.801768: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:22.801935: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:22.802112: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2023-03-26 21:31:22.802213: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1613] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 4656 MB memory: -> device: 0, name: NVIDIA GeForce GTX 1060 6GB, pci bus id: 0000:01:00.0, compute capability: 6.1 Weight matrix is <tf.Variable 'weight:0' shape=(2, 3) dtype=float32, numpy= array([[ 0.72208846, 0.34211397, 0.04753423], [ 0.48018157, 0.9557345 , -0.19968122]], dtype=float32)> Bias vector is <tf.Variable 'bias:0' shape=(1, 3) dtype=float32, numpy=array([[ 0.31122065, -0.81101143, -0.7763765 ]], dtype=float32)> tf.Tensor([[0.8801311 0.80885255 0.24449256]], shape=(1, 3), dtype=float32)
You see this behaviour because after TF 2.7, Keras switched to tf.random.uniform for the tf.keras.initializers.xxx, and glorot_uniform is used in self.add_weight by default. Long story short, the best thing you can do is to set seeds using tf.keras.utils.set_random_seed() or use any version below 2.7.0 and set it using tf.random.set_seed(). There was a related discussion about this here. One can also check this official guide for reproducibility.
3
5
75,867,644
2023-3-28
https://stackoverflow.com/questions/75867644/how-to-return-pydantic-object-with-a-specific-http-response-code-in-fastapi
I have an endpoint which returns a Pydantic object. However, I would like a response code other than 200 in some cases (for example if my service in not healthy). How can I achieve that with FastAPI? class ServiceHealth(BaseModel): http_ok: bool = True database_ok: bool = False def is_everything_ok(self) -> bool: return self.http_ok and self.database_ok @router.get("/health") def health() -> ServiceHealth: return ServiceHealth()
You can return a Response Directly. For example, you can use JSONResponse and set the status manually: @router.get("/health") async def health() -> ServiceHealth: response = ServiceHealth() if response.is_everything_ok(): return JSONResponse(content=response.dict(), status_code=200) return JSONResponse(content=response.dict(), status_code=500) Also, there is a handy status.py which you can import from fastapi that contains all the available status codes: from fastapi import status @router.get("/health") async def health() -> ServiceHealth: response = ServiceHealth() if response.is_everything_ok(): return JSONResponse(content=response.dict(), status_code=status.HTTP_200_OK) return JSONResponse(content=response.dict(), status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
3
1
75,848,964
2023-3-26
https://stackoverflow.com/questions/75848964/create-a-type-of-pair-tensor-from-cartesian-product-of-1d-array-with-itself
I have an array of strings, like arr = np.array(['A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']) I want to create a torch tensor matrix with the type of pairs that will be created by cartesian product. So, the result would be a 8x8 tensor where: if the row == 'A' and column is col == 'B', then the value in a matrix is for example 1; if the row == 'B' and column is col == 'C', then the value in a matrix is for example 2, 0 otherwise (i.e. if row is the same as col). How can I achieve that? So far, I have tried to do something as follows: arr = np.array(['A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']) _, arr = np.unique(arr, return_inverse=True) arr = torch.tensor(arr) arr += 1 out = torch.cartesian_prod(arr, arr).reshape(8, 8, 2) out = out[:, :, 1] * out[:, :, 0] torch.where(torch.sqrt(out) == torch.sqrt(out).int(), 0, out) tensor([[0, 2, 2, 2, 3, 3, 3, 3], [2, 0, 0, 0, 6, 6, 6, 6], [2, 0, 0, 0, 6, 6, 6, 6], [2, 0, 0, 0, 6, 6, 6, 6], [3, 6, 6, 6, 0, 0, 0, 0], [3, 6, 6, 6, 0, 0, 0, 0], [3, 6, 6, 6, 0, 0, 0, 0], [3, 6, 6, 6, 0, 0, 0, 0]]) But it feels a bit clumsy (even the values are quite random and not 0, 1, 2...), so I wanted to hear other ideas.
Combine meshgrid and fancy indexing Comments on the published solution There are two flaws in the approach published in the original post. First, the square root of the product of two unequal numbers can be an integer. For example, the root of 1 * 4 is two which is an integer number. Therefore, zeros will be inserted as identifiers of pairs like (1, 4), (2, 8), (3, 12), ..., which was certainly not intended. Next, equal identifiers will be set for some different pairs. For example, we have the identifier 6 for pairs (1, 6) and (2, 3) in this model. To differentiate them, it is necessary to change the way the pair is identified. New solution Let's create a matrix of identifiers for all possible pairs based on range(number_of_pairs).reshape(...): import numpy as np data = np.array(['A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']) unique, codes = np.unique(data, return_inverse=True) n = len(unique) pairs_id = np.arange(n*n).reshape(n, n) # assign unique id's to each pair pairs_id = np.triu(pairs_id, k=1) # put 0 on the diagonal and below it pairs_id = pairs_id + pairs_id.T # mirror the upper triangular matrix # p.s. A hidden trick that is better expressed explicitly: # we can start the range from 0, because in this model # the very first element is inevitably removed by replacing with zero Now we have unique identifiers for each pair of initial unique values with the exception that the identifier is independent of the ordering of the pair, and for those pairs in which both values are equal, the identifier is zero. To get the desirable answer, we can use numpy.meshgrid instead of Cartesian product and Integer array indexing: left, right = np.meshgrid(codes, codes) answer = pairs_id[left, right] Summary code and output import numpy as np arr = np.array(['A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']) unique, codes = np.unique(arr, return_inverse=True) n = len(unique) pairs = np.arange(n*n).reshape(n, n) pairs = np.triu(pairs, k=1) pairs = pairs + pairs.T left, right = np.meshgrid(codes, codes) answer = pairs[left, right] print( f'{unique = }', f'{codes = }', f'{pairs = }', f'{answer = }', sep='\n' + '\N{Horizontal Line Extension}'*30 + '\n' ) Output: unique = array(['A', 'B', 'C'], dtype='<U1') ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ codes = array([0, 1, 1, 1, 2, 2, 2, 2]) ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ pairs = array([ [0, 1, 2], [1, 0, 5], [2, 5, 0]]) ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ answer = array([ [0, 1, 1, 1, 2, 2, 2, 2], [1, 0, 0, 0, 5, 5, 5, 5], [1, 0, 0, 0, 5, 5, 5, 5], [1, 0, 0, 0, 5, 5, 5, 5], [2, 5, 5, 5, 0, 0, 0, 0], [2, 5, 5, 5, 0, 0, 0, 0], [2, 5, 5, 5, 0, 0, 0, 0], [2, 5, 5, 5, 0, 0, 0, 0]])
4
1
75,842,787
2023-3-25
https://stackoverflow.com/questions/75842787/issues-with-saving-a-transparent-gif-using-pillow
I am using Python to create a program that can automatically make Pokemon gifs for me by using Sprite sheets from a Sprite repository. It combines animation, along with its shadow to create a sprite sheet that is then cut up into frames. The frames are assembled into GIFs which are then shown in the program, inside canvasses, so I know what to download. The GIFs look and function perfectly in the cavasses but when I use PIL and try to save the GIF it does this weird thing where it crops the frames so that the edges and the shadow of the frame are sometimes removed like it's unnecessarily clamping around the frame. As you can see in the code below, I have attempted just about everything I know. I could very well be missing something though. Please note that each frame is exactly the same size before they are saved and that even by resizing them, the issue remained. When each frame is exported on its own, it retains its original size, it only has an issue when it's trying to put all the frames together into the gif. def download_this(button, download_single_buttons): export_directory = config.get('Directory', 'export_directory') idx = download_single_buttons.index(button) starting_frame_index = idx * num_cols canvas_frames = frames[starting_frame_index: starting_frame_index + num_cols] canvas_frames = [ImageTk.getimage(f) for f in canvas_frames] durations = frame_duration_values[:num_cols] loop_value = 0 if loop_check_value.get() else 1 if loop_value == 0: filename = f"{export_directory}\{(this_poke.lower())}-{(animations.lower())}({directions[idx]}).gif" else: filename = f"{export_directory}\{(this_poke.lower())}-{(animations.lower())}_once({directions[idx]}).gif" canvas_frames[0].save(filename, format="GIF", append_images=canvas_frames[1:], save_all=True, loop=loop_value, transparency=0, disposal=[2] * len(canvas_frames), duration=durations, compress_level=0, save_local_palette=True, width=frame_width, height=frame_height) I will also attach the method of creating the frames: Example values for the arguments: 'anim_selected': .!toplevel.!toplevel This is the window that is used and thus added buttons/canvasses to. 'animations': 'Hop' This is the variable that changes based on what animation the user picks. 'search_poke_number': '0194' This is the numerical value that is used to identify the pokemon. 'this_poke': 'Quagsire' This is the english name for the pokemon and is used when saving the gif. def generate_gifs(anim_selected, animations, search_poke_number, this_poke, shadow_check_value): global photo_img, frames url = f'https://github.com/PMDCollab/SpriteCollab/blob/master/sprite/{int(search_poke_number[0]) + 1:04}/AnimData.xml?raw=true' response = requests.get(url, verify=False) root = ET.fromstring(response.content) for anim in root.findall('./Anims/Anim'): if anim.find('Name').text == animations: frame_width = int(anim.find('FrameWidth').text) frame_height = int(anim.find('FrameHeight').text) frame_duration_values = [int(dur.text) * 20 for dur in anim.findall('./Durations/Duration')] shadow_size = root.find('ShadowSize').text anim_url = f'https://github.com/PMDCollab/SpriteCollab/blob/master/sprite/{int(search_poke_number[0]) + 1:04}/{animations}-Anim.png?raw=true' response = requests.get(anim_url, verify=False) anim_img = Image.open(io.BytesIO(response.content)) if shadow_check_value is True: shadow_url = f'https://github.com/PMDCollab/SpriteCollab/blob/master/sprite/{int(search_poke_number[0]) + 1:04}/{animations}-Shadow.png?raw=true' response = requests.get(shadow_url, verify=False) shadow_img = Image.open(io.BytesIO(response.content)) shadow_arr = np.array(shadow_img) white = [255, 255, 255, 255] blue = [0, 0, 255, 255] green = [0, 255, 0, 255] red = [255, 0, 0, 255] black = [0, 0, 0, 255] transparent = [0, 0, 0, 0] colour_list = [white, green, red, blue] # Replace the colors with black or transparent based on shadow_size i = 0 while i <= 3: if i <= int(shadow_size) + 1: shadow_arr[(shadow_arr == colour_list[i]).all(axis=2)] = black else: shadow_arr[(shadow_arr == colour_list[i]).all(axis=2)] = transparent i += 1 shadow_img = Image.fromarray(shadow_arr) # Combine the images and merge them with the shadow image underneath merged_img = Image.alpha_composite(shadow_img, anim_img) else: merged_img = anim_img photo_img = ImageTk.PhotoImage(merged_img) # Calculate the number of columns and rows in the sprite sheet num_cols = photo_img.width() // frame_width num_rows = photo_img.height() // frame_height # Create a list of PhotoImage objects for each frame in the GIF frames = [None] * (num_rows * num_cols) frame_count = 0 for row in range(num_rows): for col in range(num_cols): x1 = col * frame_width y1 = row * frame_height x2 = x1 + frame_width y2 = y1 + frame_height cropped_img = merged_img.crop((x1, y1, x2, y2)) frame = ImageTk.PhotoImage(cropped_img) frames[frame_count] = frame frame_count += 1 # Create a list of directions in anti-clockwise order directions = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'] gifs = [] for direction in directions[:num_rows]: # Find the starting frame for this direction starting_frame_index = directions.index(direction) * num_cols # Get the frames for this direction gif_frames = frames[starting_frame_index: starting_frame_index + num_cols] # Create a gif from the frames gif = [] for frame in gif_frames: gif.append(frame) gifs.append(gif) frame_duration_values = frame_duration_values * num_rows canvases = [] for i, direction in enumerate(directions[:num_rows]): # Create a new canvas canvas = tk.Canvas(anim_selected, width=70, height=70) canvas.config(bg='#78acff') # Add the gif to the canvas canvas.anim_frames = gifs[i] canvas.anim_delays = frame_duration_values[starting_frame_index:starting_frame_index + num_cols] canvas.anim_index = 0 canvas.anim_after_id = None canvas.anim_running = True # Start the animation immediately # Create a function to animate the canvas def animate(canvas, frame_delays): # Get the current frame canvas.delete('all') frame = canvas.anim_frames[canvas.anim_index] # Update the canvas image canvas.create_image(70 / 2, 70 / 2, image=frame, anchor=tk.CENTER) # Increment the index canvas.anim_index += 1 if canvas.anim_index >= len(canvas.anim_frames): canvas.anim_index = 0 # Get the delay for the next frame next_frame_index = canvas.anim_index - 1 if canvas.anim_index - 1 < len(canvas.anim_frames) else 0 next_frame_delay = frame_delays[next_frame_index] # Schedule the next animation with the delay of the next frame canvas.anim_after_id = canvas.after(next_frame_delay, animate, canvas, frame_delays) # Add the canvas to the list canvases.append(canvas) # Start the animation animate(canvas, canvas.anim_delays) def change_directory(): # Open a folder selector dialog to select the export directory selected_directory = filedialog.askdirectory() # Update the export directory path if a directory is selected if selected_directory: export_directory = selected_directory # Save the export directory path to the configuration file config['Directory'] = {'export_directory': export_directory} with open(config_file_path, 'w') as f: config.write(f) def download_this(button, download_single_buttons): export_directory = config.get('Directory', 'export_directory') idx = download_single_buttons.index(button) starting_frame_index = idx * num_cols canvas_frames = frames[starting_frame_index: starting_frame_index + num_cols] canvas_frames = [ImageTk.getimage(f) for f in canvas_frames] durations = frame_duration_values[:num_cols] loop_value = 0 if loop_check_value.get() else 1 if loop_value == 0: filename = f"{export_directory}/{(this_poke.lower())}-{(animations.lower())}({directions[idx]}).gif" else: filename = f"{export_directory}/{(this_poke.lower())}-{(animations.lower())}({directions[idx]})-once.gif" canvas_frames[0].save(filename, append_images=canvas_frames[1:], save_all=True, loop=loop_value, transparency=0, disposal=2, duration=durations, compress_level=0, size=(frame_width, frame_height), background=0) def download_all(): export_directory = config.get('Directory', 'export_directory') for i, canvas in enumerate(canvases): idx = canvases.index(canvas) starting_frame_index = idx * num_cols canvas_frames = frames[starting_frame_index: starting_frame_index + num_cols] images = [ImageTk.getimage(f) for f in canvas_frames] durations = frame_duration_values[:num_cols] loop_value = 0 if loop_check_value.get() else 1 if loop_value == 0: filename = f"{export_directory}/{(this_poke.lower())}-{(animations.lower())}({directions[idx]}).gif" else: filename = f"{export_directory}/{(this_poke.lower())}-{(animations.lower())}_once({directions[idx]}).gif" images[0].save(filename, append_images=images[1:], save_all=True, loop=loop_value, transparency=0, disposal=[2] * len(images), duration=durations) download_single_buttons = [] directions_long = ['South', 'South East', 'East', 'North East', 'North', 'North West', 'West', 'South West'] for i, canvas in enumerate(canvases): row = i // 4 col = i % 4 canvas.grid(row=(row * 4) + 2, column=col, padx=5, pady=1) download_single_button = tk.Button(anim_selected, text='Download') download_single_button.config(width=8, height=1, bg='#78acff') download_single_button.grid(row=(row * 4) + 3, column=col, padx=5, pady=1) download_single_button.config( command=lambda button=download_single_button: download_this(button, download_single_buttons)) download_single_buttons.append(download_single_button) direction_label = tk.Label(anim_selected, text=directions_long[i]) direction_label.config(width=8, height=1, bg='#78acff') direction_label.grid(row=(row * 4) + 1, column=col, padx=5, pady=1) buffer = tk.Label(anim_selected, text=" ") buffer.grid(row=(row + 1) * 4, column=col, padx=5, pady=10) def my_upd(): print('Loop gif? :', loop_check_value.get()) loop_check_value = tk.BooleanVar() loop_check = tk.Checkbutton(anim_selected, text="Loop", variable=loop_check_value, onvalue=True, offvalue=False, command=my_upd) loop_check_value.set(True) if canvases.index(canvas) <= 0: loop_check.grid(row=0, column=0, padx=10, pady=10) else: download_all_button = tk.Button(anim_selected, text='Get All') download_all_button.config(width=8, height=1, bg='#78acff') download_all_button.grid(row=0, column=0, padx=10, pady=10) download_all_button.config(command=download_all) loop_check.grid(row=0, column=1, padx=10, pady=10) export_location = tk.Button(anim_selected, text='Export To') export_location.config(width=8, height=1, bg='#78acff') export_location.grid(row=0, column=3, padx=10, pady=10) export_location.config(command=change_directory) In theory, this should all give me a GIF like this: But instead I get a GIF like this: EDIT: So after trying for a few days it seems like it's something to do with the save function itself. Even if I make sure the files are the correct size they are changed when I try to save them as a gif together. Even saving the individual frames to a folder and assembling the gif from that results in the exact same issue. At this point, I'm just looking for an alternative/workaround.
In summary, the issue was that PIL struggles when creating gifs with frames that have transparency. The answer to my issue is the top voted answer here. Specifically the code chunk, which I will copy here: # This code adapted from https://github.com/python-pillow/Pillow/issues/4644 to resolve an issue # described in https://github.com/python-pillow/Pillow/issues/4640 # # There is a long-standing issue with the Pillow library that messes up GIF transparency by replacing the # transparent pixels with black pixels (among other issues) when the GIF is saved using PIL.Image.save(). # This code works around the issue and allows us to properly generate transparent GIFs. from typing import Tuple, List, Union from collections import defaultdict from random import randrange from itertools import chain from PIL.Image import Image class TransparentAnimatedGifConverter(object): _PALETTE_SLOTSET = set(range(256)) def __init__(self, img_rgba: Image, alpha_threshold: int = 0): self._img_rgba = img_rgba self._alpha_threshold = alpha_threshold def _process_pixels(self): """Set the transparent pixels to the color 0.""" self._transparent_pixels = set( idx for idx, alpha in enumerate( self._img_rgba.getchannel(channel='A').getdata()) if alpha <= self._alpha_threshold) def _set_parsed_palette(self): """Parse the RGB palette color `tuple`s from the palette.""" palette = self._img_p.getpalette() self._img_p_used_palette_idxs = set( idx for pal_idx, idx in enumerate(self._img_p_data) if pal_idx not in self._transparent_pixels) self._img_p_parsedpalette = dict( (idx, tuple(palette[idx * 3:idx * 3 + 3])) for idx in self._img_p_used_palette_idxs) def _get_similar_color_idx(self): """Return a palette index with the closest similar color.""" old_color = self._img_p_parsedpalette[0] dict_distance = defaultdict(list) for idx in range(1, 256): color_item = self._img_p_parsedpalette[idx] if color_item == old_color: return idx distance = sum(( abs(old_color[0] - color_item[0]), # Red abs(old_color[1] - color_item[1]), # Green abs(old_color[2] - color_item[2]))) # Blue dict_distance[distance].append(idx) return dict_distance[sorted(dict_distance)[0]][0] def _remap_palette_idx_zero(self): """Since the first color is used in the palette, remap it.""" free_slots = self._PALETTE_SLOTSET - self._img_p_used_palette_idxs new_idx = free_slots.pop() if free_slots else \ self._get_similar_color_idx() self._img_p_used_palette_idxs.add(new_idx) self._palette_replaces['idx_from'].append(0) self._palette_replaces['idx_to'].append(new_idx) self._img_p_parsedpalette[new_idx] = self._img_p_parsedpalette[0] del(self._img_p_parsedpalette[0]) def _get_unused_color(self) -> tuple: """ Return a color for the palette that does not collide with any other already in the palette.""" used_colors = set(self._img_p_parsedpalette.values()) while True: new_color = (randrange(256), randrange(256), randrange(256)) if new_color not in used_colors: return new_color def _process_palette(self): """Adjust palette to have the zeroth color set as transparent. Basically, get another palette index for the zeroth color.""" self._set_parsed_palette() if 0 in self._img_p_used_palette_idxs: self._remap_palette_idx_zero() self._img_p_parsedpalette[0] = self._get_unused_color() def _adjust_pixels(self): """Convert the pixels into their new values.""" if self._palette_replaces['idx_from']: trans_table = bytearray.maketrans( bytes(self._palette_replaces['idx_from']), bytes(self._palette_replaces['idx_to'])) self._img_p_data = self._img_p_data.translate(trans_table) for idx_pixel in self._transparent_pixels: self._img_p_data[idx_pixel] = 0 self._img_p.frombytes(data=bytes(self._img_p_data)) def _adjust_palette(self): """Modify the palette in the new `Image`.""" unused_color = self._get_unused_color() final_palette = chain.from_iterable( self._img_p_parsedpalette.get(x, unused_color) for x in range(256)) self._img_p.putpalette(data=final_palette) def process(self) -> Image: """Return the processed mode `P` `Image`.""" self._img_p = self._img_rgba.convert(mode='P') self._img_p_data = bytearray(self._img_p.tobytes()) self._palette_replaces = dict(idx_from=list(), idx_to=list()) self._process_pixels() self._process_palette() self._adjust_pixels() self._adjust_palette() self._img_p.info['transparency'] = 0 self._img_p.info['background'] = 0 return self._img_p def _create_animated_gif(images: List[Image], durations: Union[int, List[int]]) -> Tuple[Image, dict]: """If the image is a GIF, create an its thumbnail here.""" save_kwargs = dict() new_images: List[Image] = [] for frame in images: thumbnail = frame.copy() # type: Image thumbnail_rgba = thumbnail.convert(mode='RGBA') thumbnail_rgba.thumbnail(size=frame.size, reducing_gap=3.0) converter = TransparentAnimatedGifConverter(img_rgba=thumbnail_rgba) thumbnail_p = converter.process() # type: Image new_images.append(thumbnail_p) output_image = new_images[0] save_kwargs.update( format='GIF', save_all=True, optimize=False, append_images=new_images[1:], duration=durations, disposal=2, # Other disposals don't work loop=0) return output_image, save_kwargs def save_transparent_gif(images: List[Image], durations: Union[int, List[int]], save_file): """Creates a transparent GIF, adjusting to avoid transparency issues that are present in the PIL library Note that this does NOT work for partial alpha. The partial alpha gets discarded and replaced by solid colors. Parameters: images: a list of PIL Image objects that compose the GIF frames durations: an int or List[int] that describes the animation durations for the frames of this GIF save_file: A filename (string), pathlib.Path object or file object. (This parameter corresponds and is passed to the PIL.Image.save() method.) Returns: Image - The PIL Image object (after first saving the image to the specified target) """ root_frame, save_args = _create_animated_gif(images, durations) root_frame.save(save_file, **save_args) If, like I was, you're having the issue and wondering what to do with the code, you should simply create a new py file in your project and put the code within it. Next, instead of using the save function in your code you are using to save the gif, you will use save_transparent_gif(canvas_frames, durations, filename). Be sure to replace the arguments with either raw values or the vars you have already made.
4
0
75,832,256
2023-3-24
https://stackoverflow.com/questions/75832256/how-to-get-output-from-fiona-instead-of-fiona-model-object
I'm following the examples in the docs but using Virginia's parcel shp file. Warning: it's about 1GB zipped and 1.8GB unzipped. I have very simply fiava = fiona.open("VirginiaParcel.shp/VirginiaParcel.shp", layer='VirginiaParcel') from which I can do fiava.schema to get # {'properties': {'FIPS': 'str:8', # 'LOCALITY': 'str:64', # 'PARCELID': 'str:64', # 'PTM_ID': 'str:64', # 'LASTUPDATE': 'date', # 'VGIN_QPID': 'str:50'}, # 'geometry': 'Polygon'} So far so good but when I do fiava[0] ## I get a Feature object, not the data ## <fiona.model.Feature at 0x7f2fd582aa10> In the docs it shows this output {'geometry': {'coordinates': [[(-4.663611, 51.158333), (-4.669168, 51.159439), (-4.673334, 51.161385), (-4.674445, 51.165276), (-4.67139, 51.185272), (-4.669445, 51.193054), (-4.665556, 51.195), (-4.65889, 51.195), (-4.656389, 51.192215), (-4.646389, 51.164444), (-4.646945, 51.160828), (-4.651668, 51.159439), (-4.663611, 51.158333)]], 'type': 'Polygon'}, 'id': '1', 'properties': OrderedDict([('CAT', 232.0), ('FIPS_CNTRY', 'UK'), ('CNTRY_NAME', 'United Kingdom'), ('AREA', 244820.0), ('POP_CNTRY', 60270708.0)]), 'type': 'Feature'} If I use the schema for the specific keys then I can get data one value at a time but this is not optimal fiava[0]['properties']['FIPS'] ## 51149 Even if I do fiava[0].items() then it's just an ItemsView What am I missing?
You can use fiona.model.to_dict() from fiona.model import to_dict d = to_dict(fiava[0]) if you want to serialize the data as json without calling to_dict() on each object, you can use the fiona.model.ObjectEncoder: import json from fiona.model import ObjectEncoder j = json.dumps(fiava, cls=ObjectEncoder)
4
2
75,832,713
2023-3-24
https://stackoverflow.com/questions/75832713/stable-baselines-3-support-for-farama-gymnasium
I am building an environment in the maintained fork of gym: Gymnasium by Farama. In my gym environment, I state that the action_space = gym.spaces.Discrete(5) and the observation_space = gym.spaces.MultiBinary(25). Running the environment with the agent-environment loop suggested on the Gym Basic Usage website runs with no problems: I registered the environment and it is simply callable by gym.make(). However, I want to now train a reinforcement learning agent on this environment. Now I have come across Stable Baselines3, which makes a DQN agent implementation fairly easy. However, it does seem to support the new Gymnasium. Namely: import gymnasium as gym from stable_baselines3.ppo.policies import MlpPolicy from stable_baselines3 import DQN env = gym.make("myEnv") model = DQN(MlpPolicy, env, verbose=1) Yes I know, "myEnv" is not reproducable, but the environment itself is too large (along with the structure of the file system), but that is not the point of this question This code produces an error: AssertionError: The algorithm only supports (<class 'gym.spaces.discrete.Discrete',) as action spaces but Discrete(5) was provided My question is the following: does Stable Baselines3 support Gymnasium? I have tried to instead use gym.spaces in order to define the action_space and observation_space, such that from gym.spaces import Discrete, MultiBinary action_space = Discrete(5) observation_space = MultiBinary(25) but along with this, I have to rewrite a large portion of the environment to support the old gym package. I wonder whether there is a better solution than that.
I was a bit confused by the other answer here as I was sure I'd seen gymnasium in the Stable Baselines 3 docs somewhere. Sure enough, it's even in the most basic "getting started" example: https://stable-baselines3.readthedocs.io/en/master/guide/quickstart.html. However, I just tried running exactly this code and received the same error as the OP. Replacing gymnasium with gym 0.21 in the same example works without a problem. Edit: The "getting started" example using gymnasium works with stable_baselines3 version 2.0.0a1 and above.
3
4
75,834,708
2023-3-24
https://stackoverflow.com/questions/75834708/filling-contours-but-leaving-contained-regions-unfilled
I have this python code that supposedly fills the contours of an image, but leaves the holes contained in it unfilled. This is what I want: But this is what I get: I've tried specifying the contour hierarchies for filling with cv2, but I can't get the result I want. This is what I've tried: import numpy as np import cv2 # Load the PNG image img = cv2.imread('slice.png') # Convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Threshold the image to create a binary image ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY) # Find the contours in the binary image contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Create a blank image with the same dimensions as the original image filled_img = np.zeros(img.shape[:2], dtype=np.uint8) # Iterate over the contours and their hierarchies for i, contour in enumerate(contours): # Check if the contour has a parent if hierarchy[0][i][3] == -1: # If the contour doesn't have a parent, fill it with pixel value 255 cv2.drawContours(filled_img, [contour], -1, 255, cv2.FILLED) # Display the result cv2.imshow('Original Image', img) cv2.imshow('Filled Regions', filled_img) cv2.waitKey(0) cv2.destroyAllWindows() I've tried modifying the -1, 0, 1 values for the 'if hierarchy[0][i][3] == -1:' part, but it either fills the smaller holes, or fills the entire bigger contour like the first pic I posted. Update I also would like to fill with white the inside of lesser hierarchy contours, like this:
The issue is that cv2.drawContours fills the entire inner part of a closed contour, regardless if there is an inner contour. Instead of filling the contours without a parent with white, we may start with white contour, and fill the contours without a child with black. Assuming we know that the inner part should be black, we may apply the following stages: Find contours using cv2.RETR_EXTERNAL, and fill the outer contour with white. Find contours using cv2.RETR_TREE. Iterate the contours hierarchy, and fill with black color only contours that doesn't have a child contour (fill with black the most inner contours). Code sample: import numpy as np import cv2 # Load the PNG image img = cv2.imread('slice.png') # Convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Threshold the image to create a binary image ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY) # Find the outer contours in the binary image (using cv2.RETR_EXTERNAL) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Create a blank image with the same dimensions as the original image filled_img = np.zeros(img.shape[:2], dtype=np.uint8) # Fill the outer contour with white color cv2.drawContours(filled_img, contours, -1, 255, cv2.FILLED) # Find contours with hierarchy, this time use cv2.RETR_TREE contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Iterate over the contours and their hierarchies for i, contour in enumerate(contours): # Check if the contour has no child if hierarchy[0][i][2] < 0: # If contour has no child, fill the contour with black color cv2.drawContours(filled_img, [contour], -1, 0, cv2.FILLED) # Display the result cv2.imshow('Original Image', img) cv2.imshow('Filled Regions', filled_img) cv2.waitKey(0) cv2.destroyAllWindows() Result filled_img: Note: In case we don't know the color of the most inner contour, we may draw a white contour on a black background, and use the result as a mask - use the mask for copying the original content of the input image. Update: Support contours that don't have a child: For supporting both contours that have a child and contours without a child, we may fill with black color, only contours that match both conditions: Contours has no child contour. Contour has a grandparent contour (look for grandparent instead of a parent because an empty contour has an inner contour and its parent is the outer contour). Code sample: import numpy as np import cv2 # Load the PNG image img = cv2.imread('slice.png') # Convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Threshold the image to create a binary image ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY) # Find the outer contours in the binary image (using cv2.RETR_EXTERNAL) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Create a blank image with the same dimensions as the original image filled_img = np.zeros(img.shape[:2], dtype=np.uint8) # Fill the outer contour with white color cv2.drawContours(filled_img, contours, -1, 255, cv2.FILLED) # Find contours with hierarchy, this time use cv2.RETR_TREE contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Iterate over the contours and their hierarchies for i, contour in enumerate(contours): has_grandparent = False has_parent = hierarchy[0][i][3] >= 0 if has_parent: # Check if contour has a grandparent parent_idx = hierarchy[0][i][3] has_grandparent = hierarchy[0][parent_idx][3] >= 0 # Check if the contour has no child if hierarchy[0][i][2] < 0 and has_grandparent: # If contour has no child, fill the contour with black color cv2.drawContours(filled_img, [contour], -1, 0, cv2.FILLED) # Display the result cv2.imshow('Original Image', img) cv2.imshow('Filled Regions', filled_img) cv2.waitKey(0) cv2.destroyAllWindows() Update: Fill with white the inside of lesser hierarchy contours: Before filling the contour with black color, we may check is the nominated contour has black pixels inside. Fill with black only if it has no child, has a grandparent and has black inside. For testing if has black pixels inside we may draw the contour (with white color) over temporary image. Then check if the minimum value is 0 (value where drawn contour is white). tmp = np.zeros_like(thresh) cv2.drawContours(tmp, [contour], -1, 255, cv2.FILLED) has_innder_black_pixels = (thresh[tmp==255].min() == 0) Code sample: import numpy as np import cv2 # Load the PNG image img = cv2.imread('slice.png') # Convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Threshold the image to create a binary image ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY) # Find the outer contours in the binary image (using cv2.RETR_EXTERNAL) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Create a blank image with the same dimensions as the original image filled_img = np.zeros(img.shape[:2], dtype=np.uint8) # Fill the outer contour with white color cv2.drawContours(filled_img, contours, -1, 255, cv2.FILLED) # Find contours with hierarchy, this time use cv2.RETR_TREE contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Iterate over the contours and their hierarchies for i, contour in enumerate(contours): has_grandparent = False has_parent = hierarchy[0][i][3] >= 0 if has_parent: # Check if contour has a grandparent parent_idx = hierarchy[0][i][3] has_grandparent = hierarchy[0][parent_idx][3] >= 0 # Draw the contour over temporary image first (for testing if it has black pixels inside). tmp = np.zeros_like(thresh) cv2.drawContours(tmp, [contour], -1, 255, cv2.FILLED) has_innder_black_pixels = (thresh[tmp==255].min() == 0) # If the minimum value is 0 (value where draw contour is white) then the contour has black pixels inside if hierarchy[0][i][2] < 0 and has_grandparent and has_innder_black_pixels: # If contour has no child and has a grandparent and it has black inside, fill the contour with black color cv2.drawContours(filled_img, [contour], -1, 0, cv2.FILLED) # Display the result cv2.imshow('Original Image', img) cv2.imshow('Filled Regions', filled_img) cv2.waitKey(0) cv2.destroyAllWindows()
3
2
75,853,863
2023-3-27
https://stackoverflow.com/questions/75853863/install-pytorch-version-1-0-0-using-pip-or-cuda-in-2023
I want to install the pytoch version 1.0.0, but i couldn't able to do that I tried pip install torch===1.0.0 -f https://download.pytorch.org/whl/torch_stable.html its not wotking I'm getting a error Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/ Looking in links: https://download.pytorch.org/whl/torch_stable.html ERROR: Could not find a version that satisfies the requirement torch===1.0.0 (from versions: 1.7.1, 1.7.1+cpu, 1.7.1+cu101, 1.7.1+cu110, 1.7.1+cu92, 1.7.1+rocm3.7, 1.7.1+rocm3.8, 1.8.0, 1.8.0+cpu, 1.8.0+cu101, 1.8.0+cu111, 1.8.0+rocm3.10, 1.8.0+rocm4.0.1, 1.8.1, 1.8.1+cpu, 1.8.1+cu101, 1.8.1+cu102, 1.8.1+cu111, 1.8.1+rocm3.10, 1.8.1+rocm4.0.1, 1.9.0, 1.9.0+cpu, 1.9.0+cu102, 1.9.0+cu111, 1.9.0+rocm4.0.1, 1.9.0+rocm4.1, 1.9.0+rocm4.2, 1.9.1, 1.9.1+cpu, 1.9.1+cu102, 1.9.1+cu111, 1.9.1+rocm4.0.1, 1.9.1+rocm4.1, 1.9.1+rocm4.2, 1.10.0, 1.10.0+cpu, 1.10.0+cu102, 1.10.0+cu111, 1.10.0+cu113, 1.10.0+rocm4.0.1, 1.10.0+rocm4.1, 1.10.0+rocm4.2, 1.10.1, 1.10.1+cpu, 1.10.1+cu102, 1.10.1+cu111, 1.10.1+cu113, 1.10.1+rocm4.0.1, 1.10.1+rocm4.1, 1.10.1+rocm4.2, 1.10.2, 1.10.2+cpu, 1.10.2+cu102, 1.10.2+cu111, 1.10.2+cu113, 1.10.2+rocm4.0.1, 1.10.2+rocm4.1, 1.10.2+rocm4.2, 1.11.0, 1.11.0+cpu, 1.11.0+cu102, 1.11.0+cu113, 1.11.0+cu115, 1.11.0+rocm4.3.1, 1.11.0+rocm4.5.2, 1.12.0, 1.12.0+cpu, 1.12.0+cu102, 1.12.0+cu113, 1.12.0+cu116, 1.12.0+rocm5.0, 1.12.0+rocm5.1.1, 1.12.1, 1.12.1+cpu, 1.12.1+cu102, 1.12.1+cu113, 1.12.1+cu116, 1.12.1+rocm5.0, 1.12.1+rocm5.1.1, 1.13.0, 1.13.0+cpu, 1.13.0+cu116, 1.13.0+cu117, 1.13.0+cu117.with.pypi.cudnn, 1.13.0+rocm5.1.1, 1.13.0+rocm5.2, 1.13.1, 1.13.1+cpu, 1.13.1+cu116, 1.13.1+cu117, 1.13.1+cu117.with.pypi.cudnn, 1.13.1+rocm5.1.1, 1.13.1+rocm5.2, 2.0.0, 2.0.0+cpu, 2.0.0+cpu.cxx11.abi, 2.0.0+cu117, 2.0.0+cu117.with.pypi.cudnn, 2.0.0+cu118, 2.0.0+rocm5.3, 2.0.0+rocm5.4.2) ERROR: No matching distribution found for torch===1.0.0
It seems like your Python3 version is newer (>3.7) than what the version of torch you're trying to install supports. Available versions of torch start from 1.7.1. Consider using an older version of Python3 (<=3.7). To do this, I recommend installing conda or miniconda from here. Then, run: conda create -n myenv python=3.6.9 Load your env: conda activate myenv Try install torch again: pip install torch===1.0.0 -f https://download.pytorch.org/whl/torch_stable.html Regards.
5
4
75,853,973
2023-3-27
https://stackoverflow.com/questions/75853973/azure-app-service-app-not-in-root-directory
I have a mono repo with more than one application in it. The application I'm trying to deploy is in the directory rest_api. The deploy as seen in github actions is successful, but start-up fails. This is my start-up command gunicorn -w 1 -k uvicorn.workers.UvicornWorker main:app This is what the github actions file look like: name: Deploy rest_api (dev) to Azure env: AZURE_WEBAPP_NAME: 'xxx-rest-api' PYTHON_VERSION: '3.11' on: push: branches: [ "dev" ] workflow_dispatch: permissions: contents: read jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python version uses: actions/[email protected] with: python-version: ${{ env.PYTHON_VERSION }} cache: 'pip' - name: Create and start virtual environment working-directory: rest_api run: | python -m venv venv source venv/bin/activate - name: Install dependencies working-directory: rest_api run: | pip install --upgrade pip pip install -r requirements/base.txt - name: Upload artifact for deployment jobs uses: actions/upload-artifact@v3 with: name: python-app path: | rest_api !venv/ !rest_api/venv/ deploy: permissions: contents: none runs-on: ubuntu-latest needs: build environment: name: 'Production' url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v3 with: name: python-app path: rest_api - name: 'Deploy to Azure Web App' id: deploy-to-webapp uses: azure/webapps-deploy@v2 with: app-name: ${{ env.AZURE_WEBAPP_NAME }} publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_A79D58476BA645D1BF1A6116201A6E5F }} package: rest_api This is the error: 2023-03-27T08:52:28.865320556Z Launching oryx with: create-script -appPath /home/site/wwwroot -output /opt/startup/startup.sh -virtualEnvName antenv -defaultApp /opt/defaultsite -userStartupCommand 'gunicorn -w 1 -k uvicorn.workers.UvicornWorker main:app' 2023-03-27T08:52:28.925294508Z Cound not find build manifest file at '/home/site/wwwroot/oryx-manifest.toml' 2023-03-27T08:52:28.925870805Z Could not find operation ID in manifest. Generating an operation id... 2023-03-27T08:52:28.925880705Z Build Operation ID: d2e6df02-e71b-45fd-b84c-a0d9d8114831 2023-03-27T08:52:29.307010231Z Oryx Version: 0.2.20230103.1, Commit: df89ea1db9625a86ba583272ce002847c18f94fe, ReleaseTagName: 20230103.1 2023-03-27T08:52:29.354907333Z Writing output script to '/opt/startup/startup.sh' 2023-03-27T08:52:29.472048349Z WARNING: Could not find virtual environment directory /home/site/wwwroot/antenv. 2023-03-27T08:52:29.491003271Z WARNING: Could not find package directory /home/site/wwwroot/__oryx_packages__. 2023-03-27T08:52:30.408188883Z 2023-03-27T08:52:30.408226683Z Error: class uri 'uvicorn.workers.UvicornWorker' invalid or not found: 2023-03-27T08:52:30.408231383Z 2023-03-27T08:52:30.408234383Z [Traceback (most recent call last): 2023-03-27T08:52:30.408237183Z File "/opt/python/3.11.1/lib/python3.11/site-packages/gunicorn/util.py", line 99, in load_class 2023-03-27T08:52:30.408240383Z mod = importlib.import_module('.'.join(components)) 2023-03-27T08:52:30.408243083Z ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2023-03-27T08:52:30.408245783Z File "/opt/python/3.11.1/lib/python3.11/importlib/__init__.py", line 126, in import_module 2023-03-27T08:52:30.408248583Z return _bootstrap._gcd_import(name[level:], package, level) 2023-03-27T08:52:30.408251383Z ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2023-03-27T08:52:30.408262283Z File "<frozen importlib._bootstrap>", line 1206, in _gcd_import 2023-03-27T08:52:30.408265483Z File "<frozen importlib._bootstrap>", line 1178, in _find_and_load 2023-03-27T08:52:30.408268383Z File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked 2023-03-27T08:52:30.408271083Z File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed 2023-03-27T08:52:30.408273883Z File "<frozen importlib._bootstrap>", line 1206, in _gcd_import 2023-03-27T08:52:30.408276583Z File "<frozen importlib._bootstrap>", line 1178, in _find_and_load 2023-03-27T08:52:30.408279383Z File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked 2023-03-27T08:52:30.408282083Z ModuleNotFoundError: No module named 'uvicorn' 2023-03-27T08:52:30.408284783Z ] My hunch is that the error relates to the app and the virtualenv not being in root.
I found out that the problem was requirements were not in rest_api/requirements.txt but in rest_api/requirements/requirements.txt.
5
0
75,867,972
2023-3-28
https://stackoverflow.com/questions/75867972/pandas-irregular-time-series-data-compare-row-to-next-8-hours-of-rows
Right now I am using pandas to analyze call center data. The data is structured as followed: call_time = pd.to_datetime([ '2020-01-01 01:00:00', '2020-01-01 09:00:00', '2020-01-01 01:00:00', '2020-01-01 03:00:00', '2020-01-01 04:00:00', '2020-01-01 06:00:00', '2020-01-01 01:00:00', '2020-01-01 10:00:00', ]) df = pd.DataFrame({'phone_number': ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c'], 'was_answered': [False, True, False, False, True, False, False, True],}, index=call_time) >>> df phone_number was_answered 2020-01-01 01:00:00 a False 2020-01-01 09:00:00 a True 2020-01-01 01:00:00 b False 2020-01-01 03:00:00 b False 2020-01-01 04:00:00 b True 2020-01-01 06:00:00 b False 2020-01-01 01:00:00 c False 2020-01-01 10:00:00 c True Each row represents a call at the call center. The index (call_time) is the time the call started. phone_number shows the hashed phone numbers. was_answered denotes if the call was answered. The data was sorted by phone_number first and then the call_time. Notice that the call_time is therefore not chronological. What I would like to do is identify the return callers. Return callers are callers that were not answered the first time, but called back within 8 hours. On top of this I need the time from the first call until the next call, regardless of wether the call was answered. So it would look something like this: phone_number was_answered is_return_call time_until_return 2020-01-01 01:00:00 a False False Null 2020-01-01 09:00:00 a True True 08:00:00 2020-01-01 01:00:00 b False False Null 2020-01-01 03:00:00 b False True 02:00:00 2020-01-01 04:00:00 b True True 01:00:00 2020-01-01 06:00:00 b False False Null 2020-01-01 01:00:00 c False False Null 2020-01-01 10:00:00 c True False Null I have tried many thing. Does anyone know how to do this? If my goal is unclear, please let me know!
You can solve this with rolling windows: was_answered = df.groupby("phone_number", group_keys=True)["was_answered"] # When the call has never been answered in the previous 8 # hours, it's a return call. Since we use closed="left", if # it's the first call in 8 hours, the window is empty, its # sum is NaN and hence not considered a return call. is_return_call = was_answered.rolling("8H", closed="left").sum().eq(0) # Time difference since previous call time_since_last_call = was_answered.apply(lambda w: w.index.to_series().diff()) result = pd.concat( [ was_answered.rolling(1).sum().astype("bool"), is_return_call.rename("is_return_call"), # If it's not a return call, time_until_return = NA time_since_last_call.where(is_return_call, None).rename("time_until_return"), ], axis=1, ) # Alternatively, you can extract `was_answered` from the # original frame but with modified index so that it can line # up with the other 2 series result = pd.concat( [ df.set_index("phone_number", append=True).swaplevel()["was_answered"], is_return_call.rename("is_return_call"), time_since_last_call.where(is_return_call, None).rename("time_until_return"), ], axis=1, ) Result: was_answered is_return_call time_until_return phone_number a 2020-01-01 01:00:00 False False NaT 2020-01-01 09:00:00 True True 0 days 08:00:00 b 2020-01-01 01:00:00 False False NaT 2020-01-01 03:00:00 False True 0 days 02:00:00 2020-01-01 04:00:00 True True 0 days 01:00:00 2020-01-01 06:00:00 False False NaT c 2020-01-01 01:00:00 False False NaT 2020-01-01 10:00:00 True False NaT
3
1
75,836,953
2023-3-24
https://stackoverflow.com/questions/75836953/how-to-resolve-typeerror-dispatch-model-got-an-unexpected-keyword-argument-o
After running the following code: import torch from accelerate import infer_auto_device_map, init_empty_weights from transformers import AutoConfig, AutoModelForCausalLM config = AutoConfig.from_pretrained("facebook/opt-13b") with init_empty_weights(): model = AutoModelForCausalLM.from_config(config) device_map = infer_auto_device_map(model, no_split_module_classes=["OPTDecoderLayer"], dtype="float16") model = AutoModelForCausalLM.from_pretrained( "facebook/opt-13b", device_map=device_map, offload_folder="offload", offload_state_dict=True, torch_dtype=torch.float16) I end up with the following error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_23/3733710460.py in <module> 4 offload_folder="offload", 5 offload_state_dict=True, ----> 6 torch_dtype=torch.float16) /opt/conda/lib/python3.7/site-packages/transformers/models/auto/auto_factory.py in from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs) 463 model_class = _get_model_class(config, cls._model_mapping) 464 return model_class.from_pretrained( --> 465 pretrained_model_name_or_path, *model_args, config=config, **hub_kwargs, **kwargs 466 ) 467 raise ValueError( /opt/conda/lib/python3.7/site-packages/transformers/modeling_utils.py in from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs) 2527 # Dispatch model with hooks on all devices if necessary 2528 if device_map is not None: -> 2529 dispatch_model(model, device_map=device_map, offload_dir=offload_folder, offload_index=offload_index) 2530 2531 if output_loading_info: TypeError: dispatch_model() got an unexpected keyword argument 'offload_index' I'm trying to load a large model from hugging face, and to do that, I split the weights into the GPUs from Kaggle. I don't understand exactly what is going on here, and how to deal with this issue.
please try updating your accelerate package, for example pip install accelerate==0.18.0
4
2
75,851,849
2023-3-27
https://stackoverflow.com/questions/75851849/mouve-mouse-human-like-with-python-selenium-like-pptr-ghost-cursor
I try this code: Human-like mouse movements via Selenium but trying to figure out how to integrate it in a real life scraper to follow with my mouse with different DOM elements: #!/usr/bin/python # https://stackoverflow.com/questions/39422453/human-like-mouse-movements-via-selenium import os from time import sleep from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains import numpy as np import scipy.interpolate as si #curve base points = [[-6, 2], [-3, -2],[0, 0], [0, 2], [2, 3], [4, 0], [6, 3], [8, 5], [8, 8], [6, 8], [5, 9], [7, 2]]; points = np.array(points) x = points[:,0] y = points[:,1] t = range(len(points)) ipl_t = np.linspace(0.0, len(points) - 1, 100) x_tup = si.splrep(t, x, k=3) y_tup = si.splrep(t, y, k=3) x_list = list(x_tup) xl = x.tolist() x_list[1] = xl + [0.0, 0.0, 0.0, 0.0] y_list = list(y_tup) yl = y.tolist() y_list[1] = yl + [0.0, 0.0, 0.0, 0.0] x_i = si.splev(ipl_t, x_list) y_i = si.splev(ipl_t, y_list) url = "https://codepen.io/falldowngoboone/pen/PwzPYv" driver = webdriver.Chrome() driver.get(url) action = ActionChains(driver); startElement = driver.find_element(By.ID, 'drawer') # First, go to your start point or Element: action.move_to_element(startElement); action.perform(); # https://stackoverflow.com/a/70796266/465183 for mouse_x, mouse_y in zip(x_i, y_i): # Here you should reset the ActionChain and the 'jump' wont happen: action = ActionChains(driver) action.move_by_offset(mouse_x,mouse_y); action.perform(); print(mouse_x, mouse_y) Is there a Python module like NodeJS/pptr Ghost Cursor to facilitate integration? Or anybody here can show us a way to integrate it in a real life scraper? Created a feature request: https://github.com/SeleniumHQ/selenium/issues/11824
Using pyautogui+Selenium ChromeDriver https://youtu.be/zZfPST2QS-g I think there's a better way, using Bezier curves as I do here and Selenium ActionsChains like your github links suggest, overriding class to do something like driver.move_to_element() and driver.random_mouse(), but this is working well for simple requirements: git clone https://github.com/sputnick-dev/pyautogui-with-selenium.git cd pyautogui-with-selenium ./run Code to avoid link only answer: paw file: #!/usr/bin/env python3 import random import bezier import pyautogui import numpy as np from time import sleep from random import uniform as randfloat from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException from selenium import webdriver def slow_type(element, text: str): """Send a text to an element one character at a time with a delay.""" for character in text: element.send_keys(character) sleep(randfloat(0.05,0.3)) def resting_mouse(): """move mouse to right of screen.""" panelWidht = driver.execute_script('return window.outerWidth;') start = pyautogui.position() end = random.randint(panelWidht-100, panelWidht), random.randint(400,850) x2 = (start[0] + end[0])/2 #midpoint x y2 = (start[1] + end[1]) / 2 ##midpoint y control1X = (start[0] + x2)/2 control2X = (end[0] + x2) / 2 # Two intermediate control points that may be adjusted to modify the curve. control1 = control1X, y2 ##combine midpoints to create perfect curve control2 = control2X, y2 ## using y2 for both to get a more linear curve # Format points to use with bezier control_points = np.array([start, control1, control2, end]) points = np.array([control_points[:, 0], control_points[:, 1]]) # Split x and y coordinates # You can set the degree of the curve here, should be less than # of control points degree = 3 # Create the bezier curve curve = bezier.Curve(points, degree) curve_steps = 70 # How many points the curve should be split into. Each is a separate pyautogui.moveTo() execution delay = 0.008 # Time between movements. 1/curve_steps = 1 second for entire curve # Move the mouse for j in range(1, curve_steps + 1): # The evaluate method takes a float from [0.0, 1.0] and returns the coordinates at that point in the curve # Another way of thinking about it is that i/steps gets the coordinates at (100*i/steps) percent into the curve x, y = curve.evaluate(j / curve_steps) pyautogui.moveTo(x, y) # Move to point in curve pyautogui.sleep(delay) # Wait delay sleep(2) def bezier_mouse(location, size, panelHeight): ##move mouse to middle of element x, relY = location["x"], location["y"] ##abs X and relative Y absY = relY + panelHeight w, h = size["width"], size["height"] wCenter = w/2 hCenter = h/2 xCenter = int(wCenter + x) yCenter = int(hCenter + absY) start = pyautogui.position() end = xCenter, yCenter x2 = (start[0] + end[0]) / 2 #midpoint x y2 = (start[1] + end[1]) / 2 ##midpoint y control1X = (start[0] + x2) / 2 control1Y = (end[1] + y2) / 2 control2X = (end[0] + x2) / 2 control2Y = (start[1] + y2) / 2 # Two intermediate control points that may be adjusted to modify the curve. control1 = control1X, y2 ##combine midpoints to create perfect curve control2 = control2X, y2 # Format points to use with bezier control_points = np.array([start, control1, control2, end]) points = np.array([control_points[:, 0], control_points[:, 1]]) # Split x and y coordinates # You can set the degree of the curve here, should be less than # of control points degree = 3 # Create the bezier curve curve = bezier.Curve(points, degree) curve_steps = 70 # How many points the curve should be split into. Each is a separate pyautogui.moveTo() execution delay = 0.008 # Time between movements. 1/curve_steps = 1 second for entire curve # Move the mouse for j in range(1, curve_steps + 1): # The evaluate method takes a float from [0.0, 1.0] and returns the coordinates at that point in the curve # Another way of thinking about it is that i/steps gets the coordinates at (100*i/steps) percent into the curve x, y = curve.evaluate(j / curve_steps) pyautogui.moveTo(x, y) # Move to point in curve pyautogui.sleep(delay) # Wait delay # Disable pyautogui pauses pyautogui.MINIMUM_DURATION = 0 pyautogui.MINIMUM_SLEEP = 0 pyautogui.PAUSE = 0 # avoid Exception when mouse if in a top corner pyautogui.FAILSAFE = False # instanciate Chrome websriver driver = webdriver.Chrome() driver.maximize_window() driver.implicitly_wait(0.5) try: driver.get("http://localhost:8000") except TimeoutException: driver.execute_script("window.stop();") sleep(2) e1 = driver.find_element(By.ID, "change-me-paw") e2 = driver.find_element(By.ID, "textarea") panelHeight = driver.execute_script('return window.outerHeight - window.innerHeight;') location1 = e1.location ## coords of element1 location2 = e2.location ## coords of element2 size1 = e1.size ## size of element1 size2 = e2.size ## size of element2 sleep(3) bezier_mouse(location1, size1, panelHeight) e1.click() sleep(2) bezier_mouse(location2, size2, panelHeight) slow_type(e2, 'I type like a human being...') sleep(2) resting_mouse() sleep(2) driver.close() The rest of artefacts are in repository. run wrapper script: #!/bin/bash trap 'kill $pid $$' 1 2 3 15 [[ ! -e .req ]] && pip3 install -r requirements.txt && touch .req cd tests/ python3 -m http.server & pid=$! cd .. ./paw kill $pid &>/dev/null
3
2
75,862,378
2023-3-28
https://stackoverflow.com/questions/75862378/plot-difference-between-two-plotly-hexbin-maps
I've seen posts relating to plotting the difference between two hexbin maps in matplotlib. I couldn't find anything executing the same process but for Plotly hexbin map box plots. If I have two separate hexbin subplots (t, y), is it possible to produce a single plot that subtracts the difference between t and y? import pandas as pd import plotly.express as px import plotly.graph_objs as go import plotly.figure_factory as ff from plotly.subplots import make_subplots data = pd.DataFrame({ 'Cat': ['t','y','y','t','t','t','t','y','y','y','t','y'], 'LAT': [5,6,7,5,6,7,5,6,7,5,6,7], 'LON': [10,11,12,10,11,12,10,11,12,10,11,12], }) data = pd.concat([data]*5) df_t = data[data['Cat'] == 't'] df_y = data[data['Cat'] == 'y'] fig = make_subplots( rows = 2, cols = 1, subplot_titles = ('t', 'y'), specs = [[{"type": "choroplethmapbox"}], [{"type": "choroplethmapbox"}]], vertical_spacing = 0.05, horizontal_spacing = 0.05 ) fig2 = ff.create_hexbin_mapbox(data_frame=df_t, lat="LAT", lon="LON", nx_hexagon=5, opacity=0.5, labels={"color": "Point Count"}, mapbox_style='carto-positron', ) fig3 = ff.create_hexbin_mapbox(data_frame=df_y, lat="LAT", lon="LON", nx_hexagon=5, opacity=0.5, labels={"color": "Point Count"}, mapbox_style='carto-positron', ) fig.add_trace(fig2.data[0], row=1,col=1) fig.update_mapboxes(zoom=4, style='carto-positron') fig.add_trace(fig3.data[0], row=2,col=1) fig.update_mapboxes(zoom=4, style='carto-positron') fig.update_layout(height=600, margin=dict(t=20,b=0,l=0,r=0)) fig.show() intended output: The bottom left bin for t has 15 points, while y has 5. So this will total 10. The middle bin has 10 points for both so will result in 0. The top right has 5 for t and 15 for y, coming to -10. But I'll set vmin to 0 to ensure no negative values. Edit 2: If I alter the input data with different size arrays and include min_count = 1 as a parameter, I return an error. data = pd.DataFrame({ 'Cat': ['t','y','y','t','t','t','t','y','y','y','t','y','y'], 'LAT': [5,6,7,5,6,7,5,6,7,5,6,7,8], 'LON': [10,11,12,10,11,12,10,11,12,10,11,12,8], }) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /var/folders/bf/09nyl3td65j2lty5m7138ndw0000gn/T/ipykernel_78237/2142200526.py in <module> 47 48 fig = go.Figure(fig2) ---> 49 fig.data[0]['z'] = (fig2.data[0]['z'] - fig3.data[0]['z']).clip(min=0) 50 cmax, cmin = max(fig.data[0]['z']), min(fig.data[0]['z']) 51 ValueError: operands could not be broadcast together with shapes (3,) (4,)
Since plotly determines the counts within each hexbin when creating the figure, you'll need to access the count data inside both fig2 and fig3. Here is the array as it's stored inside fig2.data[0]['z']: array([15., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 5., 0., 0., 0., 0., 0., 0., 0., 10., 0., 0., 0., 0., 0., 0., 0.]) We can set fig to be a copy of fig2, create a new array by taking the difference between the count arrays from fig2 and fig3 (and clipping it at 0), and set fig.data[0]['z'] to this new array. You will also want to update the minimum and maximum values of the colorbar accordingly. import pandas as pd import plotly.express as px import plotly.graph_objs as go import plotly.figure_factory as ff from plotly.subplots import make_subplots data = pd.DataFrame({ 'Cat': ['t','y','y','t','t','t','t','y','y','y','t','y'], 'LAT': [5,6,7,5,6,7,5,6,7,5,6,7], 'LON': [10,11,12,10,11,12,10,11,12,10,11,12], }) data = pd.concat([data]*5) df_t = data[data['Cat'] == 't'] df_y = data[data['Cat'] == 'y'] # fig = make_subplots( # rows = 2, # cols = 1, # subplot_titles = ('t', 'y'), # specs = [[{"type": "choroplethmapbox"}], [{"type": "choroplethmapbox"}]], # vertical_spacing = 0.05, # horizontal_spacing = 0.05 # ) fig2 = ff.create_hexbin_mapbox(data_frame=df_t, lat="LAT", lon="LON", nx_hexagon=5, opacity=0.5, labels={"color": "Point Count"}, mapbox_style='carto-positron', ) fig3 = ff.create_hexbin_mapbox(data_frame=df_y, lat="LAT", lon="LON", nx_hexagon=5, opacity=0.5, labels={"color": "Point Count"}, mapbox_style='carto-positron', ) fig = go.Figure(fig2) fig.data[0]['z'] = (fig2.data[0]['z'] - fig3.data[0]['z']).clip(min=0) cmax, cmin = max(fig.data[0]['z']), min(fig.data[0]['z']) fig.update_mapboxes(zoom=6, style='carto-positron') fig.update_layout(height=600, margin=dict(t=20,b=0,l=0,r=0)) fig.update_coloraxes(cmax=cmax, cmin=cmin) fig.show() Update: in a situation where fig2.data[0]['z'] and fig3.data[0]['z'] are arrays of different lengths, you'll need to pad the shorter array. I am making the assumption that the padding values are zero, and that we will calculate the differences in the same manner. Using your edited sample data, we get that fig2.data[0]['z'] is array([15., 5., 10.]) and fig3.data[0]['z'] is array([10., 15., 5., 5.]). So we pad array([15., 5., 10.]) with 0s to match the length of the other array meaning we use array([15., 5., 10., 0.]). I've added some code which pads the shorter array, then computes the difference and clips negative values the same way as before. import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objs as go import plotly.figure_factory as ff from plotly.subplots import make_subplots # data = pd.DataFrame({ # 'Cat': ['t','y','y','t','t','t','t','y','y','y','t','y'], # 'LAT': [5,6,7,5,6,7,5,6,7,5,6,7], # 'LON': [10,11,12,10,11,12,10,11,12,10,11,12], # }) data = pd.DataFrame({ 'Cat': ['t','y','y','t','t','t','t','y','y','y','t','y','y'], 'LAT': [5,6,7,5,6,7,5,6,7,5,6,7,8], 'LON': [10,11,12,10,11,12,10,11,12,10,11,12,8], }) data = pd.concat([data]*5) df_t = data[data['Cat'] == 't'] df_y = data[data['Cat'] == 'y'] fig2 = ff.create_hexbin_mapbox(data_frame=df_t, lat="LAT", lon="LON", nx_hexagon=5, opacity=0.5, labels={"color": "Point Count"}, mapbox_style='carto-positron', min_count=1 ) fig3 = ff.create_hexbin_mapbox(data_frame=df_y, lat="LAT", lon="LON", nx_hexagon=5, opacity=0.5, labels={"color": "Point Count"}, mapbox_style='carto-positron', min_count=1, ) fig = go.Figure(fig2) fig2_values, fig3_values = fig2.data[0]['z'], fig3.data[0]['z'] ## we pad whichever figure has fewer z values if len(fig2_values) < len(fig3_values): pad_length = len(fig3_values) - len(fig2_values) fig2_values = np.pad(fig2_values, (0, pad_length), 'constant') elif len(fig2_values) > len(fig3_values): pad_length = len(fig2_values) - len(fig3_values) fig3_values = np.pad(fig3_values, (0, pad_length), 'constant') else: pass fig.data[0]['z'] = (fig2_values - fig3_values).clip(min=0) cmax, cmin = max(fig.data[0]['z']), min(fig.data[0]['z']) fig.update_mapboxes(zoom=6, style='carto-positron') fig.update_layout(height=600, margin=dict(t=20,b=0,l=0,r=0)) fig.update_coloraxes(cmax=cmax, cmin=cmin) fig.show()
3
3
75,864,807
2023-3-28
https://stackoverflow.com/questions/75864807/mypy-complaining-about-no-any-return-rule-being-violated-for-obvious-boolean-e
The following code throws a mypy error: from typing import Dict, Any def asd(x: Dict[str, Any]) -> bool: return x['a'] == 1 asd({"x": 2}) IMO it doesn't matter what is passed as a dict. x['a'] == 1 should always be a boolean. But mypy complains with: test.py:4: error: Returning Any from function declared to return "bool" [no-any-return] Any Idea how to fix is besides peppering our codebase with # type: ignore[no-any-return]? my setup.cfg for reference: namespace_packages = True explicit_package_bases = True check_untyped_defs = True warn_return_any = True warn_unused_ignores = True show_error_codes = True
The __eq__ method, one of Python's rich comparison methods, does not always return True or False, it can also return NotImplemented (or other values). This is used, for example, in the case where the first type cannot compare itself with the second, so a.__eq__(b) returns NotImplemented. In that case, it then tries b.__eq__(a) as a fallback (a). If that also returns NotImplemented, then I believe it falls back to the base object type to figure out equality. You can see the way mypy has defined the typing for this in its source code, specifically mypy/mypy/typeshed/stdlib/_operator.pyi: def eq(__a: object, __b: object) -> Any: ... That's why you're getting that particular message. As a quick fix, you can change the function to return bool(x['x'] == 1). This is exactly what Python itself does when evaluating the return value in a boolean context, so should be acceptable for placating mypy (b). (a) It's a little more complex than that, involving also the hierarchical type relationships of the two items, but the bottom line still stands: rich comparison operators do not always return a bool. (b) This is covered in the Python documentation for the data model (my emphasis): A rich comparison method may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments. By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false. Interestingly, though this doesn't change the validity of this answer, the section after that states: By default, object implements __eq__() by using is, returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented. But I'm not convinced that's accurate. In the actual code, both == and != seem to result in True or False, depending on object identity, and never returning NotImplemented or raising an exception (the exceptions happen only for ordering comparisons like < or >=): /* If neither object implements it, provide a sensible default for == and !=, but raise an exception for ordering. */ switch (op) { case Py_EQ: res = (v == w) ? Py_True : Py_False; break; case Py_NE: res = (v != w) ? Py_True : Py_False; break; default: _PyErr_Format(tstate, PyExc_TypeError, ... As pointed out in a comment, the identity checking is done at a different level to base objects, for example,the type objects. So I'd take that part of the documentation with a grain of salt :-) In any case, it shows that, while base objects may only give you back true or false, some derived objects can also give other values, which is why the warning you're seeing is correct.
5
5
75,818,230
2023-3-23
https://stackoverflow.com/questions/75818230/what-is-the-best-practice-to-apply-cross-validation-using-timeseriessplit-over
Let's say I have dataset within the following pandas dataframe format with a non-standard timestamp column without datetime format as follows: +--------+-----+ |TS_24hrs|count| +--------+-----+ |0 |157 | |1 |334 | |2 |176 | |3 |86 | |4 |89 | ... ... |270 |192 | |271 |196 | |270 |251 | |273 |138 | +--------+-----+ 274 rows Γ— 2 columns I have already applied some regression algorithms after splitting data without using cross-validation (CV) into training-set and test-set and got results like the following: import numpy as np import pandas as pd import matplotlib.pyplot as plt #Load the time-series data as dataframe df = pd.read_csv('/content/U2996_24hrs_.csv', sep=",") print(df.shape) # Split the data into training and testing sets from sklearn.model_selection import train_test_split train, test = train_test_split(df, test_size=0.27, shuffle=False) print(train.shape) #(200, 2) print(test.shape) #(74, 2) #visulize splitted data train['count'].plot(label='Training-set') test['count'].plot(label='Test-set') plt.legend() plt.show() #Train and fit the model from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor().fit(train, train['count']) #X, y rf.score(train, train['count']) #0.9998644192184375 # Use the forest's model to predict on the test-set predictions = rf.predict(test) #convert prediction result into dataframe for plot issue in ease df_pre = pd.DataFrame({'TS_24hrs':test['TS_24hrs'], 'count_prediction':predictions}) # Calculate the mean absolute errors from sklearn.metrics import mean_absolute_error rf_mae = mean_absolute_error(test['count'], df_pre['count_prediction']) print(train.shape) #(200, 2) print(test.shape) #(74, 2) print(df_pre.shape) #(74, 2) #visulize forecast or prediction of used regressor model train['count'].plot(label='Training-set') test['count'].plot(label='Test-set') df_pre['count_prediction'].plot(label=f'RF_forecast MAE={rf_mae:.2f}') plt.legend() plt.show() According this answer I noticed: if your data is already sorted based on time then simply use shuffle=False in train, test = train_test_split(newdf, test_size=0.3, shuffle=False) So far, I have used this classic split data method, but I want to experiment with Time-series-based split methods that are summarized here: Additionally, based on my investigation (please see the references at the end of the post), it is recommended to use the cross-validation method (K-Fold) before applying regression models. explanation: Cross Validation in Time Series Problem: How can split time-series data with using CV methods for comparable results? (plot the quality of data split for ensure\evaluate the quality of data splitting) TSS CV method: TimeSeriesSplit() BTSS CV method: BlockingTimeSeriesSplit() So far, the closest solution that crossed my mind is to separate the last 74 observations as hold-on test-set a side and do CV on just the first 200 observations. I'm still struggling with playing with these arguments max_train_size=199, test_size=73 to reach desired results, but it's very tricky and I couldn't figure it out. in fact, I applied time-series-based data split using TSS CV methods before training RF regressor to train-set (first 200 days\observations) and fit model over test-set (last 74 days\observations). I've tried recommended TimeSeriesSplit() as the following unsuccessfully: import numpy as np import pandas as pd import matplotlib.pyplot as plt #Load the time-series data as dataframe df = pd.read_csv('/content/U2996_24hrs_.csv', sep=",") print(df.shape) #Try to split data with CV (K-Fold) by using TimeSeriesSplit() method from sklearn.model_selection import TimeSeriesSplit tscv = TimeSeriesSplit( n_splits=len(df['TS_24hrs'].unique()) - 1, gap=0, # since data alraedy groupedby for 24hours to retrieve daily count there is no need to to have gap #max_train_size=199, #here: https://stackoverflow.com/a/43326651/10452700 they recommended to set this argument I'm unsure if it is the case for my problem #test_size=73, ) for train_idx, test_idx in tscv.split(df['TS_24hrs']): print('TRAIN: ', df.loc[df.index.isin(train_idx), 'TS_24hrs'].unique(), 'val-TEST: ', df.loc[df.index.isin(test_idx), 'TS_24hrs'].unique()) The following figures for understanding and better alignment of split data could be part of the expected output if one could plot for each method: expected output: References: Using k-fold cross-validation for time-series model selection Cross validation with time series [duplicate] Time series k-fold cross validation for classification How many folds for (time series) cross validation Cross Validation for Time Series Classification (Not Forecasting!) Edit1: I found 3 related posts: post1 post2 I decided to apply TimeSeriesSplit() in short TTS cv output within for loop to train\fit regression model over training-set with assist of CV-set then predict() over Hold-on test-set. The current output of my implementation shows slightly improvement in forecasting with or without, which could be due to problems in my implementation. #Load the time-series data as dataframe import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('/content/U2996_24hrs_.csv', sep=",") #print(df.shape) #(274, 2) #####----------------------------without CV # Split the data into training and testing sets from sklearn.model_selection import train_test_split train, test = train_test_split(df, test_size=0.27, shuffle=False) print(train.shape) #(200, 2) print(test.shape) #(74, 2) #visulize splitted data #train['count'].plot(label='Training-set') #test['count'].plot(label='Test-set') #plt.legend() #plt.show() #Train and fit the model from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor().fit(train, train['count']) #X, y rf.score(train, train['count']) #0.9998644192184375 # Use the forest's model to predict on the test-set predictions = rf.predict(test) #convert prediction result into dataframe for plot issue in ease df_pre = pd.DataFrame({'TS_24hrs':test['TS_24hrs'], 'count_prediction':predictions}) # Calculate the mean absolute errors from sklearn.metrics import mean_absolute_error rf_mae = mean_absolute_error(test['count'], df_pre['count_prediction']) #####----------------------------with CV df1 = df[:200] #take just first 1st 200 records #print(df1.shape) #(200, 2) #print(len(df1)) #200 from sklearn.model_selection import TimeSeriesSplit tscv = TimeSeriesSplit( n_splits=len(df1['TS_24hrs'].unique()) - 1, #n_splits=3, gap=0, # since data alraedy groupedby for 24hours to retrieve daily count there is no need to to have gap #max_train_size=199, #test_size=73, ) #print(type(tscv)) #<class 'sklearn.model_selection._split.TimeSeriesSplit'> #mae = [] cv = [] TS_24hrs_tss = [] predictions_tss = [] for train_index, test_index in tscv.split(df1): cv_train, cv_test = df1.iloc[train_index], df1.iloc[test_index] #cv.append(cv_test.index) #print(cv_train.shape) #(199, 2) #print(cv_test.shape) #(1, 2) TS_24hrs_tss.append(cv_test.values[:,0]) #Train and fit the model from sklearn.ensemble import RandomForestRegressor rf_tss = RandomForestRegressor().fit(cv_train, cv_train['count']) #X, y # Use the forest's model to predict on the cv_test predictions_tss.append(rf_tss.predict(cv_test)) #print(predictions_tss) # Calculate the mean absolute errors #from sklearn.metrics import mean_absolute_error #rf_tss_mae = mae.append(mean_absolute_error(cv_test, predictions_tss)) #print(rf_tss_mae) #print(len(TS_24hrs_tss)) #199 #print(type(TS_24hrs_tss)) #<class 'list'> #print(len(predictions_tss)) #199 #convert prediction result into dataframe for plot issue in ease import pandas as pd df_pre_tss1 = pd.DataFrame(TS_24hrs_tss) df_pre_tss1.columns =['TS_24hrs_tss'] #df_pre_tss1 df_pre_tss2 = pd.DataFrame(predictions_tss) df_pre_tss2.columns =['count_predictioncv_tss'] #df_pre_tss2 df_pre_tss= pd.concat([df_pre_tss1,df_pre_tss2], axis=1) df_pre_tss # Use the forest's model to predict on the hold-on test-set predictions_tsst = rf_tss.predict(test) #print(len(predictions_tsst)) #74 #convert prediction result of he hold-on test-set into dataframe for plot issue in ease df_pre_test = pd.DataFrame({'TS_24hrs_tss':test['TS_24hrs'], 'count_predictioncv_tss':predictions_tsst}) # Fix the missing record (1st record) df_col_merged = df_pre_tss.merge(df_pre_test, how="outer") #print(df_col_merged.shape) #(273, 2) 1st record is missing ddf = df_col_merged.rename(columns={'TS_24hrs_tss': 'TS_24hrs', 'count_predictioncv_tss': 'count'}) df_first= df.head(1) df_merged_pred = df_first.merge(ddf, how="outer") #insert first record from original df to merged ones #print(df_merged_pred.shape) #(274, 2) print(train.shape) #(200, 2) print(test.shape) #(74, 2) print(df_pre_test.shape) #(74, 2) # Calculate the mean absolute errors from sklearn.metrics import mean_absolute_error rf_mae_tss = mean_absolute_error(test['count'], df_pre_test['count_predictioncv_tss']) #visulize forecast or prediction of used regressor model train['count'].plot(label='Training-set', alpha=0.5) test['count'].plot(label='Test-set', alpha=0.5) #cv['count'].plot(label='cv TSS', alpha=0.5) df_pre['count_prediction'].plot(label=f'RF_forecast MAE={rf_mae:.2f}', alpha=0.5) df_pre_test['count_predictioncv_tss'].plot(label=f'RF_forecast_tss MAE={rf_mae_tss:.2f}', alpha=0.5 , linestyle='--') plt.legend() plt.title('Plot forecast results with & without cross-validation (K-Fold)') plt.show() post3 sklearn (I couldn't implement it, one can try this) using make_pipeline() and use def evaluate(model, X, y, cv): function but still confusing if I want to collect the results in the form of dataframe for visualizing case and what is the best practice to pass cv result to regressor and compare the results. Edit2: In the spirit of DRY, I tried to build an end-to-end pipeline without/with CV methods, load a dataset, perform feature scaling and supply the data into a regression model: #Load the time-series data as dataframe import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('/content/U2996_24hrs_.csv', sep=",") #print(df.shape) #(274, 2) #####--------------Create pipeline without CV------------ # Split the data into training and testing sets for just visualization sense from sklearn.model_selection import train_test_split train, test = train_test_split(df, test_size=0.27, shuffle=False) print(train.shape) #(200, 2) print(test.shape) #(74, 2) from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.ensemble import RandomForestRegressor from sklearn.pipeline import Pipeline # Split the data into training and testing sets without CV X = df['TS_24hrs'].values y = df['count'].values print(X_train.shape) #(200, 1) print(y_train.shape) #(200,) print(X_test.shape) #(74, 1) print(y_test.shape) #(74,) # Here is the trick X = X.reshape(-1,1) X_train, X_test, y_train, y_test = train_test_split(X, y , test_size=0.27, shuffle=False, random_state=0) print(X_train.shape) #(200, 1) print(y_train.shape) #(1, 200) print(X_test.shape) #(74, 1) print(y_test.shape) #(1, 74) #build an end-to-end pipeline, and supply the data into a regression model. It avoids leaking the test set into the train set rf_pipeline = Pipeline([('scaler', MinMaxScaler()),('RF', RandomForestRegressor())]) rf_pipeline.fit(X_train, y_train) #Displaying a Pipeline with a Preprocessing Step and Regression from sklearn import set_config set_config(display="diagram") rf_pipeline # click on the diagram below to see the details of each step r2 = rf_pipeline.score(X_test, y_test) print(f"RFR: {r2}") # -0.3034887940244342 # Use the Randomforest's model to predict on the test-set y_predictions = rf_pipeline.predict(X_test.reshape(-1,1)) #convert prediction result into dataframe for plot issue in ease df_pre = pd.DataFrame({'TS_24hrs':test['TS_24hrs'], 'count_prediction':y_predictions}) # Calculate the mean absolute errors from sklearn.metrics import mean_absolute_error rf_mae = mean_absolute_error(y_test, df_pre['count_prediction']) print(train.shape) #(200, 2) print(test.shape) #(74, 2) print(df_pre.shape) #(74, 2) #visulize forecast or prediction of used regressor model train['count'].plot(label='Training-set') test['count'].plot(label='Test-set') df_pre['count_prediction'].plot(label=f'RF_forecast MAE={rf_mae:.2f}') plt.legend() plt.title('Plot results without cross-validation (K-Fold) using pipeline') plt.show() #####--------------Create pipeline with TSS CV------------ #####--------------Create pipeline with BTSS CV------------ The results got worse using the pipeline, based on MAE score comparing implementation when separating the steps outside of the pipeline!
Considering the argues in the comments and assist of @igrinis and found a possible solution addressed in Edit1/post2, I came up with the following implementation to: meet the declared forecasting strategy: ... training RF regressor to train-set (first 200 days\observations) and fit model over test-set (last 74 days\observations). use TSS class: TimeSeriesSplit() #Load the time-series data as dataframe import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('/content/U2996_24hrs_.csv', sep=",") # Select the first 200 observations df200 = df[:200] # Split the data into training and testing sets from sklearn.model_selection import train_test_split #X_train, X_test, y_train, y_test = train_test_split(X, y , test_size=0.27, shuffle=False, random_state=0) train, validation = train_test_split(df200 , test_size=0.2, shuffle=False) test = df[200:] #print(train.shape) #(160, 2) #print(validation.shape) #(40, 2) #print(test.shape) #(74, 2) #hold-on (unseen data) #Train and fit the RF model from sklearn.ensemble import RandomForestRegressor #rf_model = RandomForestRegressor().fit(train, train['count']) #X, y # calculate R2 score using model #r2_train = rf_model.score(train, train['count']) #print(f"RFR_train: {r2_train:.4f}") #RFR_train: 0.9995 #r2_validation = rf_model.score(validation, validation['count']) #print(f"RFR_val: {r2_validation:.4f}") #RFR_val: 0.9972 #r2_test = rf_model.score(test, test['count']) #print(f"RFR_test: {r2_test:.4f}") #RFR_test: 0.5967 # Use the forest's model to predict on the validation-set and test-set #predictions_val = rf_model.predict(validation) #predictions_test = rf_model.predict(test) #build an end-to-end pipeline, and supply the data into a regression model and train within pipeline. It avoids leaking the test\val-set into the train-set from sklearn.preprocessing import MinMaxScaler from sklearn.ensemble import RandomForestRegressor from sklearn.pipeline import Pipeline, make_pipeline rf_pipeline = Pipeline([('scaler', MinMaxScaler()),('RF', RandomForestRegressor())]).fit(train, train['count']) #X, y #Displaying a Pipeline with a Preprocessing Step and Regression from sklearn import set_config set_config(display="text") #print(rf_pipeline) # Pipeline(steps=[('scaler', MinMaxScaler()), ('RF', RandomForestRegressor())]) # calculate R2 score using pipeline #r2_train = rf_pipeline.score(train, train['count']) #print(f"RFR_train: {r2_train:.4f}") #RFR_train: 0.9995 #r2_validation = rf_pipeline.score(validation, validation['count']) #print(f"RFR_val: {r2_validation:.4f}") #RFR_val: 0.9972 #r2_test = rf_pipeline.score(test, test['count']) #print(f"RFR_test: {r2_test:.4f}") #RFR_test: 0.5967 # Use the pipeline to predict over the validation-set and test-set y_predictions_val = rf_pipeline.predict(validation) y_predictions_test = rf_pipeline.predict(test) from sklearn.model_selection import TimeSeriesSplit tscv = TimeSeriesSplit(n_splits = 5) rf_pipeline_tss = Pipeline([('scaler', MinMaxScaler()),('RF', RandomForestRegressor())]) rf_mae_test_tss = [] tss_cv_test_index = [] for train_index, test_index in tscv.split(df200): cv_train, cv_test = df200.iloc[train_index], df200.iloc[test_index] #print(f"cv_train: {cv_train.shape}") #print(f"cv_test: {cv_test.shape}") #print(f"cv_test_index: {cv_test.index}") rf_pipeline_tss.fit(cv_train, cv_train['count']) predictions_tss = rf_pipeline_tss.predict(cv_test) rf_mae_test_tss.append(mean_absolute_error(cv_test['count'], predictions_tss)) tss_cv_test_index.append(list(cv_test.index)) print(rf_mae_test_tss) print(tss_cv_test_index) # Use the TSS-based pipeline to predict over the hold-on (unseen) test-set y_predictions_test_tss = rf_pipeline_tss.predict(test) Similarly, one can use BTSS class within the for-loop to train the model in the pipeline. The following visualisation of the final forecast : Note: I calculate the mean of splits (K-folds): np.mean(rf_mae_test_tss) and reflect in legend in the plot.
4
0
75,813,474
2023-3-22
https://stackoverflow.com/questions/75813474/im-trying-to-scrape-a-bing-dict-page-with-beautifulsoup-however-response-cont
I'm trying to scrape a Bing dict page https://cn.bing.com/dict/search?q=avengers Here is the code import requests from bs4 import BeautifulSoup url = "https://cn.bing.com/dict/search?q=avengers" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" } response = requests.get(url, headers=headers) soup = BeautifulSoup(response.content, "html.parser") examples = soup.find_all("div", class_="sen_en b_regtxt") for example in examples: print(example.text.strip()) In particular, I'm trying scrape all the example sentences on that page, which is contained in a div with class sen_en b_regtxt However, response.content doesn't even contain one example sentence in it, what am I missing? PS, access to the page doesn't need login With @Artur Chukhrai's help, I also tried with selenium and I got "No results found for avenger" However, if I access the url "cn.bing.com/dict" first, and then put the keyword in the search box, I would get the result page.
A small modification to Arthur Chukhrai's answer works, by loading https://cn.bing.com/dict and then writing the text in the search box: from selenium import webdriver from selenium.webdriver.common.by import By from bs4 import BeautifulSoup import time url = "https://cn.bing.com/dict/" # Start a new Selenium web driver instance driver = webdriver.Chrome() driver.get(url) # Wait for the page to load time.sleep(5) # Write text in search box search_box = driver.find_element(By.CLASS_NAME, value="b_searchbox") search_box.send_keys("avengers\n") # Wait for the page to load time.sleep(5) # Get the page source after it has fully loaded html = driver.page_source soup = BeautifulSoup(html, "html.parser") # Find and print the examples of the word examples = soup.select(".sen_en") for example in examples: print(example.text.strip()) # Quit the web driver instance driver.quit()
5
3
75,861,726
2023-3-28
https://stackoverflow.com/questions/75861726/multiple-callbacks-to-filter-data-dash-plotly
I'm hoping to include multiple callbacks or combine them to filter data. These functions will be used to visualise graphs. The first callback returns point data if it's within a designated region. It is assigned to a dropdown bar called area-dropdown. The dropdown bar and callback function returns smaller subsets from the main df. This is accomplished by merging the point data within a specific polygon area. The additional callback functions are for a scatter mapbox chart and bar chart. They filter unique values in Code and Cat. At present, I've got the callback functions that filter unique values in Code and Cat operational. This is outlined in the 2nd batch of code. If I comment this section out and use the 1st batch of code, the area dropdown callback is functional. I'm aiming to find a method that combines both these functions together. import geopandas as gpd import plotly.express as px import dash from dash import dcc, html, Input, Output import dash_bootstrap_components as dbc from dash.dependencies import Input, Output import dash_bootstrap_components as dbc import plotly.express as px import plotly.graph_objs as go import plotly.figure_factory as ff import geopandas as gpd from itertools import cycle # point data gdf_all = gpd.read_file(gpd.datasets.get_path("naturalearth_cities")) i = iter(['A', 'B', 'C', 'D']) gdf_all['Cat'] = gdf_all.index.map(dict(zip(gdf_all.index, cycle(i)))) j = iter(['10-20', '20-30', '30-40', '40-50', '60-70']) gdf_all['Code'] = gdf_all.index.map(dict(zip(gdf_all.index, cycle(j)))) # polygon data gdf_poly = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")) gdf_poly = gdf_poly.drop('name', axis = 1) gdf_all['LON'] = gdf_all['geometry'].x gdf_all['LAT'] = gdf_all['geometry'].y # subset African continent Afr_gdf_area = gdf_poly[gdf_poly['continent'] == 'Africa'].reset_index(drop = True) # subset European continent Eur_gdf_area = gdf_poly[gdf_poly['continent'] == 'Europe'].reset_index(drop = True) # function to merge point data within selected polygon area def merge_withinboundary(gdf1, gdf2): # spatial join data within larger boundary gdf_out = gpd.sjoin(gdf1, gdf2, predicate = 'within', how = 'inner').reset_index(drop = True) return gdf_out gdf_Africa = merge_withinboundary(gdf_all, Afr_gdf_area) gdf_Europe = merge_withinboundary(gdf_all, Eur_gdf_area) external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP] app = dash.Dash(__name__, external_stylesheets = external_stylesheets) nav_bar = html.Div([ html.P("area-dropdown:"), dcc.Dropdown( id = 'data', value = 'data', options = [{'value': 'gdf_all', 'label': 'gdf_all'}, {'value': 'gdf_Africa', 'label': 'gdf_Africa'}, {'value': 'gdf_Europe', 'label': 'gdf_Europe'} ], clearable=False ), html.Label('Code', style = {'paddingTop': '1rem'}), dcc.Checklist( id = 'Code', options = [ {'label': '10-20', 'value': '10-20'}, {'label': '20-30', 'value': '20-30'}, {'label': '30-40', 'value': '30-40'}, {'label': '40-50', 'value': '40-50'}, {'label': '60-70', 'value': '60-70'}, ], value = ['10-20', '20-30', '30-40', '40-50', '60-70'], style = {'display': 'inline', 'margin-right': '50px'} ), html.Label('Cat', style = {'paddingTop': '1rem'}), dcc.Checklist( id = 'Cat', options = [ {'label': 'A', 'value': 'A'}, {'label': 'B', 'value': 'B'}, {'label': 'C', 'value': 'C'}, {'label': 'D', 'value': 'D'}, ], value = ['A', 'B', 'C', 'D'], style = {'display': 'inline', 'margin-right': '50px'} ), html.Label('Spatial Map', style = {'paddingTop': '1rem'}), dcc.RadioItems(['Scatter','Hexbin'],'Scatter', id = 'maps', #labelStyle= {"margin":"1rem"}, style = {'display': 'inline', 'margin-right': '50px'} ), ], className = "vstack gap-2 h-50") app.layout = dbc.Container([ dbc.Row([ dbc.Col(html.Div(nav_bar), className = 'bg-light', width=2), dbc.Col([ dbc.Row([ dbc.Col(dcc.Graph(id = 'spatial-chart')) ]), dbc.Row([ dbc.Col(dcc.Graph(id = 'bar-chart')) ]), ], width = 5), dbc.Col([ ], width = 5), ]) ], fluid = True) df = gdf_all #================ 1st ======================= # function to return selected df for plotting #@app.callback(Output('spatial-chart', 'figure'), # Output('bar-chart', 'figure'), # Input('data', 'value'), # prevent_initial_call=True) # function to return df using smaller areas #def update_dataset(dropdown_selection): # if dropdown_selection == 'gdf_Africa': # gdf = gdf_Africa # zoom = 2 # elif dropdown_selection == 'gdf_Europe': # gdf = gdf_Europe # zoom = 2 # else: # gdf = gdf_all # zoom = 0 # scatter_subset = px.scatter_mapbox(data_frame = gdf, # lat = 'LAT', # lon = 'LON', # zoom = zoom, # mapbox_style = 'carto-positron', # ) # count = gdf['name'].value_counts() # bar_subset = px.bar(x = count.index, # y = count.values, # color = count.index, # ) # return scatter_subset, bar_subset #============================================= #================ 2nd ======================= # function to filter unique Cat/Code for bar chart @app.callback( [Output('bar-chart', 'figure'), ], [Input('Cat','value'), Input('Code','value'), ] ) def date_chart(cat, code): dff = df[df['Cat'].isin(cat)] dff = dff[dff['Code'].isin(code)] count = dff['Cat'].value_counts() data = px.bar(x = count.index, y = count.values, color = count.index, ) fig = [go.Figure(data = data)] return fig # function to filter unique Cat/Code for scatter @app.callback( [Output('spatial-chart', 'figure'), ], [Input('Cat','value'), Input('Code','value'), Input("maps", "value"), ]) def scatter_chart(cat, code, maps): if maps == 'Scatter': dff = df[df['Cat'].isin(cat)] dff = dff[dff['Code'].isin(code)] data = px.scatter_mapbox(data_frame = dff, lat = 'LAT', lon = 'LON', color = 'Cat', opacity = 0.5, zoom = 1, mapbox_style = 'carto-positron', hover_name = 'Cat', ) fig = [go.Figure(data = data)] elif maps == 'Hexbin': dff = df[df['Cat'].isin(cat)] dff = dff[dff['Code'].isin(code)] data = ff.create_hexbin_mapbox(data_frame = dff, lat = "LAT", lon = "LON", nx_hexagon = 100, min_count = 1, ) fig = [go.Figure(data = data)] return fig #============================================= if __name__ == '__main__': app.run_server(debug=True, port = 8051)
I combined your callback functions update_dataset, date_chart and scatter_chart into a single callback. This function processes the dropdown selection, both checklists, and the radioitem components and outputs the updated scatter mapbox and bar charts. import geopandas as gpd import plotly.express as px import dash from dash import dcc, html, Input, Output import dash_bootstrap_components as dbc from dash.dependencies import Input, Output import dash_bootstrap_components as dbc import plotly.express as px import plotly.graph_objs as go import plotly.figure_factory as ff import geopandas as gpd from itertools import cycle # point data gdf_all = gpd.read_file(gpd.datasets.get_path("naturalearth_cities")) i = iter(['A', 'B', 'C', 'D']) gdf_all['Cat'] = gdf_all.index.map(dict(zip(gdf_all.index, cycle(i)))) j = iter(['10-20', '20-30', '30-40', '40-50', '60-70']) gdf_all['Code'] = gdf_all.index.map(dict(zip(gdf_all.index, cycle(j)))) # polygon data gdf_poly = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")) gdf_poly = gdf_poly.drop('name', axis = 1) gdf_all['LON'] = gdf_all['geometry'].x gdf_all['LAT'] = gdf_all['geometry'].y # subset African continent Afr_gdf_area = gdf_poly[gdf_poly['continent'] == 'Africa'].reset_index(drop = True) # subset European continent Eur_gdf_area = gdf_poly[gdf_poly['continent'] == 'Europe'].reset_index(drop = True) # function to merge point data within selected polygon area def merge_withinboundary(gdf1, gdf2): # spatial join data within larger boundary gdf_out = gpd.sjoin(gdf1, gdf2, predicate = 'within', how = 'inner').reset_index(drop = True) return gdf_out gdf_Africa = merge_withinboundary(gdf_all, Afr_gdf_area) gdf_Europe = merge_withinboundary(gdf_all, Eur_gdf_area) external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP] app = dash.Dash(__name__, external_stylesheets = external_stylesheets) nav_bar = html.Div([ html.P("area-dropdown:"), dcc.Dropdown( id = 'data', value = 'data', options = [{'value': 'gdf_all', 'label': 'gdf_all'}, {'value': 'gdf_Africa', 'label': 'gdf_Africa'}, {'value': 'gdf_Europe', 'label': 'gdf_Europe'} ], clearable=False ), html.Label('Code', style = {'paddingTop': '1rem'}), dcc.Checklist( id = 'Code', options = [ {'label': '10-20', 'value': '10-20'}, {'label': '20-30', 'value': '20-30'}, {'label': '30-40', 'value': '30-40'}, {'label': '40-50', 'value': '40-50'}, {'label': '60-70', 'value': '60-70'}, ], value = ['10-20', '20-30', '30-40', '40-50', '60-70'], style = {'display': 'inline', 'margin-right': '50px'} ), html.Label('Cat', style = {'paddingTop': '1rem'}), dcc.Checklist( id = 'Cat', options = [ {'label': 'A', 'value': 'A'}, {'label': 'B', 'value': 'B'}, {'label': 'C', 'value': 'C'}, {'label': 'D', 'value': 'D'}, ], value = ['A', 'B', 'C', 'D'], style = {'display': 'inline', 'margin-right': '50px'} ), html.Label('Spatial Map', style = {'paddingTop': '1rem'}), dcc.RadioItems(['Scatter','Hexbin'],'Scatter', id = 'maps', #labelStyle= {"margin":"1rem"}, style = {'display': 'inline', 'margin-right': '50px'} ), ], className = "vstack gap-2 h-50") app.layout = dbc.Container([ dbc.Row([ dbc.Col(html.Div(nav_bar), className = 'bg-light', width=2), dbc.Col([ dbc.Row([ dbc.Col(dcc.Graph(id = 'spatial-chart')) ]), dbc.Row([ dbc.Col(dcc.Graph(id = 'bar-chart')) ]), ], width = 5), dbc.Col([ ], width = 5), ]) ], fluid = True) df = gdf_all @app.callback( [Output('bar-chart', 'figure'), Output('spatial-chart', 'figure'), ], [Input('data', 'value'), Input('Cat', 'value'), Input('Code','value'), Input('maps', 'value'), ] ) def update_charts(dropdown_selection, cat, code, maps): ## dropdown defines df before the other inputs subset it further if dropdown_selection == 'gdf_Africa': df = gdf_Africa zoom = 2 elif dropdown_selection == 'gdf_Europe': df = gdf_Europe zoom = 2 else: df = gdf_all zoom = 0 dff = df[df['Cat'].isin(cat)] dff = dff[dff['Code'].isin(code)] count = dff['Cat'].value_counts() data = px.bar(x = count.index, y = count.values, color = count.index, ) fig_bar = go.Figure(data = data) if maps == 'Scatter': dff = df[df['Cat'].isin(cat)] dff = dff[dff['Code'].isin(code)] data = px.scatter_mapbox(data_frame = dff, lat = 'LAT', lon = 'LON', color = 'Cat', opacity = 0.5, zoom = 1, mapbox_style = 'carto-positron', hover_name = 'Cat', ) fig_mapbox = go.Figure(data = data) elif maps == 'Hexbin': dff = df[df['Cat'].isin(cat)] dff = dff[dff['Code'].isin(code)] data = ff.create_hexbin_mapbox(data_frame = dff, lat = "LAT", lon = "LON", nx_hexagon = 100, min_count = 1, ) fig_mapbox = go.Figure(data = data) return fig_bar, fig_mapbox if __name__ == '__main__': app.run_server(debug=True, port = 8051)
3
2
75,848,129
2023-3-26
https://stackoverflow.com/questions/75848129/how-to-apply-rate-limit-based-on-method-parameter
I'm using the python module ratelimit to throttle a function, which calls a rest api, I need to apply throttle based on the method of the requests, e.g. for PUT/POST/DELETE 1 per 10s, for GET 5 per 1s, how can I achieve this without breaking the function into two? from ratelimit import limits, sleep_and_retry @sleep_and_retry @limits(calls=1 if method != 'GET' else 5, period=10 if method != 'GET' else 1) def callrest(method, url, data): ... Is it possible to do this?
You don't have to re-invent the wheel by creating your own rate limiter when ratelimit already works well. To apply different rate limits based on the method argument passed in, make a decorator that creates two ratelimit.limits-decorated functions from the given function--one decorated with arguments needed by the GET method, and the other decorated with those needed by non-GET methods. Then make the decorator return a wrapper function that calls one of the two decorated functions above according to the value of the method argument: from ratelimit import limits, sleep_and_retry def limits_by_method(func): def wrapper(method, *args, **kwargs): return (get if method == 'GET' else non_get)(method, *args, **kwargs) get = limits(calls=5, period=1)(func) non_get = limits(calls=1, period=10)(func) return wrapper @sleep_and_retry @limits_by_method def callrest(method, url, data): ... Demo: https://replit.com/@blhsing/ExoticWretchedAdvance
4
8
75,821,466
2023-3-23
https://stackoverflow.com/questions/75821466/python-render-svg-image-with-the-python-only-modules
The question is simple, but I have googled a lot of methods, and there no such solution as: import svg-render-library figure = svg-render-library.open('test.svg') figure.render() Is there any simple methods to display an SVG image using only python libraries? I am asking about rendering the SVG image without any conversion to another formats and to render using pure python, without any 3rd party software. As I have tried, this seems impossible for now. As built-in python I mean - only python packages available through pip, so it is not necessary to install/compile anything else. And to render I mean to show inside window which part of the python, not the browser or any external software. At least I have currently working solution my question on Stack Overflow.
Currently, there is no method to render natively cross-platform with just the standard library (ie. some python distributions for OSX do not include tkinter by default). Ergo, there is no good way to do this. AFAIK, there are no other ways to do this maintaining your described API without writing your own code or reaching out to non-standard library modules. If you still are 100% set on doing it with pure python and the standard library, you have tkinter, and don't care about writing your own implementation, then proceed. If you are talking about rendering in the context of displaying an SVG in a window, then your best bet would be to utilize the tkinter and xml modules. SVG is just an XML file, so xml.minidom should be able to parse an svg file. You can then extract the height and width from the dom, draw each element onto a tkinter.Canvas widget, and then have tkinter render the window. You will need to either pre-calculate transparencies or handle that while managing the layering. Another option is to use the turtle package which wraps around tkinter. If the SVG is just a path, then this should be able to draw that path fairly straight forward. If you are willing to reach out beyond the standard library, then cairosvg or svglib both can easily handle this task. cairosvg is a bit of a bear if you aren't used to installing system libraries, but svglib is a pure python implementation.
7
1
75,820,558
2023-3-23
https://stackoverflow.com/questions/75820558/how-to-create-a-table-with-buttons-element-in-a-column-with-pynecone
The table's last column (action) contains pc.button, that can get data in the row that the button residing in, and then send that data to a State variable. Some thing like this: name age job action John 20 Developer Update May 23 Designer Update I have tried pc.list like this: return pc.center( pc.list([ ["name","age","job","action"], ["John",20, "Developer", pc.button("Update", on_click=State.update_employee)], ["May",23, "Designer", pc.button("Update", on_click=State.update_employee)], ]) ) but pc.list can only take in python primitive types (str,int,float...). Is there any way to add multiple components progamatically to another Pynecone component
https://youtube.com/shorts/u-TUSQ9DkCw <-- Example here I write the following full example for what you want. The simple answer is to use table_container. But we need to care about some detail. from pcconfig import config import pynecone as pc class Member(pc.Model, table=True): ename:str # The attribute cannot be call "name", so we use ename here age:int job:str def __init__(self, ename,age,job): self.ename=ename self.age =age self.job =job def __repr__(self) -> str: return "("+self.ename+","+self.age+","+self.job+")" class State(pc.State): members:list[Member] = [ Member("John",20,"Developer"), Member("May",23,"Design"), Member("Milo",18,"Teacher"), Member("Aloha",48,"CEO"), ] def delete_member(self,member_name:str): del_idx:int = -1 for i in range(len(self.members)): if(self.members[i].ename == member_name): del_idx = i break if(del_idx > -1): del self.members[del_idx] return def index() -> pc.Component: return pc.center( pc.vstack( pc.vstack( pc.hstack( pc.heading("Members"), ), pc.table_container( pc.table( pc.thead( pc.tr( pc.th("Name"), pc.th("Age"), pc.th("Job"), pc.th("Action"), ) ), pc.tbody( pc.foreach( State.members, lambda member: pc.tr( pc.td(member.ename), pc.td(member.age), pc.td(member.job), pc.td( pc.button( "Delete", on_click=lambda: State.delete_member(member.ename), bg="red", color="white", ) ), ) ) ), ), bg="#F7FAFC ", border="1px solid #ddd", border_radius="25px", ), align_items="left", padding_top="7em", ), ), padding="1em", ) # Add state and page to the app. app = pc.App(state=State) app.add_page(index, title="table container") app.compile() (1) You need to define a class. In my case, it is Member(pc.Model, table=True). You must add (pc.Model, table=True) Can we use [list[list[str]] to represent the self.members? The answer is NO. That's we we use members:list[Member] in State but not members:list[list[str]]. (2) When your code satisfies the above condition 1, then we can use pc.foreach() to generate table's data in UI. pc.foreach( State.members, lambda member: pc.tr( pc.td(member.ename), pc.td(member.age), pc.td(member.job), pc.td( pc.button( "Delete", on_click=lambda: State.delete_member(member.ename), bg="red", color="white", ) ), ) )
3
3
75,839,825
2023-3-25
https://stackoverflow.com/questions/75839825/how-to-prevent-transformer-generate-function-to-produce-certain-words
I have the following code: from transformers import T5Tokenizer, T5ForConditionalGeneration tokenizer = T5Tokenizer.from_pretrained("t5-small") model = T5ForConditionalGeneration.from_pretrained("t5-small") input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids sequence_ids = model.generate(input_ids) sequences = tokenizer.batch_decode(sequence_ids) sequences Currently it produces this: ['<pad><extra_id_0> park offers<extra_id_1> the<extra_id_2> park.</s>'] Is there a way to prevent the generator to produce certain words (e.g. stopwords = ["park", "offer"])?
after looking at the docs found out there is a bad_words_ids parameter that you can pass in the generate() given a bad word list you can create the id list using tokenizer(bad_words, add_special_tokens=False).input_ids input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids bad_words = ["park", "offers"] bad_words_ids = tokenizer(bad_words, add_special_tokens=False).input_ids #[[2447], [704]] sequence_ids = model.generate(input_ids, bad_words_ids=bad_words_ids) #tensor([[ 0, 32099, 1061, 19, 3, 9, 710, 1482, 550, 45, 32098, 8, 32097, 1061, 5, 1]]) sequences = tokenizer.batch_decode(sequence_ids) print(sequences) #['<pad><extra_id_0> Park is a short walk away from<extra_id_1> the<extra_id_2> Park.</s>'] Notice how the word "Park" is appearing now. This is because the tokenizer identifies park (id 2447) and Park (id 1061) as 2 different tokens. This may depend on the tokenizer you use (there are case-insensitive tokenizers). If you don't want this to happen you can add Park into the bad word list as well. Colab demo
3
5
75,845,842
2023-3-26
https://stackoverflow.com/questions/75845842/is-the-default-trainer-class-in-huggingface-transformers-using-pytorch-or-tens
Question According to the official documentation, the Trainer class "provides an API for feature-complete training in PyTorch for most standard use cases". However, when I try to actually use Trainer in practice, I get the following error message that seems to suggest that TensorFlow is currently being used under the hood. tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. So which one is it? Does the HuggingFace transformers library use PyTorch or TensorFlow for their internal implementation of Trainer? And is it possible to switch to only using PyTorch? I can't seem to find a relevant parameter in TrainingArguments. Why does my script keep printing out TensorFlow related errors? Shouldn't Trainer be using PyTorch only? Source code from transformers import GPT2Tokenizer from transformers import GPT2LMHeadModel from transformers import TextDataset from transformers import DataCollatorForLanguageModeling from transformers import Trainer from transformers import TrainingArguments import torch # Load the GPT-2 tokenizer and LM head model tokenizer = GPT2Tokenizer.from_pretrained('gpt2') lmhead_model = GPT2LMHeadModel.from_pretrained('gpt2') # Load the training dataset and divide blocksize train_dataset = TextDataset( tokenizer=tokenizer, file_path='./datasets/tinyshakespeare.txt', block_size=64 ) # Create a data collator for preprocessing batches data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=False ) # Defining the training arguments training_args = TrainingArguments( output_dir='./models/tinyshakespeare', # output directory for checkpoints overwrite_output_dir=True, # overwrite any existing content per_device_train_batch_size=4, # sample batch size for training dataloader_num_workers=1, # number of workers for dataloader max_steps=100, # maximum number of training steps save_steps=50, # after # steps checkpoints are saved save_total_limit=5, # maximum number of checkpoints to save prediction_loss_only=True, # only compute loss during prediction learning_rate=3e-4, # learning rate fp16=False, # use 16-bit (mixed) precision optim='adamw_torch', # define the optimizer for training lr_scheduler_type='linear', # define the learning rate scheduler logging_steps=5, # after # steps logs are printed report_to='none', # report to wandb, tensorboard, etc. ) if __name__ == '__main__': torch.multiprocessing.freeze_support() trainer = Trainer( model=lmhead_model, args=training_args, data_collator=data_collator, train_dataset=train_dataset, ) trainer.train()
It depends on how the model is trained and how you load the model. Most popular models on transformers supports both PyTorch and Tensorflow (and sometimes also JAX). from transformers import AutoTokenizer, AutoModelForSeq2SeqLM from transformers import TFAutoModelForSeq2SeqLM model_name = "google/flan-t5-large" model = AutoModelForSeq2SeqLM.from_pretrained(model_name) # This would work if the model's backend is PyTorch. print(type(next(model.parameters()))) tf_model = TFAutoModelForSeq2SeqLM.from_pretrained(model_name) # The `model.parameters()` would not work for Tensorflow, # instead you can try `.summary()` tf_model.summary() [out]: <class 'torch.nn.parameter.Parameter'> Model: "tft5_for_conditional_generation" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= shared (Embedding) multiple 32899072 encoder (TFT5MainLayer) multiple 341231104 decoder (TFT5MainLayer) multiple 441918976 lm_head (Dense) multiple 32899072 ================================================================= Total params: 783,150,080 Trainable params: 783,150,080 Non-trainable params: 0 _________________________________________________________________ Maybe something like: def which_backend(model): try: model.parameters() return 'torch' except: try: model.summary() return 'tensorflow' except: return 'I have no idea... Maybe JAX?' Q: So if I use Trainer, it's PyTorch? A: Yes, most probably the model has PyTorch backend, and the training loop (optimizer, loss, etc.) uses PyTorch. But the Trainer() isn't the model, it's the wrapper object. Q: And if I want to use Trainer for Tensorflow backend models, I should use TFTrainer? Not really. In the latest version of transformers, the TFTrainer object is deprecated, see https://github.com/huggingface/transformers/pull/12706 It is recommended that you use Keras' sklearn-style .fit() training if you are using a model with Tensorflow backend. https://huggingface.co/docs/transformers/tasks/sequence_classification https://huggingface.co/docs/transformers/training#train-a-tensorflow-model-with-keras Q: Why does my script keep printing out TensorFlow related errors? Shouldn't Trainer be using PyTorch only? Try checking your transformers version, most probably you are using an outdated version that uses some deprecated objects, e.g. TextDataset (see How to resolve "only integer tensors of a single element can be converted to an index" error when creating a Dataset to fine-tune GPT2 model?) In the later versions, most probably pip install transformers>=4.26.1, the Trainer shouldn't be activating TF warnings and using TFTrainer would have raised warnings to suggest users to use Keras instead.
4
5
75,866,093
2023-3-28
https://stackoverflow.com/questions/75866093/how-does-huggingfaces-zero-shot-classification-work-in-production-webapp-do-i
I have already used huggingface's zero-shot classification: I used "facebook/bart-large-mnli" model as reported here (https://huggingface.co/tasks/zero-shot-classification). The accuracy is quite good for my task. My question is about productionizing the code: In particular I would like to create a Gradio (or streamlit) webapp. Do I need to train the "facebook/bart-large-mnli" model first, secondly save the model in a pickle file, and then predict a new (unseen) sentence using the pickle file? Or can I simply import the "facebook/bart-large-mnli" library and compute the prediction for the production/webapp code? The latter scenario would be preferable. But I am not sure whether loading the model from scratch would produce the same output as loadingthe pickle file with the saved facebook/bart-large-mnli" model. Thank you in advance.
Q: How does zero-shot classification work? Do I need train/tune the model to use in production? Options: (i) train the "facebook/bart-large-mnli" model first, secondly save the model in a pickle file, and then predict a new (unseen) sentence using the pickle file? or (ii) can I simply import the "facebook/bart-large-mnli" library and compute the prediction for the production/webapp code? A (human): (ii) You can load up the model with pipeline("zero-shot-classification", model="facebook/bart-large-mnli") once when the server start, then reuse the pipeline without re-initializing it for each request. When you use the model off-the-shelf, it'll be zero-shot but if you fine-tune a model with limited training data, people commonly refer to that as "few-shot"; take a look at https://github.com/huggingface/setfit for few-shot learning. The proof is in the pudding, see if the model you pick fits the task you want. Also, there's more than one way to wield the shiny hammer =) Disclaimer: Your Miles May Vary... Zero shot classification TL;DR: I don't want to train anything, I don't have labeled data, do something with some labels that I come up with. from transformers import pipeline classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli") text = "Catan (Base Game) | Ages 10+ | for 3 to 4 Players | Average Playtime 60 Minutes | Made by Catan Studio | TRADE, BUILD AND SETTLE: Embark on a quest to settle the isle of Catan! Guide your settlers to victory by clever trading and cunning development. But beware! Someone might cut off your road or buy a monopoly. And you never know when the wily robber might steal some of your precious games!" candidate_labels = ['Beauty & Wellness', 'Electronics', 'Toys & Games'] classifier(text, candidate_labels) [out]: {'sequence': 'Catan (Base Game) | Ages 10+ | for 3 to 4 Players | Average Playtime 60 Minutes | Made by Catan Studio | TRADE, BUILD AND SETTLE: Embark on a quest to settle the isle of Catan! Guide your settlers to victory by clever trading and cunning development. But beware! Someone might cut off your road or buy a monopoly. And you never know when the wily robber might steal some of your precious games!', 'labels': ['Toys & Games', 'Electronics', 'Beauty & Wellness'], 'scores': [0.511284351348877, 0.38416239619255066, 0.10455326735973358]} Don't classify, translate (or seq2seq) Inspiration: https://arxiv.org/abs/1812.05774 from transformers import AutoTokenizer, AutoModelForSeq2SeqLM model_name = "google/flan-t5-large" tokenizer= AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) text = "Catan (Base Game) | Ages 10+ | for 3 to 4 Players | Average Playtime 60 Minutes | Made by Catan Studio | TRADE, BUILD AND SETTLE: Embark on a quest to settle the isle of Catan! Guide your settlers to victory by clever trading and cunning development. But beware! Someone might cut off your road or buy a monopoly. And you never know when the wily robber might steal some of your precious games!" prompt=f"""Which category is this product? QUERY:{text} OPTIONS: - Beauty & Wellness - Electronics - Toys & Games """ input_ids = tokenizer(prompt, return_tensors="pt").input_ids tokenizer.decode(model.generate(input_ids)[0], skip_special_tokens=True) [out]: Toys & Games And for the fun of it =) from transformers import AutoTokenizer, AutoModelForSeq2SeqLM model_name = "google/flan-t5-large" tokenizer= AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) prompt=f"""How does zero-shot classification work? QUERY: Do I need tune/modify the model to use in production? OPTIONS: - (i) train the "facebook/bart-large-mnli" model first, secondly save the model in a pickle file, and then predict a new (unseen) sentence using the pickle file - (ii) can I simply import the "facebook/bart-large-mnli" library and compute the prediction for the production/webapp code """ input_ids = tokenizer(prompt, return_tensors="pt").input_ids print(tokenizer.decode(model.generate(input_ids)[0], skip_special_tokens=True)) [out]: (ii) Q: What if both methods above don't work? A: Try more models from https://huggingface.co/models or try different tasks and be creative in how to use what's available to fit your data to solve the problem Q: What if none of the models/tasks works? A: Then it's time to think about what data you can/need to collect to train the model you need. But before collecting the data, it'll be prudent to first decide how you want to evaluate/measure the success of the model, e.g. F1-score, accuracy, etc. This is how I'll personally solve NLP problems that fits the frame "X problem, Y approach" solutions, https://hackernoon.com/what-kind-of-scientist-are-you (shameless plug) Q: How do I deploy a model after I found the model+task I want? There're several ways but it'll be out-of-scope of this question, since it's asking about how zero-shot works and more pertinently "Can I use zero-shot classification models off-the-shelf without training?". To deploy a model, take a look at: https://huggingface.co/docs/sagemaker/inference https://azure.microsoft.com/en-us/solutions/hugging-face-on-azure/ https://huggingface.co/inference-endpoints
4
9
75,870,293
2023-3-28
https://stackoverflow.com/questions/75870293/tkinter-share-single-frame-accross-multiple-tabs-or-dynamically-reparent
I have tkinter.Notebook that contains multiple tabs. I have tkinter.Frame "run box" with set of controls, that I want share across several tabs. Specifically Test info and Test list should have it. Currently I duplicate entire "run box" into each tab that needs it. And it works somewhat fine, but feels excessive and not right, because code behind "run box" controls is almost identical. Ideally I want this "run box" to be single instance and dynamically shown on active tab. Can anyone advise how to detach"run box" from one tab and re-attach to different tab? I would do that on Notebook switch event.
A widget can only be in one place at a time. There is no way to share a frame among multiple notebook tabs without removing it from one tab and adding it to another when the active tab changes. If that's what you want to do, you can create the "runbox" once, and then add a container to each tab to act as a placeholder. You can add a binding to the <Visibility> event to add the runbox to the placeholder when it becomes visible. This might cause some flickering as you switch tabs. The key to this working is to use the in_ parameter to pack which lets you pack one widget inside another widget. It also uses the lift mechanism to make sure that the "runbox" is higher in z-order than the placeholder. The runbox is re-packed whenever its visibility changes, by binding to the <Visibility> event. Here's an example. It creates a single instance of Runbox and swaps it between two tabs. import tkinter as tk from tkinter import ttk class RunParameters(): """Parameters to be shared by all tabs""" def __init__(self): self.magic_num = tk.IntVar(value=0) self.iter_count = tk.IntVar(value=1) self.duration = tk.IntVar(value=0) self.result = "fail" self.repeat = tk.BooleanVar(value=True) class Runbox(tk.Frame): def __init__(self, parent, run_parameters): super().__init__(parent) radiobuttons = [] for i in (range(8)): rb = tk.Radiobutton( self, text=i, variable=run_parameters.magic_num, value=i ) radiobuttons.append(rb) itercount_spinbox = tk.Spinbox( self, from_=1, to=100, textvariable=run_parameters.iter_count ) duration_spinbox = tk.Spinbox( self, from_=0, to=100, textvariable=run_parameters.duration ) radiobuttons[0].grid(row=0, column=0) radiobuttons[1].grid(row=0, column=1) radiobuttons[2].grid(row=0, column=2) radiobuttons[3].grid(row=0, column=3) radiobuttons[4].grid(row=1, column=0) radiobuttons[5].grid(row=1, column=1) radiobuttons[6].grid(row=1, column=2) radiobuttons[7].grid(row=1, column=3) itercount_spinbox.grid(row=3, column=0, columnspan=4) duration_spinbox.grid(row=4, column=0, columnspan=4) class TestInfo(tk.Frame): def __init__(self, parent, runbox): super().__init__(parent) self.runbox = runbox self._container = tk.Frame(self) label = tk.Label(self, text="Something unique to the Test Info tab") self._container.pack(side="top", fill="x") label.pack(side="bottom", fill="both", expand=True) self.bind("<Visibility>", self.on_vis) def on_vis(self, event): if self.winfo_viewable(): self.runbox.pack(in_=self._container, fill="both", expand=True) self.runbox.lift() class TestList(tk.Frame): def __init__(self, parent, runbox): super().__init__(parent) self.runbox = runbox self._container = tk.Frame(self) listbox = tk.Listbox(self) listbox.insert("end", "Test 1", "Test 2", "Test 3") self._container.pack(side="top", fill="x") listbox.pack(side="bottom", fill="both", expand=True) self.bind("<Visibility>", self.on_vis) def on_vis(self, event): if self.winfo_viewable(): self.runbox.pack(in_=self._container, fill="both", expand=True) self.runbox.lift() class Trace32(tk.Frame): pass class TMEConfig(tk.Frame): pass root = tk.Tk() params = RunParameters() nb = ttk.Notebook(root) nb.pack(fill="both", expand=True) runbox = Runbox(nb, params) test_info = TestInfo(nb, runbox = runbox) test_list = TestList(nb, runbox = runbox) trace32 = Trace32(nb) tme_config = TMEConfig(nb) nb.add(test_info, text="Test Info") nb.add(test_list, text="Test List") nb.add(trace32, text="Trace32") nb.add(tme_config, text="TME config") root.mainloop()
3
2
75,871,610
2023-3-28
https://stackoverflow.com/questions/75871610/spawning-a-new-process-with-an-asyncio-loop-from-within-the-asyncio-loop-running
I'm a little confused about the interaction between multiprocessing and asyncio. My goal is to be able to spawn async processes from other async processes. Here is a small example: import asyncio from multiprocessing import Process async def sleep_n(n): await asyncio.sleep(n) def async_sleep(n): # This does not work # # loop = asyncio.get_event_loop() # loop.run_until_complete(sleep_n(n)) # This works asyncio.run(sleep_n(n)) async def spawn_another(): await asyncio.sleep(0.2) p = Process(target=async_sleep, args=(5,)) p.start() p.join() def spawn(): # This does not work # loop = asyncio.get_event_loop() # loop.run_until_complete(spawn_another()) # This works asyncio.run(spawn_another()) def doit(): p = Process(target=spawn) p.start() p.join() if __name__ == '__main__': doit() If I replace asyncio.run with get_event_loop().run_until_complete, I get the following error: "The event loop is already running". This is raised from loop.run_until_complete(sleep_n(n)). What's the difference between these two? (NB: the reason I care about this is, if it makes a difference in the proposed remedy, is because in my actual code the thing I'm running in async is a grpc.aio client which apparently requires me to use run_until_complete or otherwise I get an error about a Future that's attached to a different event loop. That said, this is just an aside and not really material to the question above.)
I think I've pinned it down. Its an issue with how multiprocessing works on Linux vs Windows/MacOS From the docs: Contexts and start methods Depending on the platform, multiprocessing supports three ways to start a process. These start methods are spawn The parent process starts a fresh Python interpreter process. The child process will only inherit those resources necessary to run the process object’s run() method. In particular, unnecessary file descriptors and handles from the parent process will not be inherited. Starting a process using this method is rather slow compared to using fork or forkserver. Available on Unix and Windows. The default on Windows and macOS. fork The parent process uses os.fork() to fork the Python interpreter. The child process, when it begins, is effectively identical to the parent process. All resources of the parent are inherited by the child process. Note that safely forking a multithreaded process is problematic. Available on Unix only. The default on Unix. forkserver When the program starts and selects the forkserver start method, a server process is started. From then on, whenever a new process is needed, the parent process connects to the server and requests that it fork a new process. The fork server process is single threaded so it is safe for it to use os.fork(). No unnecessary resources are inherited. Available on Unix platforms which support passing file descriptors over Unix pipes. So this works on MacOS and Windows because the default is spawn, versus it fails on Linux where the default is fork. Because we're using fork, the entire set of data is being mapped, meaning that we're sharing the existing already instantiated local event loop in the new process. That's why the event loop states that it is already be running (and asyncio is by design non-re-entrant). To get around this you can set the mode to spawn manually in the main. When we use this mode, the interpreter will be newly invoked, meaning that there will be no existing event loop to conflict on. if __name__ == '__main__': import multiprocessing as mp mp.set_start_method('spawn') doit()
4
2
75,867,636
2023-3-28
https://stackoverflow.com/questions/75867636/how-to-get-value-of-jaxlib-xla-extension-arrayimpl
Using type(z1[0]) I get jaxlib.xla_extension.ArrayImpl. Printing z1[0] I get Array(0.71530414, dtype=float32). How can I get the actual number 0.71530414? I tried z1[0][0] because z1[0] is a kind of array with a single value, but it gives me an error: IndexError: Too many indices for array: 1 non-None/Ellipsis indices for dim 0.. I tried also a different approach: I searched on the web if it was possible to convert from jaxnumpy array to a python list, but I didn't find an answer. Can someone help me to get the value inside a jaxlib.xla_extension.ArrayImpl object?
You can use float(x[0]) to convert x[0] to a Python float: In [1]: import jax.numpy as jnp In [2]: x = jnp.array([0.71530414]) In [3]: x Out[3]: Array([0.71530414], dtype=float32) In [4]: x[0] Out[4]: Array(0.71530414, dtype=float32) In [5]: float(x[0]) Out[5]: 0.7153041362762451 If you're interested in converting the entire JAX array to a list of Python floats, you can use the tolist() method: In [6]: x.tolist() Out[6]: [0.7153041362762451]
4
6
75,869,481
2023-3-28
https://stackoverflow.com/questions/75869481/remove-stripes-vertical-streaks-in-remote-sensing-images
I have a remote sensing photo that has bright non continuous vertical streaks or stripes as in the pic below, my question is there a way to remove them using python and opencv or any other ip library? ,
You could just do a 7x1 median filter on the image: Input: After 7x1 median filter:
4
2
75,870,150
2023-3-28
https://stackoverflow.com/questions/75870150/convert-pandas-dataframe-to-nested-dictionary-where-key-value-pairs-are-columns
I have a pandas dataframe with 3 columns. Say it looks like this: test_df = pd.DataFrame({ 'key1': [1, 1, 1, 1, 2, 2, 2], 'key2': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 'value': ['a-mapped', 'b-mapped', 'c-mapped', 'd-mapped', 'e-mapped', 'f-mapped', 'g-mapped'] }) > test_df key1 key2 value 0 1 a a-mapped 1 1 b b-mapped 2 1 c c-mapped 3 1 d d-mapped 4 2 e e-mapped 5 2 f f-mapped 6 2 g g-mapped I would like to return a nested dictionary where the first keys are key1 and then then the second key value pair would be {key2: value}. For example, I would want the desired_result to be { 1: {'a': 'a-mapped', 'b': 'b-mapped', 'c': 'c-mapped', 'd': 'd-mapped'}, 2: {'e': 'e-mapped', 'f': 'f-mapped', 'g': 'g-mapped'} } I can achieve this by using some loops: desired_result = {} for key1 in test_df.key1: desired_result[key1] = {} for idx, row in test_df.iterrows(): desired_result[row.key1][row.key2] = row.value Is there a more efficient way of doing this?
Try: out = test_df.groupby("key1").apply(lambda x: dict(zip(x["key2"], x["value"]))).to_dict() print(out) Prints: { 1: {"a": "a-mapped", "b": "b-mapped", "c": "c-mapped", "d": "d-mapped"}, 2: {"e": "e-mapped", "f": "f-mapped", "g": "g-mapped"}, }
3
3
75,856,310
2023-3-27
https://stackoverflow.com/questions/75856310/grouping-dataframe-by-similar-non-matching-values
If I have a pandas dataframe with the following columns: id, num, amount. I want to group the dataframe such that all rows in each group have the same id and amount and where each row's value of num has a value that is not more than 10 larger or smaller the next row's value of num. For the same id, if one row to the next does not have the same amount or if the absolute difference between the two num values is more than 10 then it will start a new grouping. Having a row with a different id in the middle does not break a grouping. How can I go about doing this? I have not managed to make a grouping where I'm not looking for matching values (like here where I need it to be close - but not matching). I'm assuming that this would need some custom grouping function but I've been having trouble putting one together Example dataframe: id amount num aaa-aaa 130 12 aaa-aaa 130 39 bbb-bbb 270 41 ccc-ccc 130 19 bbb-bbb 270 37 aaa-aaa 130 42 aaa-aaa 380 39 Expected Groups: Group 1: id amount num aaa-aaa 130 12 Group 2: id amount num aaa-aaa 130 39 aaa-aaa 130 42 Group 3: id amount num bbb-bbb 270 41 bbb-bbb 270 37 Group 4: id amount num ccc-ccc 130 19 Group 5: id amount num aaa-aaa 380 39
The logic is not fully clear, but assuming you want to start a new group when there is a gap of more than 10: close = (df.sort_values(by=['amount', 'num']) .groupby('amount') ['num'].diff().abs().gt(10).cumsum() ) for _, g in df.groupby(['amount', close]): print(g, end='\n\n') Output: id amount num 0 aaa-aaa 130 12 3 ddd-ddd 130 19 id amount num 1 bbb-bbb 130 39 id amount num 2 ccc-ccc 270 41 4 eee-eee 270 37 how it works: # sort values by amount/sum df.sort_values(by=['amount', 'num']) id amount num 0 aaa-aaa 130 12 3 ccc-ccc 130 19 1 aaa-aaa 130 39 5 aaa-aaa 130 42 4 bbb-bbb 270 37 2 bbb-bbb 270 41 6 aaa-aaa 380 39 # get the absolute successive difference in "num" (df.sort_values(by=['amount', 'num']) .groupby('amount') ['num'].diff().abs() ) 0 NaN 3 7.0 1 20.0 5 3.0 4 NaN 2 4.0 6 NaN Name: num, dtype: float64 # check if it's greater than 10 and cumsum # to create a grouper for groupby [...].gt(10).cumsum() 0 0 3 0 1 1 5 1 4 1 2 1 6 1 Name: num, dtype: int64
3
4
75,858,529
2023-3-27
https://stackoverflow.com/questions/75858529/polars-rolling-count-with-temporal-window
I'm trying to write a method for a features pipeline that returns a polars expression. The method should take a column name as a string and an integer number of days. I want to perform a rolling count on that column using a window equal to the number of days. There doesn't seem to be a rolling_count expression, so I attempted to use rolling_sum_by to no avail. def temporal_rolling_count(col: str, days: int) -> pl.Expr: return ( pl.lit(1) .rolling_sum_by(window_size=f"{days}d", by="date_time") .over(col) .fill_null(0) ) I also tried this method, which was closer but still didn't work in all cases def temporal_rolling_count(col: str, days: int) -> pl.Expr: return ( pl.col(col) .cum_count() .over(col, (pl.col("date_time") - pl.col("date_time").min()).dt.days() % days == 0) .fill_null(0) ) Is there anyway to achieve this by returning an expression? Or will I have to act on the DataFrame directly, maybe by using rolling?
As per the suggestion from @jqurious, by using .clip I was able to achieve the desired outcome without acting on the DataFrame. def temporal_rolling_count(col: str, days: int) -> pl.Expr: return ( pl.col(col).clip(1,1) .rolling_sum(window_size=f"{days}d", by="date_time") .over(col) .fill_null(0) ) EDIT I managed to perform the same thing but only count when a condition was true by doing the following. def temporal_rolling_count(col: str, days: int) -> pl.Expr: return ( pl.when(condition).then(1).otherwise(0) .rolling_sum(window_size=f"{days}d", by="date_time") .over(col) .fill_null(0) )
3
1
75,864,073
2023-3-28
https://stackoverflow.com/questions/75864073/use-of-unstructuredpdfloader-unstructured-package-not-found-please-install-it-w
I just have a newly created Environment in Anaconda (conda 22.9.0 and Python 3.10.10). Then I proceed to install langchain (pip install langchain if I try conda install langchain it does not work). According to the quickstart guide I have to install one model provider so I install openai (pip install openai). Then I enter to the python console and try to load a PDF using the class UnstructuredPDFLoader and I get the following error. What the problem could be? (langchain) C:\Users\user>python Python 3.10.10 | packaged by Anaconda, Inc. | (main, Mar 21 2023, 18:39:17) [MSC v.1916 64 bit (AMD64)] on win32 >>> from langchain.document_loaders import UnstructuredPDFLoader >>> loader = UnstructuredPDFLoader("C:\\<path-to-data>\\data\\name-of-file.pdf") Traceback (most recent call last): File "C:\<path-to-anaconda>\envs\langchain\lib\site-packages\langchain\document_loaders\unstructured.py", line 32, in __init__ import unstructured # noqa:F401 ModuleNotFoundError: No module named 'unstructured' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\<path-to-anaconda>\envs\langchain\lib\site-packages\langchain\document_loaders\unstructured.py", line 90, in __init__ super().__init__(mode=mode, **unstructured_kwargs) File "C:\<path-to-anaconda>\envs\langchain\lib\site-packages\langchain\document_loaders\unstructured.py", line 34, in __init__ raise ValueError( ValueError: unstructured package not found, please install it with `pip install unstructured`
Run this pip install unstructured or this pip install "unstructured[local-inference]"
12
8
75,862,628
2023-3-28
https://stackoverflow.com/questions/75862628/how-to-put-serials-in-a-data-frame-by-group
There is a data frame with a model and an item as a column below df = pd.DataFrame({'model':['A','A','A','A','A','A','A','B','B','B','B','B','B','B'], 'item':['aa','ab','ab','ab','ac','ad','ad','ba','ba','ba','bb','bb','bb','bc']}) I want to add a serial column to this data frame, but there are some rules The serial number is reset when the model(A, B) is changed and starts from zero. Serial cannot exceed 3. 0, 1, 2 values only After two(2), it starts at zero(0) In the case of the same item, serial is be the same what I want is
You want pd.factorize on item within each model group (groupby). The reset part is just a modulo away: df['serial'] = df.groupby(['model'])['item'].transform(lambda x: pd.factorize(x)[0]) % 3 Output: model item serial 0 A aa 0 1 A ab 1 2 A ab 1 3 A ab 1 4 A ac 2 5 A ad 0 6 A ad 0 7 B ba 0 8 B ba 0 9 B ba 0 10 B bb 1 11 B bb 1 12 B bb 1 13 B bc 2
4
4
75,854,700
2023-3-27
https://stackoverflow.com/questions/75854700/how-to-fine-tune-a-huggingface-seq2seq-model-with-a-dataset-from-the-hub
I want to train the "flax-community/t5-large-wikisplit" model with the "dxiao/requirements-ner-id" dataset. (Just for some experiments) I think my general procedure is not correct, but I don't know how to go further. My Code: Load tokenizer and model: from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModel checkpoint = "flax-community/t5-large-wikisplit" tokenizer = AutoTokenizer.from_pretrained(checkpoint) model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint).cuda() Load dataset that I want to train: from datasets import load_dataset raw_dataset = load_dataset("dxiao/requirements-ner-id") The raw_dataset looks like this ['id', 'tokens', 'tags', 'ner_tags'] I want to get the sentences as sentence and not as tokens. def tokenToString(tokenarray): string = tokenarray[0] for x in tokenarray[1:]: string += " " + x return string def sentence_function(example): return {"sentence" : tokenToString(example["tokens"]), "simplefiedSentence" : tokenToString(example["tokens"]).replace("The", "XXXXXXXXXXX")} wikisplit_req_set = raw_dataset.map(sentence_function) wikisplit_req_set I tried to restructure the dataset such that it looks like the wikisplit dataset: simple1dataset = wikisplit_req_set.remove_columns(['id', 'tags', 'ner_tags', 'tokens']); complexdataset = wikisplit_req_set.remove_columns(['id', 'tags', 'ner_tags', 'tokens']); complexdataset["train"] = complexdataset["train"].add_column("simple_sentence_1",simple1dataset["train"]["sentence"]).add_column("simple_sentence_2",simple1dataset["train"]["simplefiedSentence"]) complexdataset["test"] = complexdataset["test"].add_column("simple_sentence_1",simple1dataset["test"]["sentence"]).add_column("simple_sentence_2",simple1dataset["test"]["simplefiedSentence"]) complexdataset["validation"] = complexdataset["validation"].add_column("simple_sentence_1",simple1dataset["validation"]["sentence"]).add_column("simple_sentence_2",simple1dataset["validation"]["simplefiedSentence"]) trainingDataSet = complexdataset.rename_column("sentence", "complex_sentence") trainingDataSet Tokenize it: def tokenize_function(example): model_inputs = tokenizer(example["complex_sentence"],truncation=True, padding=True) targetS1 = tokenizer(example["simple_sentence_1"],truncation=True, padding=True) targetS2 = tokenizer(example["simple_sentence_2"],truncation=True, padding=True) model_inputs['simple_sentence_1'] = targetS1['input_ids'] model_inputs['simple_sentence_2'] = targetS2['input_ids'] model_inputs['decoder_input_ids'] = targetS2['input_ids'] return model_inputs tokenized_datasets = trainingDataSet.map(tokenize_function, batched=True) tokenized_datasets=tokenized_datasets.remove_columns("complex_sentence") tokenized_datasets=tokenized_datasets.remove_columns("simple_sentence_1") tokenized_datasets=tokenized_datasets.remove_columns("simple_sentence_2") tokenized_datasets=tokenized_datasets.remove_columns("simplefiedSentence") tokenized_datasets DataLoader: from transformers import DataCollatorForLanguageModeling data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False) data_collator Training: from transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments, TrainingArguments, EvalPrediction, DataCollatorWithPadding, Trainer bleu = evaluate.load("bleu") training_args = Seq2SeqTrainingArguments( output_dir = "/", log_level = "error", num_train_epochs = 0.25, learning_rate = 5e-4, lr_scheduler_type = "linear", warmup_steps = 50, optim = "adafactor", weight_decay = 0.01, per_device_train_batch_size = 1, per_device_eval_batch_size = 1, gradient_accumulation_steps = 16, evaluation_strategy = "steps", eval_steps = 50, predict_with_generate=True, generation_max_length = 128, save_steps = 500, logging_steps = 10, push_to_hub = False, auto_find_batch_size=True ) trainer = Seq2SeqTrainer( model, training_args, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets["validation"], tokenizer=tokenizer, data_collator=data_collator, compute_metrics=bleu, ) trainer.train() The Problem is, that I do not understand how the model know the expected value and how it calculate its loss. Can someone give me some ideas what happens where? I hope some one can help me understand my own code, because the documentation by Hugging Face does not help me enough. Maybe someone have some Codeexamples or something else. I do not completely understand how I fine tune the model and how I get the parameters the model expects to train it. I also do not understand how the training works and what the parameters do.
TL;DR Take some time to go through https://huggingface.co/course/ or read the https://www.oreilly.com/library/view/natural-language-processing/9781098136789/ After that, you would have answered most of the questions you're having. Show me the code: Scroll down the bottom of the answer =) What is a datasets.Dataset and datasets.DatasetDict? TL;DR, basically we want to look through it and give us a dictionary of keys of name of the tensors that the model will consume, and the values are actual tensors so that the models can uses in its .forward() function. In code, you want the processed dataset to be able to do this: from datasets import load_dataset ds = load_dataset(...) ds.map(func_to_preprocess) for data in ds: model(data) # Does a forward propagation pass. Why can't I just feed the Dataset into the model directly? It's because the individual datasets creators/maintainers are not necessary the ones that create the models. And keeping them independent makes sense since a dataset can be used by different model and each model requires different datasets to be preprocessed/"munge"/"manipulated" to the format that it expects (kind of like the Extract, Transform, Load (ETL) process in transformers-based models). Unless explicitly preprocessed, most datasets are in raw text (str) and annotation/label format, which usually are of these types: single token decoder output (single token label), e.g. Language ID task [in]: Hallo Welt and [out]: de normally uses AutoModelForSequenceClassification regression float output e.g. Textual Similarity [in]: Hello world <sep> Foo bar and [out]: 32.12 normally uses AutoModelForSequenceClassification free-form autoregressive decoder output (a natural text sentence, i.e. a list of tokens) e.g. Machine Translation [in]: Hallo Welt and [out]: Hello World normally uses AutoModelForSeq2SeqLM fixed tokens decoder output (a list of labels) e.g. BIO anntoations [in]: Obama is the president and [out]: ['B-PER', 'O', 'O', 'O'] normally uses AutoModelForTokenClassification For the dataset you're interested in: from datasets import load_dataset raw_dataset = load_dataset("dxiao/requirements-ner-id") raw_dataset['train'][0] [out]: {'id': 0, 'tokens': ['The', 'operating', 'humidity', 'shall', 'be', 'between', '0.4', 'and', '0.6'], 'tags': ['O', 'B-ATTR', 'I-ATTR', 'O', 'B-ACT', 'B-RELOP', 'B-QUANT', 'O', 'B-QUANT'], 'ner_tags': [0, 3, 4, 0, 1, 5, 7, 0, 7]} But the model doesn't understand inputs and outputs, it only understand torch.tensor objects, hence you need to do some processing. So tokenizers usually expects raw strings, not list of tokens. Normally, a model's tokenizer converts raw strings into a list of token ids, from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModel model_name = "flax-community/t5-large-wikisplit" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) tokenizer(["hello world", "foo bar is a sentence", "fizz buzz"]) [out]: {'input_ids': [[21820, 296, 1], [5575, 32, 1207, 19, 3, 9, 7142, 1], [361, 5271, 15886, 1]], 'attention_mask': [[1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1]]} But my dataset comes pre-tokenized? So what do I do? sentences = [ ['The', 'operating','humidity','shall','be','between','0.4','and','0.6'], ['The', 'CIS', 'CNET', 'shall', 'accommodate', 'a', 'bandwidth', 'of', 'at', 'least', '24.0575', 'Gbps', 'to', 'the', 'Computer', 'Room', '.'] ] [tokenizer.convert_tokens_to_ids(sent) for sent in sentences] [out]: [[634, 2, 2, 2, 346, 24829, 22776, 232, 22787], [634, 21134, 2, 2, 2, 9, 2, 858, 144, 2, 2, 2, 235, 532, 2, 2, 5]] Why are there so many tokens with index 2? Because they are unknowns. If we take a look at the vocab, >>> tokenizer.convert_tokens_to_ids(tokenizer.unk_token) 2 Then how do I encode the tags or new tokens? Here's an example: from itertools import chain from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModel from datasets import load_dataset model_name = "flax-community/t5-large-wikisplit" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) raw_dataset = load_dataset("dxiao/requirements-ner-id") # Get the NER tags. tag_set = list(map(str, set(chain(*raw_dataset['train']['tags'])))) # Put them into the tokenizer. tokenizer.add_special_tokens({'additional_special_tokens': tag_set}) train_datset = raw_dataset['train'].map(lambda x: {'input_ids': tokenizer.convert_tokens_to_ids(x['tokens']), 'labels': tokenizer.convert_tokens_to_ids(x['tags'])} ) valid_datset = raw_dataset['validation'].map(lambda x: {'input_ids': tokenizer.convert_tokens_to_ids(x['tokens']), 'labels': tokenizer.convert_tokens_to_ids(x['tags'])} ) How to train a Seq2Seq using the text inputs and the NER labels as the outputs? TL;DR: from itertools import chain from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModel from transformers import Seq2SeqTrainingArguments, Seq2SeqTrainer from datasets import load_dataset import evaluate model_name = "flax-community/t5-large-wikisplit" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) raw_dataset = load_dataset("dxiao/requirements-ner-id") # Get the NER tags. tag_set = list(map(str, set(chain(*raw_dataset['train']['tags'])))) # Put them into the tokenizer. tokenizer.add_special_tokens({'additional_special_tokens': tag_set}) train_data = raw_dataset['train'].map(lambda x: {'input_ids': tokenizer.convert_tokens_to_ids(x['tokens']), 'labels': tokenizer.convert_tokens_to_ids(x['tags'])} ) valid_data = raw_dataset['validation'].map(lambda x: {'input_ids': tokenizer.convert_tokens_to_ids(x['tokens']), 'labels': tokenizer.convert_tokens_to_ids(x['tags'])} ) # set special tokens, not sure if it's needed but adding them for sanity... model.config.eos_token_id = tokenizer.eos_token_id model.config.pad_token_id = tokenizer.pad_token_id mt_metrics = evaluate.combine( ["bleu", "chrf"], force_prefix=True ) def compute_metrics(pred): labels_ids = pred.label_ids pred_ids = pred.predictions predictions = tokenizer.batch_decode(pred_ids, skip_special_tokens=True) labels_ids[labels_ids == -100] = tokenizer.pad_token_id references = tokenizer.batch_decode(labels_ids, skip_special_tokens=True) outputs = mt_metrics.compute(predictions=predictions, references=references) return outputs training_args = Seq2SeqTrainingArguments( output_dir='./', per_device_train_batch_size=4, per_device_eval_batch_size=4, logging_steps=1, save_steps=5, eval_steps=1, max_steps=10, evaluation_strategy="steps", predict_with_generate=True, report_to=None, metric_for_best_model="chr_f_score", load_best_model_at_end=True ) trainer = Seq2SeqTrainer( model=model, args=training_args, train_dataset=train_data.with_format("torch"), eval_dataset=valid_data.with_format("torch"), compute_metrics=compute_metrics ) trainer.train() Hey, something seems fishy, when we train an NER, shouldn't we be using AutoModelForTokenClassification not AutoModelForSeq2SeqLM? Yeah, but like many things in life, there's many means to get to the same end. So in this case, you can take the liberty and be creative to do, e.g. https://paperswithcode.com/paper/dont-classify-translate-multi-level-e/review/ https://aclanthology.org/2022.vardial-1.9/ ΠΡρίμΡνΡ Ξ­Ξ½Ξ± Ξ»Ξ΅Ο€Ο„ΟŒ! (Wait a minute!) That's not what I want to do! I guess you don't really want to do NER but the lessons learnt from munging the corpus with additional tokens and the .map functions should help what you need. Why don't you just tell me how to manipulate the DatasetDict so that it fits what I need?! Alright, alright. Here goes... First, I guess you would need to clarify in your question what task are you tackling on top of what model and dataset you're using. From your code, I am guessing you are trying to build a model for Task: Text simplification [in]: This is super long sentence that has lots of no meaning words. [out]: This is a long-winded sentence. Model: Seq2Seq Using AutoModelForSeq2SeqLM("flax-community/t5-large-wikisplit") Dataset: Texts from dxiao/requirements-ner-id [in]: ['The', 'operating','humidity','shall','be',...,] [out]: 'The humidity is high' Only the input tokens from dxiao/requirements-ner-id are use as input texts, everything else in the dataset is not needed Preprocessing: Convert the input into a simplified version [in]: ['The', 'operating','humidity','shall','be',...,] [out]: ['The', 'XXXXX', 'humidity', ...] Convert the simplified output and original inputs to input_ids and labels (that the model expects) Lets create a random_xxx function for this purpose. def random_xxx(tokens): # Pick out 3 tokens to XXX. to_xxx = set(random.sample(range(len(tokens)), 3)) tokens = [] for i, tok in enumerate(tokens): if i in to_xxx: tokens.append('<xxx>') else: tokens.append(tok) return tokens So how do I do what you listed above? Stop stalling, just give me the code... from itertools import chain import random import os os.environ["WANDB_DISABLED"] = "true" from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModel from transformers import Seq2SeqTrainingArguments, Seq2SeqTrainer from datasets import load_dataset import evaluate model_name = "flax-community/t5-large-wikisplit" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) def random_xxx(tokens): # Pick out 3 tokens to XXX. to_xxx = set(random.sample(range(len(tokens)), 3)) tokens = [] for i, tok in enumerate(tokens): if i in to_xxx: tokens.append('<xxx>') else: tokens.append(tok) return tokens raw_dataset = load_dataset("dxiao/requirements-ner-id") # Put '<xxx>' into the tokenizer. tokenizer.add_special_tokens({'additional_special_tokens': ['<xxx>']}) # Assuming `input_ids` is "complex" original sentence. # and `labels` is "simplified" sentence with XXX train_data = raw_dataset['train'].map(lambda x: {'input_ids': tokenizer(" ".join(x['tokens']), max_length=40, truncation=True, padding="max_length")["input_ids"], 'labels': tokenizer(" ".join(random_xxx(x['tokens'])), max_length=40, truncation=True, padding="max_length")["input_ids"]} ) valid_data = raw_dataset['validation'].map(lambda x: {'input_ids': tokenizer(" ".join(x['tokens']), max_length=40, truncation=True, padding="max_length")["input_ids"], 'labels': tokenizer(" ".join(random_xxx(x['tokens'])), max_length=40, truncation=True, padding="max_length")["input_ids"]} ) # set special tokens, not sure if it's needed but adding them for sanity... model.config.eos_token_id = tokenizer.eos_token_id model.config.pad_token_id = tokenizer.pad_token_id mt_metrics = evaluate.combine( ["bleu", "chrf"], force_prefix=True ) def compute_metrics(pred): labels_ids = pred.label_ids pred_ids = pred.predictions predictions = tokenizer.batch_decode(pred_ids, skip_special_tokens=True) labels_ids[labels_ids == -100] = tokenizer.pad_token_id references = tokenizer.batch_decode(labels_ids, skip_special_tokens=True) outputs = mt_metrics.compute(predictions=predictions, references=references) return outputs training_args = Seq2SeqTrainingArguments( output_dir='./', per_device_train_batch_size=4, per_device_eval_batch_size=4, logging_steps=1, save_steps=5, eval_steps=1, max_steps=10, evaluation_strategy="steps", predict_with_generate=True, report_to=None, metric_for_best_model="chr_f_score", load_best_model_at_end=True ) trainer = Seq2SeqTrainer( model=model, args=training_args, train_dataset=train_data.with_format("torch"), eval_dataset=valid_data.with_format("torch"), compute_metrics=compute_metrics ) trainer.train() Here's a few other tutorials that will I find helpful: Take some time to go through https://huggingface.co/course/ or read the https://www.oreilly.com/library/view/natural-language-processing/9781098136789/ It would really help answer most of the questions you'll have and be more confident that you understand what you're typing in code. https://huggingface.co/docs/datasets/tutorial https://www.kaggle.com/code/alvations/from-datasets-import-datasetdict https://discuss.huggingface.co/t/how-to-efficiently-convert-a-large-parallel-corpus-to-a-huggingface-dataset-to-train-an-encoderdecodermodel/24788 https://www.kaggle.com/code/alvations/huggingface-earlystopping-callbacks
5
12
75,860,763
2023-3-27
https://stackoverflow.com/questions/75860763/how-can-i-use-startswith-without-specifying-a-certain-string-is-there-any-alter
I would like to apply vocal_start to so many different variables and i can't handle them all and i wouldn't always repeat startswith. So I don't want to write variable1.startswith(("a", "e", "i", "o", "u")), but i would like to apply startswith(("a", "e", "i", " o", "u")) directly to all variables without specifying variable1.startswith (something similar to my code). I wouldn't always repeat startswith I guess using startswith is only like this (variable1.startswith), so is there anything else I can use? I need something like my code, but not with startswith (or I'd like to use startswith differently if possible) vocal_start = startswith(("a", "e", "i", "o", "u")) variable1 = "open" #Only for Test if variable1 == vocal_start: print("correct") In the code, of course, I get the NameError: name 'startswith' is not defined because I didn't specify variable1.startswith(("a", "e", "i", "o", "u")), but as I said, I don't want to go this route
You can get your desired form to work if you don't mind writing really obscure code. Write a class whose __eq__ does what you want and then use an instance of that class for your compare. >>> class Startswith: ... def __eq__(self, rhs): ... return rhs.startswith(('a', 'e', 'i', 'o', 'u')) ... >>> startswith = Startswith() >>> "abcd" == startswith True >>> "xxx" == startswith False
3
3
75,824,045
2023-3-23
https://stackoverflow.com/questions/75824045/tensorflow-m2-pro-failure
When I run the following test script for tensorflow import tensorflow as tf cifar = tf.keras.datasets.cifar100 (x_train, y_train), (x_test, y_test) = cifar.load_data() model = tf.keras.applications.ResNet50( include_top=True, weights=None, input_shape=(32, 32, 3), classes=100,) loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"]) model.fit(x_train, y_train, epochs=5, batch_size=4) I obtain the following terminal output: Metal device set to: Apple M2 Pro systemMemory: 16.00 GB maxCacheSize: 5.33 GB 2023-03-23 00:26:32.203361: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:305] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support. 2023-03-23 00:26:32.203521: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:271] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 0 MB memory) -> physical PluggableDevice (device: 0, name: METAL, pci bus id: <undefined>) zsh: bus error python3 app/model/tf_verify.py
While unclear from the official Apple documentation, it looks like the tensorflow-macos version should match the tensorflow-metal plugin version from the "Releases" section. Since you are using tensorflow-macos==2.9, you should use tensorflow-metal==0.5.0 and not tensorflow-metal==0.6.0. I was able to reproduce and solve the issue on a MacBook Pro M1 Pro and the training works fine.
3
3
75,858,336
2023-3-27
https://stackoverflow.com/questions/75858336/is-there-a-better-way-to-define-multiple-boolean-variables
I have multiple Boolean variables in my code and now they are defined like this: self.paused, self.show_difficulty, self.resizable, self.high_score_saved, \ self.show_high_scores, self.show_game_modes = \ False, False, True, False, False, False And I thought of refactoring the code like this to improve readability. ui_options = { "paused": False, "show_difficulty": False, "resizable": False, "high_score_saved": False, "show_high_scores": False, "show_game_modes": False } Is there a better way to do it?
To group values like this, I'd recommend using a dataclass over a dictionary. This means you can still have named attributes rather than needing to do string lookups. This will allow auto-completes and static analyzers to work with your code. from dataclasses import dataclass @dataclass class UIOptions: paused: bool = False show_difficulty: bool = False resizable: bool = False high_score_saved: bool = False show_high_scores: bool = False show_game_modes: bool = False ui_options = UIOptions()
3
6
75,854,837
2023-3-27
https://stackoverflow.com/questions/75854837/seaborn-cumulative-sum-and-hue
I have the following dataframe in pandas: data = { 'idx': [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10], 'hue_val': ["A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C","C","C","C","C","C","C",], 'value': np.random.rand(30), } df = pd.DataFrame(data) Now I want to have a line plot with the cumulative sum over the value by following the "idx" for each "hue_val". So in the end it would be three curves going strictly up (since they are positive numbers), one for "A", "B" and "C". I found this code in several sources: sns.lineplot(x="idx", y="value", hue="hue_val", data=df, estimator="cumsum") That is not doing the trick, since both the curve and the x-axis are false:
Given OPs dataframe import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt data = { 'idx': [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10], 'hue_val': ["A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C","C","C","C","C","C","C",], 'value': np.random.rand(30) } df = pd.DataFrame(data) There are two things one needs to do: Calculate the cum sum for each hue_val Plot it 1. Calculate the cum sum for each hue_val In order to calculate the cumulative sum, one can use pandas.DataFrame.groupby and pandas.Series.cumsum. As per OP's request, use a variable column as a way to select the column one wants to consider as follows column = 'value' df['cum_sum'] = df.groupby('hue_val')[column].cumsum() As one is using Numpy to generate some dataframe values, one can also use it to calculate the cum sum with pandas.DataFrame.apply and numpy.cumsum as follows df['cum_sum'] = df.groupby('hue_val')[column].apply(lambda x: np.cumsum(x)) 2. Plot it Then one can plot it with seaborn.lineplot as follows sns.lineplot(data=df, x='idx', y='cum_sum', hue='hue_val') Notes: Having a variable to specify the column, makes it more user friendly if the dataframe has more columns, as the one below, (one of OP's concern), as one will simply change the variable to, let's say value3 data = { 'idx': [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10], 'hue_val': ["A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C","C","C","C","C","C","C",], 'value': np.random.rand(30), 'value1': np.random.rand(30), 'value2': np.random.rand(30), 'value3': np.random.rand(30), } df = pd.DataFrame(data) column = 'value3' df['cum_sum'] = df.groupby('hue_val')[column].cumsum() sns.lineplot(data=df, x='idx', y='cum_sum', hue='hue_val') There are strong opinions on using .apply(). Would recommend reading this: When should I (not) want to use pandas apply() in my code?
3
2
75,830,063
2023-3-24
https://stackoverflow.com/questions/75830063/how-to-optimize-and-speed-up-this-matrices-multiplication-in-python
According to the gradient equation, matrices multiplication is given by where both @ and * are needed. Here is the code if readers are interested: # parameters beta = 0.98 alpha = 0.03 delta = 0.1 T = 1000 loop = 1 dif = 1 tol = 1e-8 kss = ((1 / beta - (1 - delta)) / alpha)**(1 / (alpha - 1)) k = np.linspace(0.5 * kss, 1.8 * kss, T) k_reshaped = k.reshape(-1, 1) c = k_reshaped ** alpha + (1 - delta) * k_reshaped - k c[c<0] = 1e-11 c = np.log(c) beta_square = beta**2 # multiplication I = np.identity(T) E = np.ones(T)[:,None] Q2 = I while np.any(dif > tol) and loop < 200: J = beta * Q2 B = inv(I - J) Q3 = np.zeros([T,T]) ini = np.argmax(c + (B @ (J * c) @ E).flatten(),axis=1) Q3[np.arange(T),ini] = 1 gB = 2 * B @ (J * c @ E) @ (beta * Q2 * c @ E + B @ (np.linalg.matrix_power(I - J, 2) * c @ E)).T / beta_square B += 0.1 * gB dif = np.max(np.absolute(Q3 - Q2)) kcQ = k[ini] Q2 = Q3 loop += 1 Basically, it is folloing the stochastic gradient descent algorithm, matrix B is initialized by B = inv(I - J) and evolving by B += 0.1 * gB, J varying along with Q2, and Q2 needs to be determined in each iteration. However Q2 is a sparse matrix each column only has one one and the rest being zero, in the code it is like: ini = np.argmax(c + (B @ (J * c) @ E).flatten(),axis=1) Q3[np.arange(T),ini] = 1 ... Q2 = Q3 The code currently demonstrates a 1000 by 1000 matrices operation, could this be optimized and run even fatster?
Here is some improvements: beta * Q2 is computed twice, J can be used instead the second time. J * c is also computed multiple time while it can be done once. The same for I - J. B @ (J * c) @ E and B @ (J * c @ E) are mathematically equivalent, but the later is faster in your case and can also be computed once. CPython optimizes (almost) nothing and Numpy performs operations eagerly so doing 0.1 * (2 * Matrix / beta_square) actually compute a new matrix M2 = 2 * Matrix, then a new one M3 = M2 / beta_square, then another one M4 = 0.1 * M4. Creating many temporary matrices like this is expensive because it is a memory-bound operation and the memory bandwidth is pretty limited on modern machines (compared to the computing power), not to mention filling new temporary arrays is generally slower than already filled ones (because of virtual memory and more specifically page faults). Thus, it is faster to do (0.1 * 2 / beta_square) * Matrix (since multiplying float is much faster than multiplying big matrices). Some basic operations like np.argmax(c + tmp3.flatten(), axis=1) or np.max(np.absolute(Q3 - Q2)) can be easily accelerated using Numba. In fact, most In-place operations are generally faster than out-of-place ones (again, because of expensive temporary arrays). You can use them thanks to the out parameter of basic functions (e.g. np.multiply(A, B, out=C)). That being said, the benefit is quite small here since inv takes a significant time. Assuming B is not needed in the end of the loop, you can use np.linalg.solve instead as mentioned by Homer512. Solving a system is significantly faster for large matrices (O(n**3) versus O(n**2)) and often more accurate. See Don’t invert that matrix. For example, inv(I-J) @ b can be replaced by solve(I-J, b). The benefit of using solve is not so big though in your specific use-case because of the sparse I-J matrix. If B is actually used, in the end of the loop, then this is a bit more complex. Numba can help to write a relatively fast matrix inversion specifically for sparse matrices like in your use-case (since the one of Scipy turns out to be pretty slow). np.linalg.matrix_power(tmp0, 2) * c can also be optimized in Numba for sparse matrices. Here is a (barely tested) implementation using Numba: @nb.njit('(float64[:,::1], float64[::1])', parallel=True) def compute_ini(a, b): n, m = a.shape assert b.size == m and m > 0 res = np.empty(n, np.int64) for i in nb.prange(n): max_val, max_pos = a[i, 0] + b[0], 0 for j in range(1, m): val = a[i, j] + b[j] if val > max_val: max_val = val max_pos = j res[i] = max_pos return res @nb.njit('(float64[:,::1], float64[:,::1])', parallel=True) def max_abs_diff(a, b): return np.max(np.absolute(a - b)) # Utility function for invert_sparse_matrix @nb.njit def invert_sparse_matrix_subkernel(b, out, i1, n, eps): for i2 in range(n): if i2 != i1: scale = b[i2, i1] if abs(scale) >= eps: for j in range(n): b[i2, j] -= scale * b[i1, j] out[i2, j] -= scale * out[i1, j] @nb.njit('(float64[:,::1], float64[:,::1])', parallel=True) def invert_sparse_matrix(a, out): eps = 1e-14 n, m = a.shape assert n == m and out.shape == (n,n) b = np.empty((n, n)) for i in nb.prange(n): out[i, :i] = 0.0 out[i, i] = 1.0 out[i, i+1:] = 0.0 b[i, :] = a[i, :] for i1 in range(n): scale = 1.0 / b[i1, i1] if abs(scale) < eps: b[i1, :].fill(0.0) out[i1, :].fill(0.0) invert_sparse_matrix_subkernel(b, out, i1, n, eps) elif abs(scale-1.0) < eps: invert_sparse_matrix_subkernel(b, out, i1, n, eps) else: b[i1, :] *= scale out[i1, :] *= scale invert_sparse_matrix_subkernel(b, out, i1, n, eps) @nb.njit('(float64[:,::1], float64[:,::1], float64[:,::1])', parallel=True) def sparse_square_premult(a, premult, out): eps = 1e-14 n, m = a.shape assert n == m assert premult.shape == (n, n) assert out.shape == (n, n) for i in nb.prange(n): out[i, :] = 0.0 for j in range(n): if abs(a[i, j]) >= eps: for k in range(n): out[i, k] += a[i, j] * a[j, k] out[i, :] *= premult[i, :] def compute_numba(): # parameters beta = 0.98 alpha = 0.03 delta = 0.1 T = 1000 loop = 1 dif = 1 tol = 1e-8 kss = ((1 / beta - (1 - delta)) / alpha)**(1 / (alpha - 1)) k = np.linspace(0.5 * kss, 1.8 * kss, T) k_reshaped = k.reshape(-1, 1) c = k_reshaped ** alpha + (1 - delta) * k_reshaped - k c[c<0] = 1e-11 c = np.log(c) beta_square = beta**2 # multiplication I = np.identity(T) E = np.ones(T)[:,None] Q2 = I J = np.empty((T, T)) tmp0 = np.empty((T, T)) tmp1 = np.empty((T, T)) tmp2 = np.empty((T, 1)) tmp3 = np.empty((T, 1)) tmp4 = np.empty((T, T)) B = np.empty((T, T)) while np.any(dif > tol) and loop < 200: np.multiply(beta, Q2, out=J) np.subtract(I, J, out=tmp0) invert_sparse_matrix(tmp0, B) Q3 = np.zeros((T,T)) np.multiply(J, c, out=tmp1) np.matmul(tmp1, E, out=tmp2) np.matmul(B, tmp2, out=tmp3) ini = compute_ini(c, tmp3.flatten()) Q3[np.arange(T), ini] = 1 factor = 0.1 * 2 / beta_square sparse_square_premult(tmp0, c, tmp4) np.add(B, (factor * tmp3) @ (tmp2 + B @ (tmp4 @ E)).T, out=B) dif = max_abs_diff(Q3, Q2) kcQ = k[ini] Q2 = Q3 loop += 1 compute_numba() Note that the invert_sparse_matrix function still takes a significant time (>50% on my machine) though it is about 3x faster than inv and about as fast as solve. It is an improvement of the naive inversion algorithm with few optimizations for very sparse matrices. It can certainly be optimized further (eg. using tiling) but this is certainly not trivial to do (especially for novice programmers). Note the compilation time takes few seconds. Overall, this implementation is about 4~5 times faster than the initial one on my i5-9600KF processor (6 cores).
5
5
75,847,828
2023-3-26
https://stackoverflow.com/questions/75847828/the-fastest-way-to-get-all-permutations-of-a-range-without-having-consecutive-ne
I want to get all permutations of any range with length n, starting from 0 and ending on n (range(n)) that don't have consecutive numbers. Example: [0,1,2,3,4] There the permutations should look like for example [0,2,4,1,3] or [3,1,4,2,0] My current approach just gets all existing permutations and just skips these ones that have consecutive numbers in them.: import itertools all = itertools.permutations(range(n)) for e in all: double = True for a, b in zip(e, e[1:]): if abs(int(a)-int(b)) <= 1: double = False break if double == True: # do sth the problem I have with this code is that the number of permutations rises by a lot really fast and when it comes to ranges of 10 or bigger, I spend most of my time just skipping permutations and waisting time. Is there any way to do this more efficiently? And another question: If that can be done faster, is there then also a more time efficient implementation where the elements must be at least 2 units appart? That the line if abs(int(a)-int(b)) <= 1 is changed to if abs(int(a)-int(b)) <= 2 and only permutations like [0,4,1,5,2,6,3] are accepted?
The following recursive function does the trick. It constructs only the wanted permutations. It accepts a dst argument indicating the minimum distance that must be exceeded by the next addition taken from set rem to the end of list beg. # comp_perm: complete the permutation # beg: beginning of sequence # rem: set of remaining (still unused) numbers # dst: integer indicating distance that must be *exceeded* def comp_perm(beg: list, rem: set, dst: int) -> list: if (not rem): # check whether rem is the empty set return [beg] return_lst = [] # list of sequences starting with beg for num in rem: if (not beg) or abs(num - beg[-1]) > dst: return_lst.extend(comp_perm(beg+[num], rem-{num}, dst)) return return_lst comp_perm([], set(range(5)), 1) # [[0, 2, 4, 1, 3], [0, 3, 1, 4, 2], [1, 3, 0, 2, 4], ...] The for-loop checks for every potential addition num whether the distance between it and the last element of beg is bigger than dst. If beg is the empty list (not beg), no such check is necessary. Here is how it is intended to be used in full generality: comp_perm([5, 9], {7, 11, 100}, 3) # [[5, 9, 100, 11, 7], [5, 9, 100, 7, 11]] Calling for tpl in comp_perm([], set(range(5)), 1): print(tpl) prints the following: [0, 2, 4, 1, 3] [0, 3, 1, 4, 2] [1, 3, 0, 2, 4] [1, 3, 0, 4, 2] [1, 4, 2, 0, 3] [2, 0, 3, 1, 4] [2, 0, 4, 1, 3] [2, 4, 0, 3, 1] [2, 4, 1, 3, 0] [3, 0, 2, 4, 1] [3, 1, 4, 0, 2] [3, 1, 4, 2, 0] [4, 1, 3, 0, 2] [4, 2, 0, 3, 1] Calling for tpl in comp_perm([], set(range(6)), 2): print(tpl) prints the following: [2, 5, 1, 4, 0, 3] [3, 0, 4, 1, 5, 2] Your desired example [0,4,1,5,2,6,3] is in the results for 7 numbers with dst set to 2: [0,4,1,5,2,6,3] in comp_perm([], set(range(7)), 2) # True Enlarging the set of numbers to permute leads quickly to long lists: len(comp_perm([], set(range(5)), 2)) # 0 len(comp_perm([], set(range(6)), 2)) # 2 len(comp_perm([], set(range(7)), 2)) # 32 len(comp_perm([], set(range(8)), 2)) # 368 len(comp_perm([], set(range(7)), 3)) # 0 len(comp_perm([], set(range(8)), 3)) # 2 len(comp_perm([], set(range(9)), 3)) # 72 len(comp_perm([], set(range(10)), 3)) # 1496 By the way, the answer by Andrej Kesely makes excellent use of yield.
3
2
75,845,280
2023-3-26
https://stackoverflow.com/questions/75845280/constraining-equation-that-includes-multiple-variables-at-a-boundary-using-gekko
I have a system of differential equations that I'm trying to perform some optimal control on, using Gekko. In particular, I have a point-mass orbiting a planet and would simply like to raise its orbit using modelled thrusters as control inputs. In order to set the final radial position and velocity at the new raised orbit, I need to set the following boundary conditions: sqrt(x[-1]**2 + y[-1]**2) = r_final sqrt(vx[-1]**2 + vy[-1]**2) = v_final Where (x,y) is the Cartesian position of the point-mass, and (vx,vy) is its velocity components, and the [-1] notation implies the last element in the trajectory. Furthermore, r_final is the desired altitude of the new orbit, and v_final is the desired speed of the new orbit. So far I have only been able to find functions in Gekko that constrain a single variable (e.g. fix(), fix_final() and fix_initial()), however I couldn't find any functions or examples that had more complex boundary conditions that included multiple variables. Looking at the above-mentioned example, I'm hoping to use Gekko to constrain the final radial position and speed at the new orbit similar to the following piece of code: m.fix(m.sqrt(x**2 + y**2), pos=len(m.time)-1,val=r_final) m.fix(m.sqrt(vx**2 + vy**2), pos=len(m.time)-1,val=v_final) Is something like this possible? Thanks.
Only variables can be directly fixed in gekko. Below are three options. I recommend trying Option 2 first and then use Option 3 if the solver can't find a solution. Option 1: Define Equations With terminal complex expressions, use a final parameter that is non-zero only at the final time point with an equation definition. z = np.linspace(0,tf,n); z[-1]=1 final = m.Param(z) m.Equation(final*(x**2 + y**2 - r_final**2)==0) m.Equation(final*(m.sqrt(vx**2 + vy**2) - v_final)==0) Don't use m.Equation(final*(x**2 + y**2)==r_final**2) or it will be infeasible with 0==r_final**2 before the final point. These equations create many 0==0 equations and can cause a problem for the gradient-based solvers thinking there are too few degrees of freedom. Option 2: Define Variables and fix_final() Another way to do this is to define two new variables and fix those at the final time point with fix_final(). r,v = m.Array(m.Var,2) m.Equations([r**2==x**2 + y**2, v**2==vx**2 + vy**2]) m.fix_final(r,r_final) m.fix_final(v,v_final) Option 3: Minimize Soft Constraints If the solver isn't able to find a feasible solution, try setting a soft constraint instead of fix() or fix_final(). m.Minimize(final*100*(r-r_final)**2) m.Minimize(final*200*(v-v_final)**2) Additional Info It is also possible to minimize final time for the maneuver by making tf a variable with m.Minimize(tf). The Bryson Benchmark problem (see Problem 2) has four examples of specifying terminal constraints. from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt #Build Model ############################ m = GEKKO() #define time space nt = 101 m.time = np.linspace(0,1.5,nt) #Parameters u = m.MV(value =0, lb = -1, ub = 1) u.STATUS = 1 u.DCOST = 0.0001 # slight penalty to discourage MV movement #Variables x1 = m.Var(value=0.5) x2 = m.Var(value = 0) myObj = m.Var() #Equations m.Equation(myObj.dt() == 0.5*x1**2) m.Equation(x1.dt() == u + x2) m.Equation(x2.dt() == -u) f = np.zeros(nt) f[-1] = 1 final = m.Param(value=f) # Four options for final constraints x1(tf)=0 and x2(tf)=0 option = 2 # best option = 3 (fix endpoints directly) if option == 1: # most likely to cause DOF issues because of many 0==0 equations m.Equation(final*x1 == 0) m.Equation(final*x2 == 0) elif option == 2: # inequality constraint approach is better but there are still # many inactive equations not at the endpoint m.Equation((final*x1)**2 <= 0) m.Equation((final*x2)**2 <= 0) elif option == 3: #requires GEKKO version >= 0.0.3a2 # fix the value just at the endpoint (best option) m.fix(x1,pos=nt-1,val=0) m.fix(x2,pos=nt-1,val=0) else: #penalty method ("soft constraint") that may influence the # optimal solution because there is just one combined objective # and it may interfere with minimizing myObj m.Obj(1000*(final*x1)**2) m.Obj(1000*(final*x2)**2) m.Obj(myObj*final) ######################################## #Set Global Options and Solve m.options.IMODE = 6 m.options.NODES = 3 m.options.MV_TYPE = 1 m.options.SOLVER = 1 # APOPT solver #Solve m.solve() # (remote=False) for local solution # Print objective value print('Objective (myObj): ' + str(myObj[-1])) ######################################## #Plot Results plt.figure() plt.plot(m.time, x1.value, 'y:', label = '$x_1$') plt.plot(m.time, x2.value, 'r--', label = '$x_2$') plt.plot(m.time, u.value, 'b-', label = 'u') plt.plot(m.time, myObj.value,'k-',label='Objective') plt.legend() plt.show()
3
1
75,842,117
2023-3-25
https://stackoverflow.com/questions/75842117/pydantic-apply-validator-on-all-fields-of-specific-type
In my project, all pydantic models inherit from a custom "base model" called GeneralModel. This enables to configure the same behavior for the entire project in one place. Let's assume the following implementation: from pydantic import BaseModel class GeneralModel(BaseModel): class Config: use_enum_values = True exclude_none = True One particularly desired behavior is to perform a validation on all fields of a specific type. Any ideas how to achieve this using my GeneralModel? Different approaches are blessed as well.
Quote from the Pydantic validators documentation: a single validator can also be called on all fields by passing the special value '*' and: you can also add any subset of the following arguments to the signature (the names must match): [...] field: the field being validated. Type of object is pydantic.fields.ModelField. So you can write a catch-all validator and pass it the ModleField instance as an argument. Then check the type of the field and apply whatever validation you want. Very simple example: from typing import Any from pydantic import BaseModel, validator from pydantic.fields import ModelField class GeneralModel(BaseModel): @validator("*") def ensure_non_negative(cls, v: Any, field: ModelField) -> Any: if field.type_ is float and v < 0: raise ValueError(f"`{field.name}` value must not be negative") return v class Config: ... Usage: from pydantic import ValidationError # ... import GeneralModel class ConcreteModel(GeneralModel): x: float y: str = "foo" print(ConcreteModel(x=3.14)) try: ConcreteModel(x=-1) except ValidationError as err: print(err.json(indent=4)) Output: x=3.14 y='foo' [ { "loc": [ "x" ], "msg": "`x` value must not be negative", "type": "value_error" } ] Note: When defining a field as for example list[str], Pydantic internally considers the field type to be str, but its shape to be pydantic.fields.SHAPE_LIST. Luckily, shape is also a public attribute of ModelField. See this answer for an example, where this is important.
3
2
75,840,780
2023-3-25
https://stackoverflow.com/questions/75840780/convert-singular-values-into-lists-when-parsing-pydantic-fields
I have an application that needs to parse some configuration. These structures often contain fields that can be either a string, or an array of strings, e.g. in YAML: fruit: apple vegetable: - tomato - cucumber However, internally I'd like to have fruit=['apple'] and vegetable=['tomato', 'cucumber'] for uniformity. I'd like to use Pydantic to do the parsing. How do I declare these fields with as little repetition as possible? Ideal solution: Retains the type of fruit and vegetable as list[str] for both typechecking (mypy) and at runtime. Has at most one line of code per field, even when used in multiple classes. Generalizes to arbitrary types, not just str. I have considered: fruit: Union[str, list[str]] - I will have to check the type of fruit everywhere it's used, which defeats the purpose of parsing in the first place. @validator("fruit", pre=True) that converts a non-list to a list - this will have to be repeated for every field in every class, bloating up the definition by 3 extra lines per field.
Suggested approach Writing custom field validator is indeed the way to go IMHO. As a general rule, it is a good idea to define the model in terms of the schema you want at the end of the parsing process, not in terms of what you might get. We can apply a few tricks to reduce code repetition to a minimum. Firstly, we can define the validator as "catch-all" by registering it for the field wildcard "*". Next, we leverage the ability to receive the respective ModelField instance as an optional argument in our validator method. It carries the (crucial) information about the shape of the field. Finally, we rely as much as possible on the built-in "smarts" of Pydantic models and their lenient type coercion/conversion, so that we do not have to worry about specifics such as "are we dealing with a tuple or a list type field?". If we go about this the right way, we can construct a highly generic validator that does what you want (and more) that only needs to be registered once on our custom base model and is then inherited and used by all subclasses. Working implementation from typing import Any, ClassVar from pydantic import BaseModel as PydanticBaseModel, validator from pydantic.fields import ( SHAPE_DEQUE, SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, ModelField, ) ITERABLE_SHAPES = {...} # repeat shape constants from imports class BaseModel(PydanticBaseModel): __split_sep__: ClassVar[str] = "," @validator("*", pre=True) def split_str(cls, v: Any, field: ModelField) -> Any: if not isinstance(v, str): return v # allow default Pydantic validator to take over generator = (item.strip() for item in v.split(cls.__split_sep__)) if field.shape == SHAPE_TUPLE: return tuple(generator) # because Pydantic checks length first if field.shape in ITERABLE_SHAPES: return generator return v @validator('*', pre=True) def discard_empty_str_elements(cls, v: Any, field: ModelField) -> Any: if field.type_ is str and field.shape in ITERABLE_SHAPES: return (item for item in v if item != "") return v The first special case SHAPE_TUPLE is only necessary because tuple types actually have a meaningful length, since you can define the specific types of tuple elements in advance. Pydantic does the length check before converting the object to a tuple and this breaks, if we pass it a generator (because a generator does not have a length). If we don't need to accommodate that special case, for example because we will only ever use fields with ellipsis-type tuple fields (x: tuple[int, ...]), the entire validator gets even shorter: @validator("*", pre=True) def split_str(cls, v: Any, field: ModelField) -> Any: if isinstance(v, str) and field.shape in ITERABLE_SHAPES: return (item.strip() for item in v.split(cls.__split_sep__)) return v The second validator discard_empty_str_elements is just for added convenience, so that leading, trailing or consecutive separators do not result in empty elements. We can rely on the fact that validators for the same field are called in the order they were defined. Demo Here is a little demo with "strings-only" input data: (JSON, not YAML, but same difference) class GroceryList(BaseModel): fruits: list[str] vegetables: set[str] class NumericStuff(BaseModel): x: tuple[int, int, int] y: frozenset[float] groceries_data = '''{ "fruits": ",apple,,orange,", "vegetables": " tomato, cucumber" }''' groceries = GroceryList.parse_raw(groceries_data) print(groceries) print(groceries.json(indent=4)) numeric_data = '''{ "x": "1,2,69", "y": "3.14" }''' numbers = NumericStuff.parse_raw(numeric_data) print(numbers) print(numbers.json(indent=4)) Output: fruits=['apple', 'orange'] vegetables={'tomato', 'cucumber'} { "fruits": [ "apple", "orange" ], "vegetables": [ "tomato", "cucumber" ] } x=(1, 2, 69) y=frozenset({3.14}) { "x": [ 1, 2, 69 ], "y": [ 3.14 ] } As you can see, no additional code is needed in the subclasses at all. The validators also work for different iterable types such as frozenset or deque, not just list. And the best thing is of course the fact that the (first) validator does not care at all about the actual type of the field. It only cares about the shape. So list[str] works just as well as frozenset[float]. Naturally, the way the validators are designed, the models still work just fine with already "valid" input data: print(GroceryList.parse_raw('{"fruits": ["mango"], "vegetables": ["carrot", "cabbage"]}')) (There is no set equivalent in JSON, so an array here and in the output above is the only sane way to represent this.) Output: fruits=['mango'] vegetables={'carrot', 'cabbage'} Lastly, as far as I can see, the way the validator is set up, it should not break or affect other field validation in any way. You should still be able to use any non-sequence type fields the same as before. PS Of course, if you don't like the base model and catch-all approach for whatever reason, you can instead define the validator as a normal function and apply it selectively as a re-usable validator. This will of course mean one additional line of code for every model that you want to use them on. Example: ... def split_str(v: Any, field: ModelField) -> Any: if isinstance(v, str) and field.shape in ITERABLE_SHAPES: return (item.strip() for item in v.split(",")) return v class Model(PydanticBaseModel): a: list[int] b: list[str] _split_str = validator("a", "b", pre=True, allow_reuse=True)(split_str) print(Model.parse_raw('{"a": "-1,-2,-3", "b": "foo,bar"}')) Output: a=[-1, -2, -3] b=['foo', 'bar'] I could imagine this approach to be better, if you care about performance because the catch-all validator is obviously called for every field. But since you were talking about parsing config files and this is typically not done millions of times for every run of the program, I would assume this is negligible.
4
2
75,841,115
2023-3-25
https://stackoverflow.com/questions/75841115/issue-with-implementing-inverse-fft-for-polynoms
I am studying the FFT algorithm for fast polynomial multiplication. We went over the algorithm and I decided to try and implement it in Python. from typing import List import numpy as np def fft(p: List[int]) -> List[int]: n = len(p) if n == 1: return p unity_root = np.exp(2j * np.pi / n) p_even = p[::2] p_odd = p[1::2] y_even = fft(p_even) y_odd = fft(p_odd) y = [0] * n for j in range(n // 2): omega = np.power(unity_root, j) y[j] = y_even[j] + omega * y_odd[j] y[n // 2 + j] = y_even[j] - omega * y_odd[j] return y def ifft(p: List[int]) -> List[int]: n = len(p) if n == 1: return p unity_root = (1 / n) * np.exp(-2j * np.pi / n) p_even = p[::2] p_odd = p[1::2] y_even = ifft(p_even) y_odd = ifft(p_odd) y = [0] * n for j in range(n // 2): omega = np.power(unity_root, j) y[j] = y_even[j] + omega * y_odd[j] y[n // 2 + j] = y_even[j] - omega * y_odd[j] return y I tried running the following code to make sure it works print(ifft(fft([1, 2, 3, 4]))) I expected the output to be the original list I started with as that list represents the coefficients, yet I am getting (ignoring precision issues with floating point arithmetic): [(4+0j), (11-0j), (12+0j), (13+0j)] My question is: Shouldn't I be getting the original list? If I should be getting the original list, where is the mistake in the code? as I went over the code several times and I am having issues finding it. If I shouldn't be getting the original list back and my code is correct, what am I actually getting?
The problem is that, in ifft, you're dividing the root of unity by n. You need to divide the final result instead.
3
2
75,837,715
2023-3-24
https://stackoverflow.com/questions/75837715/how-to-format-labels-in-scientific-notation-for-bar-label
I am plotting data in a seaborn barplot. I want to label something from my pandas dataframe into the bar. I have gotten the labeling part figured out (see code to replicate below), but I still want to convert it to scientific notation. import pandas as pd d = {'name': ['experiment1','experiment2'], 'reads': [15000,12000], 'positiveEvents': [40,60]} df = pd.DataFrame(d) df['proportianPositive'] = df['positiveEvents']/df['reads'] p = sns.barplot(data=df,x='name',y='positiveEvents', palette = 'colorblind', alpha =0.8) p.bar_label(p.containers[0],labels=df.proportianPositive, padding = -50, rotation=90) plt.show() Result: How do I convert df.proportianPositive to scientific notation so that it will show up on my barplot?
As already stated, labels= supersedes fmt=, so they may not be used together. p.containers[0] β†’ <BarContainer object of 2 artists>, which are the properties describing the bars. If using the default height (vertical bars), or width (horizontal bars), then use the fmt='%.3E' If using custom labels, the formatting must be applied to the object passed to labels= In the case of a pandas.Series: labels = df['proportianPositive'].map(lambda v: f'{v:.3E}'). See Difference between map, applymap and apply. For a list-comprehension: labels = [f'{v:.3E}' for v in df.proportianPositive] Both options use modern f-string formatting See How to add value labels on a bar chart for additional details, and examples, using matplotlib.pyplot.bar_label. fmt= ax = sns.barplot(data=df, x='name', y='positiveEvents', palette='colorblind', alpha=0.8) xa.bar_label(ax.containers[0], fmt='%.3E') labels= ax = sns.barplot(data=df, x='name', y='positiveEvents', palette='colorblind', alpha=0.8) labels = df['proportianPositive'].map(lambda v: f'{v:.3E}') # pandas.Series # labels = [f'{v:.3E}' for v in df.proportianPositive] # list comprehension ax.bar_label(ax.containers[0], labels=labels)
3
3
75,834,257
2023-3-24
https://stackoverflow.com/questions/75834257/how-to-fix-attributeerror-web3-object-has-no-attribute-tochecksumaddress
I'm trying to use 1inch oracle methods from here. This is python wrapper around 1inch apis. I want to know token price from some oracle so i'm using oracle method "get_rate_to_ETH". But in a result I have this exception: Traceback (most recent call last): File "D:\projects\1inchArb\1inch_api.py", line 20, in <module> price_usdc = oracle.get_rate_to_ETH("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", src_token_decimal=6) File "D:\projects\1inchArb\venv\lib\site-packages\oneinch_py\main.py", line 376, in get_rate_to_ETH rate = self.oracle_contract.functions.getRateToEth(self.w3.toChecksumAddress(src_token), wrap).call() AttributeError: 'Web3' object has no attribute 'toChecksumAddress' My code: from oneinch_py import OneInchOracle public_key = "my_wallet_addr" rpc_url = "https://cloudflare-eth.com" oracle = OneInchOracle(rpc_url, chain='ethereum') price_usdc = oracle.get_rate_to_ETH("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", src_token_decimal=6) Also I tried to use different RPC urls such as "https://mainnet.infura.io/v3/{}".format(my_infura_key) but it gives same error. If anyone knows how to help me it would be very grateful...
Update to latests version ΠΎf 1inch.py - 1.9, released 20 March 2023 and also web3 to use version 6.0.0. 1inch.py is using web3 as dependency. web3 removed CamelCase naming in latest version 6.0.0 1inch.py released new version to change their code and migrate to using web3, version 6.0.0.
3
2
75,827,502
2023-3-23
https://stackoverflow.com/questions/75827502/how-to-get-pydantic-model-types
Consider the following model: from pydantic import BaseModel class Cirle(BaseModel): radius: int pi = 3.14 If I run the following code, I can see the fields of this model: print(Circle.__fields__) # Output: { 'radius': ModelField(name='radius', type=int, required=True), 'pi': ModelField(name='pi', type=float, required=False, default=3.14) } The question is: how can I get the type (or inferred type hint) from the ModelField type? These all give errors: Circle.__fields__['pi'].type # AttributeError: 'ModelField' object has no attribute 'type' Circle.__fields__['pi'].__dict__ # AttributeError: 'ModelField' object has no attribute '__dict__' type(Circle.__fields__['pi']) # <class 'pydantic.fields.ModelField'> import typing typing.get_type_hints(Circle.__fields__['pi']) # TypeError: ModelField(name='pi', type=float, required=False, default=3.14) # is not a module, class, method, or function. typing.get_type_hints(Circle) # This does not include the "pi" field because it has no type hints # {'radius': <class 'int'>} I don't even see where the ModelField type is defined in github. How can I iterate over the fields of a pydantic model and find the types?
You can use the type_ variable of the pydantic fields. The variable is masked with an underscore to prevent collision with the Python internal type keyword. from pydantic import BaseModel class Cirle(BaseModel): radius: int pi = 3.14 for key, value in Cirle.__fields__.items(): print(key, value.type_) # Output: # radius <class 'int'> # pi <class 'float'>
8
6
75,826,424
2023-3-23
https://stackoverflow.com/questions/75826424/python-how-do-i-get-a-new-value-every-instance-in-a-np-where
I have a data set with a column filled with 1s and 0s as such: column 1: 1 1 1 1 0 0 0 1 1 0 1 1 and I am currently using np.where() to create a new column that segments the data from column 1. The issue is, whenever it comes across a new segments of 1s I want the values in column 2 to increase by 1. n = 1 df['column2'] = np.where(df['column1'] == 1 , n + 1 , 0) The results I am getting: column 1: column 2: 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 0 0 1 1 1 1 what I am trying to achieve column 1: column 2: 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 2 1 2 0 0 1 3 1 3
Cheeky one-liner: df["column2"] = df['column1'].diff().ne(0).cumsum().add(1).floordiv(2).where(df['column1'].astype(bool), other=0) df: column1 column2 0 1 1 1 1 1 2 1 1 3 1 1 4 0 0 5 0 0 6 0 0 7 1 2 8 1 2 9 0 0 10 1 3 11 1 3
4
3
75,824,594
2023-3-23
https://stackoverflow.com/questions/75824594/python-poetry-install-fails-on-typed-ast-1-5-4-how-to-overcome-the-obstacle-a
I tried to install the package using pip: pip wheel --use-pep517 "typed-ast (==1.5.4)" but it falls in the same place. What's the general approach when you walk into such kind of problems? I've found this thread, which seemed to be helpful, but it wasn't (.venv) ➜ src git:(develop) βœ— poetry install Installing dependencies from lock file Warning: poetry.lock is not consistent with pyproject.toml. You may be getting improper dependencies. Run `poetry lock [--no-update]` to fix it. Package operations: 24 installs, 0 updates, 0 removals β€’ Installing typed-ast (1.5.4): Failed ChefBuildError Backend subprocess exited when trying to invoke build_wheel running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-311 creating build/lib.linux-x86_64-cpython-311/typed_ast copying typed_ast/__init__.py -> build/lib.linux-x86_64-cpython-311/typed_ast copying typed_ast/ast27.py -> build/lib.linux-x86_64-cpython-311/typed_ast copying typed_ast/conversions.py -> build/lib.linux-x86_64-cpython-311/typed_ast copying typed_ast/ast3.py -> build/lib.linux-x86_64-cpython-311/typed_ast creating build/lib.linux-x86_64-cpython-311/typed_ast/tests copying ast3/tests/test_basics.py -> build/lib.linux-x86_64-cpython-311/typed_ast/tests running build_ext building '_ast27' extension creating build/temp.linux-x86_64-cpython-311 creating build/temp.linux-x86_64-cpython-311/ast27 creating build/temp.linux-x86_64-cpython-311/ast27/Custom creating build/temp.linux-x86_64-cpython-311/ast27/Parser creating build/temp.linux-x86_64-cpython-311/ast27/Python x86_64-linux-gnu-gcc -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -fPIC -Iast27/Include -I/tmp/tmpwhqt9erw/.venv/include -I/usr/include/python3.11 -c ast27/Custom/typed_ast.c -o build/temp.linux-x86_64-cpython-311/ast27/Custom/typed_ast.o ast27/Custom/typed_ast.c:1:10: fatal error: Python.h: No such file or directory 1 | #include "Python.h" | ^~~~~~~~~~ compilation terminated. error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1 at ~/c/mrnet/mrnet_backend/.venv/lib/python3.11/site-packages/poetry/installation/chef.py:152 in _prepare 148β”‚ 149β”‚ error = ChefBuildError("\n\n".join(message_parts)) 150β”‚ 151β”‚ if error is not None: β†’ 152β”‚ raise error from None 153β”‚ 154β”‚ return path 155β”‚ 156β”‚ def _prepare_sdist(self, archive: Path, destination: Path | None = None) -> Path: Note: This error originates from the build backend, and is likely not a problem with poetry but with typed-ast (1.5.4) not supporting PEP 517 builds. You can verify this by running 'pip wheel --use-pep517 "typed-ast (==1.5.4)"'. (.venv) ➜ src git:(develop) βœ— pip wheel --use-pep517 "typed-ast (==1.5.4)" Collecting typed-ast==1.5.4 Using cached typed_ast-1.5.4.tar.gz (252 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: typed-ast Building wheel for typed-ast (pyproject.toml) ... error error: subprocess-exited-with-error Γ— Building wheel for typed-ast (pyproject.toml) did not run successfully. β”‚ exit code: 1 ╰─> [25 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-311 creating build/lib.linux-x86_64-cpython-311/typed_ast copying typed_ast/__init__.py -> build/lib.linux-x86_64-cpython-311/typed_ast copying typed_ast/ast27.py -> build/lib.linux-x86_64-cpython-311/typed_ast copying typed_ast/conversions.py -> build/lib.linux-x86_64-cpython-311/typed_ast copying typed_ast/ast3.py -> build/lib.linux-x86_64-cpython-311/typed_ast creating build/lib.linux-x86_64-cpython-311/typed_ast/tests copying ast3/tests/test_basics.py -> build/lib.linux-x86_64-cpython-311/typed_ast/tests running build_ext building '_ast27' extension creating build/temp.linux-x86_64-cpython-311 creating build/temp.linux-x86_64-cpython-311/ast27 creating build/temp.linux-x86_64-cpython-311/ast27/Custom creating build/temp.linux-x86_64-cpython-311/ast27/Parser creating build/temp.linux-x86_64-cpython-311/ast27/Python x86_64-linux-gnu-gcc -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -fPIC -Iast27/Include -I/home/yevt/c/mrnet/mrnet_backend/.venv/include -I/usr/include/python3.11 -c ast27/Custom/typed_ast.c -o build/temp.linux-x86_64-cpython-311/ast27/Custom/typed_ast.o ast27/Custom/typed_ast.c:1:10: fatal error: Python.h: No such file or directory 1 | #include "Python.h" | ^~~~~~~~~~ compilation terminated. error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for typed-ast Failed to build typed-ast ERROR: Failed to build one or more wheels (.venv) ➜ src git:(develop) βœ— pip wheel --use-pep517 "typed-ast (==1.5.4)" ubuntu 22.04 gcc 11.3.0 python 3.11
Do you install python3.11-dev? sudo apt install -y python3.11-dev or packages for compiling sudo apt install -y build-essential libssl-dev libffi-dev python3.11-dev
6
6
75,825,190
2023-3-23
https://stackoverflow.com/questions/75825190/how-to-put-iconbitmap-on-a-customtkinter-toplevel
This is the code example: class ToplevelWindow(customtkinter.CTkToplevel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.geometry("400x300") self.title("New Window") self.resizable(False, False) self.iconbitmap('icon.ico') self.after(100, self.lift) class App(customtkinter.CTk): def __init__(self): super().__init__() self.geometry("550x150") self.title("Title") self.resizable(False, False) logo_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_images") self.logo = customtkinter.CTkImage( Image.open(os.path.join(logo_path, "MCB.png")), size=(90, 54)) self.labelimage = customtkinter.CTkLabel(master=self, text=None, image=self.logo) self.labelimage.place(relx=0, rely=0, anchor=tkinter.NW) self.iconbitmap('icon.ico') self.button = customtkinter.CTkButton(master=self, text="Close", command=self.close) self.button.place(relx=0.675, rely=0.8, anchor=tkinter.CENTER) self.button2 = customtkinter.CTkButton(master=self, text="New Window", command=self.open_toplevel) self.button2.place(relx=0.325, rely=0.80, anchor=tkinter.CENTER) self.toplevel_window = None def close(self): "nothing here yet" def open_toplevel(self): if self.toplevel_window is None or not self.toplevel_window.winfo_exists(): self.toplevel_window = ToplevelWindow(self) # create window if its None or destroyed else: self.toplevel_window.focus() # if window exists focus it When i use the iconbitmap on the main window it works fine. But when is used at the toplevel class, it does nothing. The icon still appears as the default version. What i'm missing ? How can i make this right or is it even possible ?
This is a bug of customtkinter. If you look into the source code of CTkToplevel, there is below code inside __init__(): class CTkToplevel(tkinter.Toplevel, ...): def __init__(self, ...): ... try: # Set Windows titlebar icon if sys.platform.startswith("win"): customtkinter_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) self.after(200, lambda: self.iconbitmap(os.path.join(customtkinter_directory, "assets", "icons", "CustomTkinter_icon_Windows.ico"))) except Exception: pass ... So an after job is scheduled to change the window icon after 200ms which overrides your call of self.iconbitmap('icon.ico'). The above code block does not exist in the source code of CTk class, so the main window shows the icon you want. To overcome it, you can delay your call of self.iconbitmap(...) using .after() as well: class ToplevelWindow(...): def __init__(...): ... self.after(250, lambda: self.iconbitmap('icon.ico')) ...
3
6
75,816,824
2023-3-22
https://stackoverflow.com/questions/75816824/implement-seek-in-read-only-gzip-stream
I have an app that seeks within a .gz file-like object. Python's gzip.GzipFile supports this, but very inefficiently – when the GzipFile object is asked to seek back, it will rewind to the beginning of the stream (seek(0)) and then read and decompress everything up to the desired offset. Needless to say this absolutely kills performance when seeking around a large tar.gz file (tens of gigabytes). So I'm looking to implement checkpointing: store the stream state every now and then, and when asked to seek back, go only to the next previous stored checkpoint, instead of rewinding all the way to the beginning. My question is around the gzip / zlib implementation: What does the "current decompressor state" consist of? Where is it stored? How big is it? And how do I copy that state out of an open GzipFile object, and then assign it back for the "backward jump" seek? Note I have no control over the input .gz files. The solution must be strictly for GzipFile in read-only rb mode. EDIT: Looking at CPython's source, this is the relevant code flow & data structures. Ordered from top-level (Python) down to raw C: gzip.GzipFile._buffer.raw gzip._GzipReader gzip._GzipReader.seek() == DecompressReader.seek() <=== NEED TO CHANGE THIS ZlibDecompressor state + its deepcopy <=== NEED TO COPY / RESTORE THIS z_stream struct internal_state struct EDIT2: Also found this teaser in zlib: An access point can be created at the start of any deflate block, by saving the starting file offset and bit of that block, and the 32K bytes of uncompressed data that precede that block. Also the uncompressed offset of that block is saved to provide a reference for locating a desired starting point in the uncompressed stream. Another way to build an index would be to use inflateCopy(). That would not be constrained to have access points at block boundaries, but requires more memory per access point, and also cannot be saved to file due to the use of pointers in the state. (they call "access points" what I call "check points"; same thing) This pretty much answers all my questions but I still need to find a way to translate this zran.c example to work with the gzip/zlib scaffolding in CPython.
You could try a library called indexed_gzip, which builds on top of the zlib's zran.c utility. Essentially, this library keeps a series of checkpoints throughout the file, and when a request for a specific byte offset arrives, it starts from the nearest checkpoint. (indexed_gzip calls this an "index seek point.") Example usage from the documentation: import indexed_gzip as igzip # You can create an IndexedGzipFile instance by specifying a file name. myfile = igzip.IndexedGzipFile('big_file.gz') # Or by passing an open file handle. In this use, the file handle # must be opened in read-only binary mode: myfile = igzip.IndexedGzipFile(fileobj=fileobj, auto_build=True, spacing=1024**2) # Write support is currently non-existent. The auto_build mode (True by default) allows incremental index building: each call to seek(offset) expands the checkpoint index to encompass the offset, in case it's not already covered. You'll probably want to tune the spacing parameter, which controls how many bytes are between each checkpoint in the uncompressed file content. This is a time-memory tradeoff: more checkpoints means that less work needs to be done on each seek, but this means that more memory is used for checkpoints. It defaults to 1MB of uncompressed data. For faster startup, you can write the index out to disk (the index is much smaller than the underlying compressed file) and load the index the next time your program runs. See Index import/export for more about how to use this feature.
5
4
75,823,656
2023-3-23
https://stackoverflow.com/questions/75823656/create-dictionary-with-pairs-from-column-from-pandas-dataframe-using-regex
I have the following dataframe import pandas as pd df = pd.DataFrame({'Original': [92,93,94,95,100,101,102], 'Sub_90': [99,98,99,100,102,101,np.nan], 'Sub_80': [99,98,99,100,102,np.nan,np.nan], 'Gen_90': [99,98,99,100,102,101,101], 'Gen_80': [99,98,99,100,102,101,100]}) I would like to create the following dictionary { 'Gen_90': 'Original', 'Sub_90': 'Gen_90', 'Gen_80': 'Original', 'Sub_80': 'Gen_80', } using regex (because at my original data I also have Gen_70, Gen_60, ... , Gen_10 and Sub_70, Sub_60, ... , Sub_10) So I would like to create pairs of Sub and Gen for the same _number and also pairs or the Original with the Gens How could I do that ?
You can do: gen_cols = df.filter(like='Gen_').columns sub_cols = df.filter(like='Sub_').columns d = dict(zip(sorted(sub_cols), sorted(gen_cols))) d.update({g : 'Original' for g in gen_cols}) print(d) {'Sub_80': 'Gen_80', 'Sub_90': 'Gen_90', 'Gen_90': 'Original', 'Gen_80': 'Original'}
3
3
75,823,000
2023-3-23
https://stackoverflow.com/questions/75823000/modules-getattr-is-called-twice
PEP-562 introduced __getattr__ for modules. While testing I noticed this magic method is called twice when called in this form: from X import Y. file_b.py: def __getattr__(name): print("__getattr__ called:", name) file_a.py: from file_b import foo, bar output: __getattr__ called: __path__ __getattr__ called: foo __getattr__ called: bar __getattr__ called: foo __getattr__ called: bar I run it with: python file_a.py. The interpreter version is: 3.10.6 Could you please let me know the reason behind this?
Because your __getattr__ returns None for __path__ instead of raising an AttributeError, the import machinery thinks your file_b is a package. None isn't actually a valid __path__, but all __import__ checks here is hasattr(module, '__path__'). It doesn't check the value: elif hasattr(module, '__path__'): return _handle_fromlist(module, fromlist, _gcd_import) Because the import machinery thinks your file_b is a package, it calls _handle_fromlist, the function responsible for loading package submodules specified in a from import. _handle_fromlist will go through all the names you specified, and for each one, it will call hasattr to check whether an attribute with that name exists on file_b. If an attribute is not found, _handle_fromlist will attempt to import a submodule with the given name: for x in fromlist: if not isinstance(x, str): if recursive: where = module.__name__ + '.__all__' else: where = "``from list''" raise TypeError(f"Item in {where} must be str, " f"not {type(x).__name__}") elif x == '*': if not recursive and hasattr(module, '__all__'): _handle_fromlist(module, module.__all__, import_, recursive=True) elif not hasattr(module, x): from_name = '{}.{}'.format(module.__name__, x) try: _call_with_frames_removed(import_, from_name) except ModuleNotFoundError as exc: # Backwards-compatibility dictates we ignore failed # imports triggered by fromlist for modules that don't # exist. if (exc.name == from_name and sys.modules.get(from_name, _NEEDS_LOADING) is not None): continue raise This is where the first __getattr__ calls come from: hasattr attempts to get the foo and bar attributes on file_b, triggering your __getattr__. The second __getattr__ calls are just the calls you would expect, retrieving the foo and bar attributes you said to import so the import statement can assign them to names in the namespace the import was executed in.
3
7
75,823,194
2023-3-23
https://stackoverflow.com/questions/75823194/create-column-in-dataframe-for-each-row-in-other-dataframe-and-compute-values
I have a DataFrame called player: player_df = pd.DataFrame(np.random.rand(10,3), columns=['x','y','more_cols']) _____________________________________________________________________________ player_df: x y more_cols 0 0.352673 0.479360 0.638508 1 0.764669 0.326961 0.778483 2 0.805774 0.911662 0.316030 3 0.114446 0.185147 0.318742 4 0.714803 0.646525 0.084143 5 0.061614 0.837432 0.886669 6 0.179777 0.519559 0.446562 7 0.615326 0.886046 0.581127 8 0.597375 0.196619 0.310331 9 0.670061 0.471363 0.313047 a second DataFrame called checkpoints_df: checkpoints_df = pd.DataFrame(np.random.rand(4,2), columns=['x','y']) checkpoints_df['checkpoint_name'] = ['Alpha', 'Hotel', 'Indigo', 'Papa'] _____________________________________________________________________________ checkpoints_df: x y checkpoint_names 0 0.616945 0.804442 Alpha 1 0.402007 0.556274 Hotel 2 0.478351 0.443920 Indigo 3 0.075494 0.803561 Papa and a function distance(x1,y1,x2,y2) that calculates the euclidean distance between 2 points, or a list of points and a point (x1 and y1 can be lists). Goal: I want to add a column to 'player_df' for each checkpoint name in 'checkpoints_df['checkpoint_name']', and fill the column with the distance of the player to that checkpoint (this is a mockup problem, the real problem could have a lot of 'checkpoints') So far I've tried many things, but settled on a solution that uses .iterrows(), however this could be slow if there are many checkpoints. This is what I use right now: for _, row in checkpoints_df.iterrows(): player_df[row['name']] = distance(player_df['x'], player_df['y'], row['x'], row['y']) I've tried using .apply() but couldn't create columns with this. Is there a way to do this without iterating over the second dataframe?
If your distance function is vectorized, you can do: import numpy as np def distance(x1, y1, x2, y2): return np.sqrt((x2-x1)**2+(y2-y1)**2) tmp = checkpoints_df.set_index('checkpoint_name') for c in checkpoints_df.index: player_df[c] = distance(player_df['x'], player_df['y'], tmp.loc[c, 'x'], tmp.loc[c, 'y']) Or, fully vectorized: player_df[checkpoints_df['checkpoint_name']] = distance( player_df['x'].to_numpy()[:,None], player_df['y'].to_numpy()[:,None], checkpoints_df['x'].to_numpy()[None], checkpoints_df['y'].to_numpy()[None] ) Output: x y more_cols Alpha Hotel Indigo Papa 0 0.548814 0.715189 0.602763 0.290325 0.173562 0.538927 0.116871 1 0.544883 0.423655 0.645894 0.448875 0.169807 0.560716 0.204632 2 0.437587 0.891773 0.963663 0.209178 0.323871 0.500542 0.325561 3 0.383442 0.791725 0.528895 0.120166 0.234831 0.404077 0.287810 4 0.568045 0.925597 0.071036 0.339141 0.374280 0.629699 0.311790 5 0.087129 0.020218 0.832620 0.774609 0.660846 0.601313 0.794770 6 0.778157 0.870012 0.978618 0.522455 0.441177 0.800208 0.302696 7 0.799159 0.461479 0.780529 0.619367 0.359296 0.795839 0.243226 8 0.118274 0.639921 0.143353 0.198590 0.345356 0.101950 0.494356 9 0.944669 0.521848 0.414662 0.725433 0.490735 0.930821 0.345899
3
2
75,821,532
2023-3-23
https://stackoverflow.com/questions/75821532/shapely-runtimewarning-invalid-value-encountered-in-intersection
Got this warning when trying to calculate the intersection between two geometry objects. >>> shapely.intersection(LineString([(0, 0), (1, 1)], LineString([(2.5, 2.5), (3, 3)])) .../lib/python3.9/site-packages/shapely/set_operations.py:133: RuntimeWarning: invalid value encountered in intersection return lib.intersection(a, b, **kwargs)
I think the warning occurs when there is no intersection at all between the two geometries, so what I did is to check if there is an intersection first with intersects() and only then calculate the intersection between them. You can then handle the case where no intersection occurs according to your application. def get_iou( polygon1, polygon2): if polygon1.intersects(polygon2): intersect = polygon1.intersection(polygon2).area union = polygon1.union(polygon2).area return intersect/union return 0
3
6
75,815,288
2023-3-22
https://stackoverflow.com/questions/75815288/slice-a-multidimensional-pytorch-tensor-based-on-values-in-other-tensors
I have 4 PyTorch tensors: data of shape (l, m, n) a of shape (k,) and datatype long b of shape (k,) and datatype long c of shape (k,) and datatype long I want to slice the tensor data such that it picks the element addressed by a in 0th dimension. In the 1st and 2nd dimensions, I want to pick a patch of values based on the element addressed by b and c. Specifically, I want to pick 9 values - a 3x3 patch around the value addressed by b. Thus my sliced tensor should have a shape (k, 3, 3). MWE: data = torch.arange(200).reshape((2, 10, 10)) a = torch.Tensor([1, 0, 1, 1, 0]).long() b = torch.Tensor([5, 6, 3, 4, 7]).long() c = torch.Tensor([4, 3, 7, 6, 5]).long() data1 = data[a, b-1:b+1, c-1:c+1] # gives error >>> TypeError: only integer tensors of a single element can be converted to an index Expected output data1[0] = [[143,144,145],[153,154,155],[163,164,165]] data1[1] = [[52,53,54],[62,63,64],[72,73,74]] data1[2] = [[126,127,128],[136,137,138],[146,147,148]] and so on How can I do this without using for loop? PS: I've padded data to make sure that the locations addressed by a,b,c are within the limit. I don't need gradients to flow through this operation. So, I can convert these to NumPy and slice if that is faster. But I would prefer a solution in PyTorch.
I would first expand the indices and then add shifts to the repeated indices. Note that the shift for the row and column should be reversed. For example, import torch data = torch.arange(200).reshape((2, 10, 10)) a = torch.Tensor([1, 0, 1, 1, 0]).long() b = torch.Tensor([5, 6, 3, 4, 7]).long() c = torch.Tensor([4, 3, 7, 6, 5]).long() index1 = a.repeat_interleave(9) # kernel_size^2 index2 = b.repeat_interleave(9) # kernel_size^2 shift = torch.arange(-1, 2).repeat_interleave(3).repeat(5) # Shape: (kernel_size^2 x 5) -> [-1, -1, -1, 0, 0, 0, 1, 1, 1] shifted_index2 = index2 + shift index3 = c.repeat_interleave(9) shift = torch.arange(-1, 2).repeat(3).repeat(5) # Shape: (kernel_size^2 x 5) -> [-1, 0, 1, -1, 0, 1, -1, 0, 1] shifted_index3 = index3 + shift # Use the indexing arrays to select the patches data1 = data[index1, shifted_index2, shifted_index3].view(5, 3, 3) print(data1[0]) print(data1[1]) print(data1[2]) The output: tensor([[143, 144, 145], [153, 154, 155], [163, 164, 165]]) tensor([[52, 53, 54], [62, 63, 64], [72, 73, 74]]) tensor([[126, 127, 128], [136, 137, 138], [146, 147, 148]])
3
2
75,740,652
2023-3-15
https://stackoverflow.com/questions/75740652/fastapi-streamingresponse-not-streaming-with-generator-function
I have a relatively simple FastAPI app that accepts a query and streams back the response from ChatGPT's API. ChatGPT is streaming back the result and I can see this being printed to console as it comes in. What's not working is the StreamingResponse back via FastAPI. The response gets sent all together instead. I'm really at a loss as to why this isn't working. Here is the FastAPI app code: import os import time import openai import fastapi from fastapi import Depends, HTTPException, status, Request from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from fastapi.responses import StreamingResponse auth_scheme = HTTPBearer() app = fastapi.FastAPI() openai.api_key = os.environ["OPENAI_API_KEY"] def ask_statesman(query: str): #prompt = router(query) completion_reason = None response = "" while not completion_reason or completion_reason == "length": openai_stream = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": query}], temperature=0.0, stream=True, ) for line in openai_stream: completion_reason = line["choices"][0]["finish_reason"] if "content" in line["choices"][0].delta: current_response = line["choices"][0].delta.content print(current_response) yield current_response time.sleep(0.25) @app.post("/") async def request_handler(auth_key: str, query: str): if auth_key != "123": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": auth_scheme.scheme_name}, ) else: stream_response = ask_statesman(query) return StreamingResponse(stream_response, media_type="text/plain") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000, debug=True, log_level="debug") And here is the very simple test.py file to test this: import requests query = "How tall is the Eiffel tower?" url = "http://localhost:8000" params = {"auth_key": "123", "query": query} response = requests.post(url, params=params, stream=True) for chunk in response.iter_lines(): if chunk: print(chunk.decode("utf-8"))
First, it wouldn't be good practice to use a POST request for requesting data from the server. Using a GET request instead would be more suitable, in your case. In addition to that, you shouldn't be sending credentials, such as auth_key as part of the URL (i.e., using the query string), but you should rather use Headers and/or Cookies (using HTTPS). Please have a look at this answer for more details and examples on the concepts of headers and cookies, as well as the risks involved when using query parameters instead. Helpful posts around this topic can also be found here and here, as well as here, here and here. Second, if you are executing a blocking operation (i.e., blocking I/O-bound or CPU-bound tasks) inside the StreamingResponse's generator function, you should define the generator function with def instead of async def, as, otherwise, the blocking operation, as well as the time.sleep() function that is used inside your generator, would blcok the event loop. As explained here, if the function for streaming the response body is a normal def generator and not an async def one, FastAPI will use iterate_in_threadpool() to run the iterator/generator in a separate thread that is then awaitedβ€”see StreamingResponse's relevant source code. If you prefer using an async def generator, then make sure to execute any blocking operations in an external ThreadPool (or ProcessPool) and await it, as well as use await asyncio.sleep() instead of time.sleep(), in cased you need to add delay in the execution of an operation. Have a look at this detailed answer for more details and examples. Third, you are using requests' iter_lines() function, which iterates over the response data, one line at a time. If, however, the response data did not include any line break character (i.e., \n), you wouldn't see the data on client's console getting printed as they arrive, until the entire response is received by the client and printed as a whole. In that case, you should instead use iter_content() and specify the chunk_size as desired (both cases are demonstrated in the example below). Finally, if you would like the StreamingResponse to work in every web browser (including Chrome as well)β€”in the sense of being able to see the data as they stream inβ€”you should specify the media_type to a different type than text/plain (e.g., application/json or text/event-stream, see here), or disable MIME Sniffing. As explained here, browsers will start buffering text/plain responses for a certain amount (around 1445 bytes, as documented here), in order to check whether or not the content received is actually plain text. To avoid that, you can either set the media_type to text/event-stream (used for server-sent events), or keep using text/plain, but set the X-Content-Type-Options response header to nosniff, which would disable MIME Sniffing (both options are demonstrated in the example below). Working Example app.py from fastapi import FastAPI from fastapi.responses import StreamingResponse import asyncio app = FastAPI() async def fake_data_streamer(): for i in range(10): yield b'some fake data\n\n' await asyncio.sleep(0.5) # If your generator contains blocking operations such as time.sleep(), then define the # generator function with normal `def`. Alternatively, use `async def` and run any # blocking operations in an external ThreadPool/ProcessPool. (see 2nd paragraph of this answer) ''' import time def fake_data_streamer(): for i in range(10): yield b'some fake data\n\n' time.sleep(0.5) ''' @app.get('/') async def main(): return StreamingResponse(fake_data_streamer(), media_type='text/event-stream') # or, use: ''' headers = {'X-Content-Type-Options': 'nosniff'} return StreamingResponse(fake_data_streamer(), headers=headers, media_type='text/plain') ''' test.py (using Python requests) import requests url = "http://localhost:8000/" with requests.get(url, stream=True) as r: for chunk in r.iter_content(1024): # or, for line in r.iter_lines(): print(chunk) test.py (using httpxβ€”see this, as well as this and this for the benefits of using httpx over requests) import httpx url = 'http://127.0.0.1:8000/' with httpx.stream('GET', url) as r: for chunk in r.iter_raw(): # or, for line in r.iter_lines(): print(chunk)
37
76
75,748,777
2023-3-15
https://stackoverflow.com/questions/75748777/does-polars-preserve-row-order-in-a-left-join
Consider the following polars dataframes: >>> left = pl.DataFrame(pl.Series('a', [1,5,3,2])) >>> left shape: (4, 1) β”Œβ”€β”€β”€β”€β”€β” β”‚ a β”‚ β”‚ --- β”‚ β”‚ i64 β”‚ β•žβ•β•β•β•β•β•‘ β”‚ 1 β”‚ β”‚ 5 β”‚ β”‚ 3 β”‚ β”‚ 2 β”‚ β””β”€β”€β”€β”€β”€β”˜ >>> right = pl.DataFrame([pl.Series('a', [0,1,2,3]), pl.Series('b', [4,5,6,7])]) >>> right shape: (4, 2) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ a ┆ b β”‚ β”‚ --- ┆ --- β”‚ β”‚ i64 ┆ i64 β”‚ β•žβ•β•β•β•β•β•ͺ═════║ β”‚ 0 ┆ 4 β”‚ β”‚ 1 ┆ 5 β”‚ β”‚ 2 ┆ 6 β”‚ β”‚ 3 ┆ 7 β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜ I would like to join the two in such a way that the order of the a values from the left dataframe is preserved. A left join seems to do this: >>> left.join(right, on='a', how='left') shape: (4, 2) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β” β”‚ a ┆ b β”‚ β”‚ --- ┆ --- β”‚ β”‚ i64 ┆ i64 β”‚ β•žβ•β•β•β•β•β•ͺ══════║ β”‚ 1 ┆ 5 β”‚ β”‚ 5 ┆ null β”‚ β”‚ 3 ┆ 7 β”‚ β”‚ 2 ┆ 6 β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”˜ My question is: is this behaviour guaranteed? If not, what would be the safe way to do this? I could use with_row_index and then do a final sort, but that seems rather cumbersome. In pandas this can be done concisely with the reindex method.
Update (November 2024): Polars has decided to no longer guarantee preserving row order in left joins in the future. More background on this decision can be found in this GitHub issue. The bottom line: this guarantee may be expensive. A new maintain_order parameter will be added in the future which allows users to control this behavior. By default, order will not be preserved. In order to future-proof your code now, you can use the workaround mentioned below of adding a row index and sorting on that. Original post: A left join guarantees preserving the order of the left dataframe, at least in the regular engine. For the streaming engine, this might not be guaranteed. If you want to be 'safe', you already have the right workaround in mind to add a row index and sort on that.
5
2
75,793,219
2023-3-20
https://stackoverflow.com/questions/75793219/polars-replace-time-zone-function-throws-error-of-non-existent-in-time-zone
here's our test data to work with: import polars as pl import pandas as pd from datetime import date, time, datetime df = pl.DataFrame( pl.datetime_range( start=date(2022, 1, 3), end=date(2022, 9, 30), interval="5m", time_unit="ns", time_zone="UTC", eager=True ).alias("UTC") ) I specifically need replace_time_zone to actually change the underlying timestamp. It works with convert_time_zone: df.select( pl.col("UTC").dt.convert_time_zone(time_zone="America/New_York").alias("US") ) shape: (77_761, 1) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ US β”‚ β”‚ --- β”‚ β”‚ datetime[ns, America/New_York] β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•‘ β”‚ 2022-01-02 19:00:00 EST β”‚ β”‚ 2022-01-02 19:05:00 EST β”‚ β”‚ 2022-01-02 19:10:00 EST β”‚ β”‚ 2022-01-02 19:15:00 EST β”‚ β”‚ 2022-01-02 19:20:00 EST β”‚ β”‚ … β”‚ β”‚ 2022-09-29 19:40:00 EDT β”‚ β”‚ 2022-09-29 19:45:00 EDT β”‚ β”‚ 2022-09-29 19:50:00 EDT β”‚ β”‚ 2022-09-29 19:55:00 EDT β”‚ β”‚ 2022-09-29 20:00:00 EDT β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ But fails with replace_time_zone: df.select( pl.col("UTC").dt.replace_time_zone(time_zone="America/New_York").alias("US") ) # ComputeError: datetime '2022-03-13 02:00:00' is non-existent in time zone 'America/New_York'. # You may be able to use `non_existent='null'` to return `null` in this case.
You cannot replace the timezone in a UTC time series with a timezone that has DST transitions - you'll end up with non-existing and/or missing datetimes. The error could be a bit more informative, but I do not think this is specific to polars. Here's an illustration. "America/New_York" had a DST transition on Mar 13. 2 am did not exist on that day... so this works fine: import polars as pl from datetime import date df = pl.DataFrame( pl.datetime_range( start=date(2022, 3, 11), end=date(2022, 3, 13), interval="5m", time_unit="ns", time_zone="UTC", eager=True, ).alias("UTC") ) print( df.select( pl.col("UTC").dt.replace_time_zone(time_zone="America/New_York").alias("US") ) ) # shape: (289, 1) # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # β”‚ US β”‚ # β”‚ --- β”‚ # β”‚ datetime[ns, America/New_York] β”‚ # β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•‘ # β”‚ 2022-03-11 00:00:00 EST β”‚ # β”‚ 2022-03-11 00:05:00 EST β”‚ # β”‚ 2022-03-11 00:10:00 EST β”‚ # β”‚ 2022-03-11 00:15:00 EST β”‚ # β”‚ … β”‚ while this doesn't: df = pl.DataFrame( pl.datetime_range( start=date(2022, 3, 13), end=date(2022, 3, 15), interval="5m", time_unit="ns", time_zone="UTC", eager=True, ).alias("UTC") ) print( df.select( pl.col("UTC").dt.replace_time_zone(time_zone="America/New_York").alias("US") ) ) # ComputeError: datetime '2022-03-13 02:00:00' is non-existent in time zone Workaround you could use is to convert UTC to the desired timezone, then add its UTC offset. Ex: df = pl.DataFrame( pl.datetime_range( start=date(2022, 1, 3), end=date(2022, 9, 30), interval="5m", time_unit="ns", time_zone="UTC", eager=True, ).alias("UTC") ) df = df.with_columns( pl.col("UTC").dt.convert_time_zone(time_zone="America/New_York").alias("US") ) df = df.with_columns( (pl.col("US")+(pl.col("UTC")-pl.col("US").dt.replace_time_zone(time_zone="UTC"))) .alias("US_fakeUTC") ) print(df.select(pl.col("US_fakeUTC"))) # shape: (77_761, 1) # β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # β”‚ US_fakeUTC β”‚ # β”‚ --- β”‚ # β”‚ datetime[ns, America/New_York] β”‚ # β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•‘ # β”‚ 2022-01-03 00:00:00 EST β”‚ # β”‚ 2022-01-03 00:05:00 EST β”‚ # β”‚ 2022-01-03 00:10:00 EST β”‚ # β”‚ 2022-01-03 00:15:00 EST β”‚ # β”‚ … β”‚
3
2
75,791,765
2023-3-20
https://stackoverflow.com/questions/75791765/how-to-download-videos-that-require-age-verification-with-pytube
I download and clip some youtube videos with pytube but some videos are not downloading and asking for age verification. How can I solve this? Thanks for your advice
For pytube 15.0.0 I had the AgeRestrictedError in streams contents even using the use_oauth option. I fixed the problem only replacing ANDROID_MUSIC with ANDROID as "client" at line 223 of innertube.py: def __init__(self, client='ANDROID_MUSIC', use_oauth=False, allow_cache=True): def __init__(self, client='ANDROID', use_oauth=False, allow_cache=True):
20
36
75,804,599
2023-3-21
https://stackoverflow.com/questions/75804599/openai-api-how-do-i-count-tokens-before-i-send-an-api-request
OpenAI's text models have a context length, e.g.: Curie has a context length of 2049 tokens. They provide max_tokens and stop parameters to control the length of the generated sequence. Therefore the generation stops either when stop token is obtained, or max_tokens is reached. The issue is: when generating a text, I don't know how many tokens my prompt contains. Since I do not know that, I cannot set max_tokens = 2049 - number_tokens_in_prompt. This prevents me from generating text dynamically for a wide range of text in terms of their length. What I need is to continue generating until the stop token. My questions are: How can I count the number of tokens in Python API so that I will set max_tokens parameter accordingly? Is there a way to set max_tokens to the max cap so that I won't need to count the number of prompt tokens?
How do I count tokens before(!) I send an API request? As stated in the official OpenAI article: To further explore tokenization, you can use our interactive Tokenizer tool, which allows you to calculate the number of tokens and see how text is broken into tokens. Alternatively, if you'd like to tokenize text programmatically, use tiktoken as a fast BPE tokenizer specifically used for OpenAI models. How does a tokenizer work? A tokenizer can split the text string into a list of tokens, as stated in the official OpenAI example on counting tokens with tiktoken: tiktoken is a fast open-source tokenizer by OpenAI. Given a text string (e.g., "tiktoken is great!") and an encoding (e.g., "cl100k_base"), a tokenizer can split the text string into a list of tokens (e.g., ["t", "ik", "token", " is", " great", "!"]). Splitting text strings into tokens is useful because GPT models see text in the form of tokens. Knowing how many tokens are in a text string can tell you: whether the string is too long for a text model to process and how much an OpenAI API call costs (as usage is priced by token). Which encodings does OpenAI use for its models? As of April 2024, tiktoken supports 2 encodings used by OpenAI models (source 1, source 2): Encoding name OpenAI models o200k_base β€’ GPT-4o models (gpt-4o) cl100k_base β€’ GPT-4 models (gpt-4)β€’ GPT-3.5 Turbo models (gpt-3.5-turbo)β€’ GPT Base models (davinci-002, babbage-002)β€’ Embeddings models (text-embedding-ada-002, text-embedding-3-large, text-embedding-3-small)β€’ Fine-tuned models (ft:gpt-4, ft:gpt-3.5-turbo, ft:davinci-002, ft:babbage-002) Note: The p50k_base and r50k_base encodings were used for models that are deprecated as of April 2024. What tokenizer libraries are out there? Official OpenAI libraries: Python: tiktoken 3rd-party libraries: Python: GPT2TokenizerFast Node.js: tiktoken, gpt4-tokenizer, gpt3-tokenizer, gpt-3-encoder .NET / C#: tryAGI.Tiktoken, SharpToken, TiktokenSharp, GPT Tokenizer Java: jtokkit, gpt2-tokenizer-java PHP: GPT-3-Encoder-PHP How do I use tiktoken? Install or upgrade tiktoken: pip install --upgrade tiktoken Write the code to count tokens, where you have two options. OPTION 1: Search in the table above for the correct encoding for a given OpenAI model If you run get_tokens_1.py, you'll get the following output: 9 get_tokens_1.py import tiktoken def num_tokens_from_string(string: str, encoding_name: str) -> int: encoding = tiktoken.get_encoding(encoding_name) num_tokens = len(encoding.encode(string)) return num_tokens print(num_tokens_from_string("Hello world, let's test tiktoken.", "cl100k_base")) OPTION 2: Use tiktoken.encoding_for_model() to automatically load the correct encoding for a given OpenAI model If you run get_tokens_2.py, you'll get the following output: 9 get_tokens_2.py import tiktoken def num_tokens_from_string(string: str, encoding_name: str) -> int: encoding = tiktoken.encoding_for_model(encoding_name) num_tokens = len(encoding.encode(string)) return num_tokens print(num_tokens_from_string("Hello world, let's test tiktoken.", "gpt-3.5-turbo")) Note: If you take a careful look at the usage field in the OpenAI API response, you'll see that it reports 10 tokens used for an identical message. That's 1 token more than tiktoken. I still haven't figured out why. I tested this in the past. As @Jota mentioned in the comment below, there still seems to be a mismatch between the token usage reported by the OpenAI API response and tiktoken.
86
114
75,799,955
2023-3-21
https://stackoverflow.com/questions/75799955/how-to-do-inference-with-yolov5-and-onnx
I've trained a YOLOv5 model and it works well on new images with yolo detect.py I've exported the model to ONNX and now i'm trying to load the ONNX model and do inference on a new image. My code works but I don't get the correct bounding boxes. I need to get the area of the bounding boxes etc. so I can't just use detect.py Also I used Yolo's non_max_suppression to prune the list of bbox but I don't if it's a good solution. What I did yet: # Load image and preprocessing import cv2 import numpy as np img = cv2.imread("image.jpg", cv2.IMREAD_UNCHANGED) resized = cv2.resize(img, (640,640), interpolation = cv2.INTER_AREA).astype(np.float32) resized = resized.transpose((2, 0, 1)) resized = np.expand_dims(resized, axis=0) # Add batch dimension # run session on ONNX import onnxruntime as ort ort_session = ort.InferenceSession("yolov5.onnx", providers=["CUDAExecutionProvider"]) # compute ONNX Runtime output prediction ort_inputs = {ort_session.get_inputs()[0].name: resized} ort_outs = ort_session.run(None, ort_inputs) HERE I HAVE TENSOR WITH ALL THE BOUNDING BOXES # Keep only interesting bounding boxes import torch from yolov5.utils.general import non_max_suppression, xyxy2xywh output= torch.from_numpy(np.asarray(ort_outs)) out = non_max_suppression(output, conf_thres=0.2, iou_thres=0.5)[0] # convert xyxy to xywh xyxy = out[:,:4] xywh = xyxy2xywh(xyxy) out[:, :4] = xywh # Show bbox from PIL import Image, ImageDraw, ImageFont tmp_image = Image.fromarray(img) draw = ImageDraw.Draw(tmp_image) for i,(x,y,w,h,score,class_id) in enumerate(out): real_x = x * w_ratio # resize from model size to image size real_y = y * h_ratio shape = (real_x, real_y, (x + w) * w_ratio, (y + h) * h_ratio) # shape of the bounding box to draw class_id = round(float(class_id)) class_string = list(class_list.keys())[list(class_list.values()).index(class_id)] color = CLASS_RECTANGLE_COLORS[class_string] draw.rectangle(shape, outline=color, width=4) fnt = ImageFont.load_default() draw.multiline_text((real_x + 8, real_y + 8), f"{class_string} {score*100:.2f}%", font=fnt, fill=color) tmp_image.show() Image with my algorithm vs detect.py : https://i.sstatic.net/ZxNLJ.jpg Can anyone help ?
I decided to give up and use this code : import cv2 import torch from PIL import Image # Model model = torch.hub.load(path_to_yolo_library, 'custom', path=onnx_path, source='local') img = Image.open(image_path) # PIL image img = img.resize((640,640)) # Inference results = model(img, size=640) # includes NMS # Results results.print() # print results to screen results.show() # display results results.save() # save as results1.jpg, results2.jpg... etc. # Data print('\n', results.xyxy[0]) # print img1 predictions
4
0