Why do we use the name 'x' in the tensorflow-serving example? - mnist

I'm reading the basic tutorial of tensorflow serving. From mnist_saved_model.py I can't uderstand something:
serialized_tf_example = tf.placeholder(tf.string, name='tf_example')
feature_configs = {'x': tf.FixedLenFeature(shape=[784], dtype=tf.float32),}
tf_example = tf.parse_example(serialized_tf_example, feature_configs)
I don't understand why we use the name 'x' in feature_configs.

It's using a linear equation, where convention has it that y as the output and x as the input.
y = x * w + b
x = input
w = weights
b = bias
y = output

Related

Translating a mixed-integer programming formulation to Scipy

I would like to solve the above formulation in Scipy and solve it using milp(). For a given graph (V, E), f_ij and x_ij are the decision variables. f_ij is the flow from i to j (it can be continuous). x_ij is the number of vehicles from i to j. p is the price. X is the available number vehicles in a region. c is the capacity.
I have difficulty in translating the formulation to Scipy milp code. I would appreciate it if anyone could give me some pointers.
What I have done:
The code for equation (1):
f_obj = [p[i] for i in Edge]
x_obj = [0]*len(Edge)
obj = f_obj + v_obj
Integrality:
f_cont = [0 for i in Edge] # continous
x_int = [1]*len(Edge) # integer
integrality = f_cont + x_int
Equation (2):
def constraints(self):
b = []
A = []
const = [0]*len(Edge) # for f_ij
for i in v: # for x_ij
for e in Edge:
if e[0] == i:
const.append(1)
else:
const.append(0)
A.append(const)
b.append(self.accInit[i])
const = [0]*len(Edge) # for f_ij
return A, b
Equation (4):
[(0, demand[e]) for e in Edge]
I'm going to do some wild guessing, given how much you've left open to interpretation. Let's assume that
this is a maximisation problem, since the minimisation problem is trivial
Expression (1) is actually the maximisation objective function, though you failed to write it as such
p and d are floating-point vectors
X is an integer vector
c is a floating-point scalar
the graph edges, since you haven't described them at all, do not matter for problem setup
The variable names are not well-chosen and hide what they actually contain. I demonstrate potential replacements.
import numpy as np
from numpy.random._generator import Generator
from scipy.optimize import milp, Bounds, LinearConstraint
import scipy.sparse
from numpy.random import default_rng
rand: Generator = default_rng(seed=0)
N = 20
price = rand.uniform(low=0, high=10, size=N) # p
demand = rand.uniform(low=0, high=10, size=N) # d
availability = rand.integers(low=0, high=10, size=N) # X aka. accInit
capacity = rand.uniform(low=0, high=10) # c
c = np.zeros(2*N) # f and x
c[:N] = -price # (1) f maximized with coefficients of 'p'
# x not optimized
CONTINUOUS = 0
INTEGER = 1
integrality = np.empty_like(c, dtype=int)
integrality[:N] = CONTINUOUS # f
integrality[N:] = INTEGER # x
upper = np.empty_like(c)
upper[:N] = demand # (4) f
upper[N:] = availability # (2) x
eye_N = scipy.sparse.eye(N)
A = scipy.sparse.hstack((-eye_N, capacity*eye_N)) # (3) 0 <= -f + cx
result = milp(
c=c, integrality=integrality,
bounds=Bounds(lb=np.zeros_like(c), ub=upper),
constraints=LinearConstraint(lb=np.zeros(N), A=A),
)
print(result.message)
flow = result.x[:N]
vehicles = result.x[N:].astype(int)

Circulant embedding in python

I'm pretty new with Python. I've been trying to write a python script for Alg 12 in attached image, but keep getting the below error..could some one please assist?Code Error :
def circ(x,n):
t = np.arange(0,n,1)
g = np.exp(-10*t/n)*np.cos(-10*math.pi*t/n) #Given covariance function
e = np.arange(n-1,0,-1)
g_rev = np.array(np.exp(-10*e/n)*np.cos(-10*math.pi*e/n))
s = np.hstack((0,g_rev))
gamma = np.concatenate((g,s))
zero = np.zeros((2*n-len(x)))
x_x = np.hstack((x,zero))
z = fft(np.conjugate(x_x))/2*n
lamb = fft(np.conjugate(gamma))
z_z = np.dot(lamb,z)
zz = fft(np.conjugate(z_z))
return z[:n+1]
## example##
n=6
x=np.array([1,1,1]) #initial guess vector
circ(x,n)
Will also appreciate feedback/tips on how to simplify my code?
Alg 12

how to define the numerical value for objective in gurobi

I am using gurobi and in my object I want to maximize difference between two variables
X1 - X2
But it is not important which variable is bigger so I want to use numerical value of this difference:
|X1 - X2|
How can I define this type of objective in gurobi.
Blow is a semi code of an implementation that I want to do:
m = Model("mip1")
Edges = tuplelist([(1,2),(1,3),(3,4),(3,5),(3,6),(5,6),(6,7),
(8,9),(9,10),(11,12),(12,10),(12,13),(14,10),
])
x = m.addVars(Edges, lb=0.0, ub=1.0, name = "x")
m.setObjectiveN(quicksum(x[w,s] for w,s in Edges),0)
-------my second variables and objective----
y = m.addVars(2, vtype=GRB.BINARY, name="y")
y[0] = quicksum(x.select(1,'*'))
y[1] = quicksum(x.select(8,'*'))
m.setObjectiveN(|y[0]-y[1]|,1)
m.optimize()
Gurobi only accepts absolute values in the constraints, so you could do it like this:
# Define two helper variables
z = m.addVar(name="z")
h = m.addVar(name="h")
m.addConstr(h == y[0]-y[1]) # h = y[0]-y[1]
m.addConstr(z == abs_(h)) # z == |h| == | y[0] - y[1] |
m.setObjectiveN(z, 1) # Maximize z = |h| = |y[0]-y[1]|
where _abs() is a general constraint.

