创建numpy函数并转换为张量

时间:2018-02-11 18:50:00

标签: python numpy tensorflow numpy-ufunc

我正在尝试使用numpy创建函数,例如f =(x-a1)^ 2 +(y-a2)^ 2 + a3

其中a1,a2,a3是随机生成的数字,x,y是参数。

但我不能使用它,我想找到f(0,0),其中[0,0]是[x,y]和[a1,a2,a3]之前设置,但我的代码不起作用。 然后我想将此函数转换为张量张量张量。这是我的代码,带“##”的字符串不起作用。

import tensorflow as tf
from random import random, seed
import numpy as np


def mypolyval(x, min_point, min_value):
    res = min_value
    for i in range(len(min_point)):
        res += (x[i] - min_point[i]) ** 2
    return res


class FunGen:
    def __init__(self, dim, n):
        self.dim = dim
        self.n = n
        self.functions = []
        self.x = []

    def c2(self):
        seed(10)
        for _ in range(self.n):
            min_point = [random() for _ in range(self.dim)]
            min_value = random()
            f = np.vectorize(mypolyval, excluded=['x'])

            ##print(f(x=np.array([0, 0]), min_point=min_point, min_value=min_value))
            self.functions.append((f, min_point, min_value))
        return self.functions


functions = FunGen(2, 1).c2()
for i in functions:
    print(type(i[0]))
    f=i[0]
   ## print(f(x=[0, 0], min_value=i[1], min_point=i[2]))
    ##a=tf.convert_to_tensor(f,dtype=np.float32)

2 个答案:

答案 0 :(得分:0)

要从numpy函数创建TensorFlow函数,您应该使用tf.py_func

  

包装python函数并将其用作TensorFlow操作。

来自TensorFlow API

def my_func(x):
  # x will be a numpy array with the contents of the placeholder below
  return np.sinh(x)
inp = tf.placeholder(tf.float32)
y = tf.py_func(my_func, [inp], tf.float32)

答案 1 :(得分:0)

问题与张量流无关。这条线

min_point = [random() for _ in range(self.dim)]

创建一个列表,列表没有.size()属性。

你可以使用min_point = np.array([random() for _ in range(self.dim)]))将其变成一个numpy数组,然后.size()就可以了。

或者,如果您想坚持列表,请使用for i in range(len(min_point))来计算列表的长度。

您还需要将min_pointmin_value添加到排除列表中:

from random import random, seed
import numpy as np


def mypolyval(x, min_point, min_value):

    print('x', x)
    print('min_point', min_point)
    print('min_value', min_value)
    res = min_value
    for i in range(len(min_point)):
        res += (x[i] - min_point[i]) ** 2
    return res


class FunGen:
    def __init__(self, dim, n):
        self.dim = dim
        self.n = n
        self.functions = []
        self.x = []

    def c2(self):
        seed(10)
        for _ in range(self.n):
            min_point = [random() for _ in range(self.dim)]
            min_value = random()
            f = np.vectorize(mypolyval, excluded=['x', 'min_point', 'min_value'])
            #print(f(x=[0, 0], min_value=min_value, min_point=min_point))
            self.functions.append((f, min_point, min_value))
        return self.functions


functions = FunGen(2, 1).c2()
for i in functions:
    print(type(i[0]))
    print(i)
    f=i[0]
    print(f(x=[0, 0], min_value=i[2], min_point=i[1]))