官术网_书友最值得收藏!

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
主站蜘蛛池模板: 和硕县| 兴仁县| 博白县| 新建县| 南江县| 东海县| 蒲城县| 廊坊市| 图们市| 昌乐县| 普格县| 义乌市| 项城市| 星子县| 乌拉特中旗| 遂宁市| 甘肃省| 德江县| 洱源县| 德格县| 沁阳市| 丹阳市| 西和县| 宝兴县| 彭泽县| 河北省| 乐业县| 和硕县| 汝南县| 泾源县| 青冈县| 西昌市| 宁城县| 澄迈县| 静海县| 米易县| 富裕县| 都匀市| 灵石县| 鹤壁市| 湘潭市|