Better way to solve simultaneous linear equations programmatically in Python

I have the following code that solves simultaneous linear equations by starting with the first equation and finding y when x=0, then putting that y into the second equation and finding x, then putting that x back into the first equation etc...
Obviously, this has the potential to reach infinity, so if it reaches +-inf then it swaps the order of the equations so the spiral/ladder goes the other way.
This seems to work, tho I'm not such a good mathematician that I can prove it will always work beyond a hunch, and of course some lines never meet (I know how to use matrices and linear algebra to check straight off whether they will never meet, but I'm not so interested in that atm).
Is there a better way to 'spiral' in on the answer? I'm not interested in using math functions or numpy for the whole solution - I want to be able to code the solution. I don't mind using libraries to improve the performance, for instance using some sort of statistical method.
This may be a very naive question from either a coding or maths point of view, but if so I'd like to know why!
My code is as follows:
# A python program to solve 2d simultaneous equations
# by iterating over coefficients in spirals
import numpy as np
def Input(coeff_or_constant, var, lower, upper):
val = int(input("Let the {} {} be a number between {} and {}: ".format(coeff_or_constant, var, lower, upper)))
if val >= lower and val <= upper :
return val
else:
print("Invalid input")
exit(0)
def Equation(equation_array):
a = Input("coefficient", "a", 0, 10)
b = Input("coefficient", "b", 0, 10)
c = Input("constant", "c", 0, 10)
equation_list = [a, b, c]
equation_array.append(equation_list)
return equation_array
def Stringify_Equations(equation_array):
A = str(equation_array[0][0])
B = str(equation_array[0][1])
C = str(equation_array[0][2])
D = str(equation_array[1][0])
E = str(equation_array[1][1])
F = str(equation_array[1][2])
eq1 = str(A + "y = " + B + "x + " + C)
eq2 = str(D + "y = " + E + "x + " + F)
print(eq1)
print(eq2)
def Spiral(equation_array):
a = equation_array[0][0]
b = equation_array[0][1]
c = equation_array[0][2]
d = equation_array[1][0]
e = equation_array[1][1]
f = equation_array[1][2]
# start at y when x = 0
x = 0
infinity_flag = False
count = 0
coords = []
coords.append([0, 0])
coords.append([1, 1])
# solve equation 2 for x when y = START
while not (coords[0][0] == coords[1][0]):
try:
y = ( ( b * x ) + c ) / a
except:
y = 0
print(y)
try:
x = ( ( d * y ) - f ) / e
except:
x = 0
if x >= 100000 or x <= -100000:
count = count + 1
if count >= 100000:
print("It\'s looking like these linear equations don\'t intersect!")
break
print(x)
new_coords = [x, y]
coords.append(new_coords)
coords.pop(0)
if not ((x == float("inf") or x == float("-inf")) and (y == float("inf") or y == float("-inf"))):
pass
else:
infinity_flag if False else True
if infinity_flag == False:
# if the spiral is divergent this switches the equations around so it converges
# the infinity_flag is to check if both spirals returned infinity meaning the lines do not intersect
# I think this would mostly work for linear equations, but for other kinds of equations it might not
x = 0
a = equation_array[1][0]
b = equation_array[1][1]
c = equation_array[1][2]
d = equation_array[0][0]
e = equation_array[0][1]
f = equation_array[0][2]
infinity_flag = False
else:
print("These linear equations do not intersect")
break
y = round(y, 3)
x = round(x, 3)
print(x, y)
equation_array = []
print("Specify coefficients a and b, and a constant c for equation 1")
equations = Equation(equation_array)
print("Specify coefficients a and b, and a constant c for equation 1")
equations = Equation(equation_array)
print(equation_array)
Stringify_Equations(equation_array)
Spiral(equation_array)

Fit implementation

Hello I am trying to fit a psf to an image. The background should be aproximated by lower order polynomials. If I just take a constant it works fine:
def fitter(image, trueImage,psf,intensity):
p0 = [intensity]
p0.append(np.amin(trueImage)*4**2)
meritFun = lambda p: np.ravel(image-(p[0]*psf+p[1]))
p = least_squares(meritFun,p0,method='trf')
Now I have the issue of how to define the x and y's for my polynomials:
#Does not work!
def fitter(image, trueImage,psf,intensity):
p0 = [intensity]
p0.append(np.amin(trueImage)*4**2)
p0.append(1)
p0.append(1) #some clever initial guess
meritFun = lambda p: np.ravel(image-(p[0]*psf+p[1]+p[2]*x+p[3]*y))
p = least_squares(meritFun,p0,method='trf')
x and y are obviuosly the indices i, j of my image array, but how do I tell that my fit routine?
As Paul Panzer mentioned in the comments, one way of solving this is by using np.ogrid:
def fitter(image, trueImage,psf,intensity):
x = np.ogrid[:image.shape[0]]
y = np.ogrid[:image.shape[1]]
p0 = [intensity]
p0.append(np.amin(trueImage)*4**2)
p0.append(0)
p0.append(0)
meritFun = lambda p: np.ravel(image-(p[0]*psf+p[1]+p[2]*x+p[3]*y))
p = least_squares(meritFun,p0,method='trf')

Resources