Linear Search with Enumerate - enumerate

I have started learning Python not to long ago and have decided to try making a linear search algorithim. The problem that seems to exist is that found is never = true therefore never triggering the print. The program is attached below. Any help would be greatly appreciated!
numbers = [55,37,12,13,89,47,3,24,21]
number_to_find = input("Enter a number to find:")
found = False
for index, single_num in enumerate(numbers):
if numbers[index] == number_to_find:
found = True
break
if found == True:
print(f"Found {number_to_find} at index {index}")
else:
print(f"Unable to find {number_to_find} in array")

Related

BertModel transformers outputs string instead of tensor

I'm following this tutorial that codes a sentiment analysis classifier using BERT with the huggingface library and I'm having a very odd behavior. When trying the BERT model with a sample text I get a string instead of the hidden state. This is the code I'm using:
import transformers
from transformers import BertModel, BertTokenizer
print(transformers.__version__)
PRE_TRAINED_MODEL_NAME = 'bert-base-cased'
PATH_OF_CACHE = "/home/mwon/data-mwon/paperChega/src_classificador/data/hugingface"
tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME,cache_dir = PATH_OF_CACHE)
sample_txt = 'When was I last outside? I am stuck at home for 2 weeks.'
encoding_sample = tokenizer.encode_plus(
sample_txt,
max_length=32,
add_special_tokens=True, # Add '[CLS]' and '[SEP]'
return_token_type_ids=False,
padding=True,
truncation = True,
return_attention_mask=True,
return_tensors='pt', # Return PyTorch tensors
)
bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME,cache_dir = PATH_OF_CACHE)
last_hidden_state, pooled_output = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask']
)
print([last_hidden_state,pooled_output])
that outputs:
4.0.0
['last_hidden_state', 'pooler_output']
While the answer from Aakash provides a solution to the problem, it does not explain the issue. Since one of the 3.X releases of the transformers library, the models do not return tuples anymore but specific output objects:
o = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask']
)
print(type(o))
print(o.keys())
Output:
transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions
odict_keys(['last_hidden_state', 'pooler_output'])
You can return to the previous behavior by adding return_dict=False to get a tuple:
o = bert_model(
encoding_sample['input_ids'],
encoding_sample['attention_mask'],
return_dict=False
)
print(type(o))
Output:
<class 'tuple'>
I do not recommend that, because it is now unambiguous to select a specific part of the output without turning to the documentation as shown in the example below:
o = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'], return_dict=False, output_attentions=True, output_hidden_states=True)
print('I am a tuple with {} elements. You do not know what each element presents without checking the documentation'.format(len(o)))
o = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'], output_attentions=True, output_hidden_states=True)
print('I am a cool object and you can acces my elements with o.last_hidden_state, o["last_hidden_state"] or even o[0]. My keys are; {} '.format(o.keys()))
Output:
I am a tuple with 4 elements. You do not know what each element presents without checking the documentation
I am a cool object and you can acces my elements with o.last_hidden_state, o["last_hidden_state"] or even o[0]. My keys are; odict_keys(['last_hidden_state', 'pooler_output', 'hidden_states', 'attentions'])
I faced the same issue while learning how to implement Bert. I noticed that using
last_hidden_state, pooled_output = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'])
is the issue. Use:
outputs = bert_model(encoding_sample['input_ids'], encoding_sample['attention_mask'])
and extract the last_hidden state using
output[0]
You can refer to the documentation here which tells you what is returned by the BertModel

Cant get a math.random to work in two different places

function INV:DeleteInventoryItem( ply, pos, item)
local rarity = INV.PLAYERS[ply:SteamID64()][pos].quality
---print(rarity)
local value = "credits"
if(rarity == "Common")then
local amount = math.floor(math.random(1, 30))
table.remove( INV.PLAYERS[ply:SteamID64()], pos)
local var = ply:ChatPrint("You got ".. amount .." credits from deconstructing!")
ply:INVAddCredits( amount )
self.SAVE:SendInventory( ply )
local updatevalue = INV.PLAYERS[ply:SteamID64()].inventorydata.credits
UpdateDatabase(value, ply:SteamID(), updatevalue)
end
end
The problem I am having is that I cannot get the same value from the amount variable, so it says that you got a certain amount when it actually gave you a different amount.
I am really confused on how I can make it the same amount... Any help would be appreciated!
Thanks for all the help you guys have been, I since have fixed the issue and it was something wrong with the adding of the inventory credits.
-Thanks D12

extensions or even observation empty with Chainer

