- Neural Network Programming with TensorFlow
- Manpreet Singh Ghotra Rajdeep Dua
- 367字
- 2021-07-02 15:17:08
Solving linear equations
TensorFlow can solve a series of linear equations using the solve operation. Let's first explain this without using the library and later use the solve function.
A linear equation is represented as follows:
ax + b = yy - ax = b
y - ax = b
y/b - a/b(x) = 1
Our job is to find the values for a and b in the preceding equation, given our observed points. First, create the matrix points. The first column represents x values, while the second column represents y values.
Consider that X is the input matrix and A is the parameters that we need to learn; we set up a system like AX=B, therefore, .
The following example, with code, shows how to solve the linear equation:
3x+2y = 15
4x−y = 10
import tensorflow as tf
# equation 1
x1 = tf.constant(3, dtype=tf.float32)
y1 = tf.constant(2, dtype=tf.float32)
point1 = tf.stack([x1, y1])
# equation 2
x2 = tf.constant(4, dtype=tf.float32)
y2 = tf.constant(-1, dtype=tf.float32)
point2 = tf.stack([x2, y2])
# solve for AX=C
X = tf.transpose(tf.stack([point1, point2]))
C = tf.ones((1,2), dtype=tf.float32)
A = tf.matmul(C, tf.matrix_inverse(X))
with tf.Session() as sess:
X = sess.run(X)
print(X)
A = sess.run(A)
print(A)
b = 1 / A[0][1]
a = -b * A[0][0]
print("Hence Linear Equation is: y = {a}x + {b}".format(a=a, b=b))
The output of the listing is shown as follows:
[[ 3. 4.][ 2. -1.]]
[[ 0.27272728 0.09090909]]
Hence Linear Equation is: y = -2.9999999999999996x + 10.999999672174463
The canonical equation for a circle is x2+y2+dx+ey+f=0; to solve this for the parameters d, e, and f, we use TensorFlow's solve operation as follows:
# canonical circle equation
# x2+y2+dx+ey+f = 0
# dx+ey+f=−(x2+y2) ==> AX = B
# we have to solve for d, e, f
points = tf.constant([[2,1], [0,5], [-1,2]], dtype=tf.float64)
X = tf.constant([[2,1,1], [0,5,1], [-1,2,1]], dtype=tf.float64)
B = -tf.constant([[5], [25], [5]], dtype=tf.float64)
A = tf.matrix_solve(X,B)
with tf.Session() as sess:
result = sess.run(A)
D, E, F = result.flatten()
print("Hence Circle Equation is: x**2 + y**2 + {D}x + {E}y + {F} = 0".format(**locals()))
The output of the listing is shown in the following code:
Hence Circle Equation is: x**2 + y**2 + -2.0x + -6.0y + 5.0 = 0