3

I'm rewriting some code from Ruby to Python. The code is for a Perceptron, listed in section 8.2.6 of Clever Algorithms: Nature-Inspired Programming Recipes. I've never used Ruby before and I don't understand this part:

def test_weights(weights, domain, num_inputs)
  correct = 0
  domain.each do |pattern|
    input_vector = Array.new(num_inputs) {|k| pattern[k].to_f}
    output = get_output(weights, input_vector)
    correct += 1 if output.round == pattern.last
  end
  return correct
end

Some explanation: num_inputs is an integer (2 in my case), and domain is a list of arrays: [[1,0,1], [0,0,0], etc.]

I don't understand this line:

input_vector = Array.new(num_inputs) {|k| pattern[k].to_f}

It creates an array with 2 values, every values |k| stores pattern[k].to_f, but what is pattern[k].to_f?

0

3 Answers 3

4

Try this:

input_vector = [float(pattern[i]) for i in range(num_inputs)]
Sign up to request clarification or add additional context in comments.

2 Comments

float() isn't necessary in python, I think it's a ruby thing that I can't understand now...
@paolocappelletto, it depends on what get_output does. Integer division in Python 2 can give you unexpected results.
2
pattern[k].to_f

converts pattern[k] to a float.

Comments

0

I'm not a Ruby expert, but I think it would be something like this in Python:

def test_weights(weights, domain, num_inputs):
    correct = 0
    for pattern in domain:
        output = get_output(weights, pattern[:num_inputs])
        if round(output) == pattern[-1]:
            correct += 1
    return correct

There is plenty of scope for optimising this: if num_inputs is always one less then the length of the lists in domain then you may not need that parameter at all.

Be careful about doing line by line translations from one language to another: that tends not to give good results no matter what languages are involved.

Edit: since you said you don't think you need to convert to float you can just slice the required number of elements from the domain value. I've updated my code accordingly.

1 Comment

Thanks. I'm totally agree with you about line by line translation, my problem is that I'm missing the behavior below the code. with Array.new(2) I create an array with two values, every value is equal the current value of domain list (I don't think is necessary to convert to float)... oh god I need a coffe...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.