I am kind of new on Chainer and I have been struggling with a weird situation recently.
I have a Chain to compute a CNN which I feed with a labeledDataSet.
But no results appears when I use the extensions. When I display the observation value it is empty. But the loss is indeed calculated and the parameters updated (at least they change) so I don't know where is the connection problem.
def convert(batch, device):
return chainer.dataset.convert.concat_examples(batch, device, padding=0)
def print_obs(t):
print("trainer.observation", trainer.observation)
print("updater.loss", updater.loss_func)
print("conv1", model.predictor.conv1.W[0][0])
print("conv20", model.predictor.conv20.W[0][0])
model.predictor.train = True
model.predictor.finetune = False ####or True ??
cuda.get_device(0).use()
model.to_gpu()
optimizer = optimizers.MomentumSGD(lr=learning_rate, momentum=momentum)
optimizer.use_cleargrads()
optimizer.setup(model)
optimizer.add_hook(chainer.optimizer.WeightDecay(weight_decay))
train, test = imageNet_data.train_val_test()
train_iter = iterators.SerialIterator(train, batch_size)
test_iter = iterators.SerialIterator(test, batch_size, repeat=False,shuffle=False)
with chainer.using_config('debug', True):
# Set up a trainer
updater = training.StandardUpdater(train_iter, optimizer, loss_func=model, converter=convert)
trainer = training.Trainer(updater, (10, 'epoch'), out="./backup/result")
trainer.extend(print_obs, trigger=(3, 'iteration'))
trainer.extend(extensions.LogReport())
trainer.extend(extensions.PrintReport(
['epoch', 'main/loss', 'validation/main/loss',
'main/accuracy', 'validation/main/accuracy', 'elapsed_time']))
trainer.run()
Maybe this is something is miss completely and which is quite obvious.. Thank you for all remarks that would help me a lot.
Chainer4.1, Ubuntu16
If you are using your own Link with the Trainer, you need to report metrics using chainer.report by your own.
See https://docs.chainer.org/en/stable/guides/report.html for instructions.
You can see some examples in Chainer repository:
https://github.com/chainer/chainer/blob/v4.1.0/chainer/links/model/classifier.py#L116
https://github.com/chainer/chainer/blob/v4.1.0/examples/imagenet/alex.py#L40

Prompting the user for an int, not a string, until they do even if it's a negative number

I'm writing a program and it asks the user to input a number, I need to make sure that that number is and actual number not a string. That number can be positive or negative. I've tried using .isnumerical() and .isdigit() but they won't except negative numbers.
lowest_num = input("What would you like the lowest possible number to be?")
while lowest_num.isdigit() is not True:
lowest_num = (input("Please only enter a number : ")).lower()
Thanks for the help in advance
lowest_num = int(input("What would you like the lowest possible number to be?")) should do it
Alright, try this:
number_not_entered = True
num = 0
while number_not_entered:
try:
num = int(input("enter num"))
number_not_entered = False
except ValueError:
print("please try again")
Note that catching all exceptions is generally a bad practice.
Use isnan() function from numpy library. First import numpy and then use numpy.isnan(a number)

How to define empty IndexedTables in Julia?

I am unable to define empty IndexedTables, e.g.
using IndexedTables, IndexedTables.Table
t = Table(Columns(a=Int64[],b=String[]),Int64[])
t[1,"a"] = 1
t[1,"b"] = 2
t[1,"c"] = t[1,"a"] + t[1,"b"]
BoundsError: attempt to access 0-element Array{Int64,1} at index [0]
I am aware that creating the IndexedTable with already the data is more efficient that creating an empty one and then insert values, but sometimes you are obliged to go on this way.
Is this a bug ? If so, is there any workaround possible ?
(I already posted this thread on the Julia forum, but so far I had no replies there)
This is probably a bug in IndexedTables.
Inserting into an IndexedTable requires reindexing to access the data. Reindexing is done with flush!.
But flush!(t) fails in the example in the question with the empty t.
Fixing flush! which calls _merge! can be done by:
julia> function IndexedTables._merge!(dst::IndexedTable, src::IndexedTable, f)
if length(dst.index)==0 || isless(dst.index[end], src.index[1])
append!(dst.index, src.index)
append!(dst.data, src.data)
else
# merge to a new copy
new = _merge(dst, src, f)
ln = length(new)
# resize and copy data into dst
resize!(dst.index, ln)
copy!(dst.index, new.index)
resize!(dst.data, ln)
copy!(dst.data, new.data)
end
return dst
end
julia> t[1,"c"] = t[1,"a"] + t[1,"b"]
3
The change is the addition of the length(...) check in the first if.
Of course, a pull request / issue should be opened with IndexedTables.jl. Antonello, will you do this? (or shall I)

Resources