Pregunta

Me pregunto si hay una manera de hacer lo que puedo hacer a continuación con Python, en Ruby:

sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))

Tengo dos matrices de iguales tamaños con los pesos y los datos, pero parece que no puedo encontrar una función similar al mapa en Ruby, reducción que tengo funcionando.

¿Fue útil?

Solución

@Michiel de Mare

Su ejemplo de Ruby 1.9 se puede acortar un poco más:

weights.zip(data).map(:*).reduce(:+)

También tenga en cuenta que en Ruby 1.8, si necesita ActiveSupport (de Rails), puede usar:

weights.zip(data).map(&:*).reduce(&:+)

Otros consejos

En Rubí 1.9:

weights.zip(data).map{|a,b| a*b}.reduce(:+)

En Rubí 1.8:

weights.zip(data).inject(0) {|sum,(w,d)| sum + w*d }

La función Array.zip realiza una combinación de matrices por elementos.No es tan claro como la sintaxis de Python, pero aquí hay un enfoque que podrías usar:

weights = [1, 2, 3]
data = [4, 5, 6]
result = Array.new
a.zip(b) { |x, y| result << x * y } # For just the one operation

sum = 0
a.zip(b) { |x, y| sum += x * y } # For both operations

Rubí tiene un map método (también conocido comoel collect método), que se puede aplicar a cualquier Enumerable objeto.Si numbers es una matriz de números, la siguiente línea en Ruby:

numbers.map{|x| x + 5}

es el equivalente de la siguiente línea en Python:

map(lambda x: x + 5, numbers)

Para más detalles, ver aquí o aquí.

Una alternativa para el mapa que también funciona para más de 2 matrices:

def dot(*arrays)
  arrays.transpose.map {|vals| yield vals}
end

dot(weights,data) {|a,b| a*b} 

# OR, if you have a third array

dot(weights,data,offsets) {|a,b,c| (a*b)+c}

Esto también podría agregarse a Array:

class Array
  def dot
    self.transpose.map{|vals| yield vals}
  end
end

[weights,data].dot {|a,b| a*b}

#OR

[weights,data,offsets].dot {|a,b,c| (a*b)+c}
weights = [1,2,3]
data    = [10,50,30]

require 'matrix'
Vector[*weights].inner_product Vector[*data] # => 200 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top