paolo cappelletto
paolo cappelletto

Reputation: 101

Translate ruby to python

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?

Upvotes: 3

Views: 4602

Answers (3)

Duncan
Duncan

Reputation: 95722

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.

Upvotes: 0

Rob Wouters
Rob Wouters

Reputation: 16327

Try this:

input_vector = [float(pattern[i]) for i in range(num_inputs)]

Upvotes: 4

user647772
user647772

Reputation:

pattern[k].to_f

converts pattern[k] to a float.

Upvotes: 2

Related Questions