Tensorflow course (1) — linear model

Time:2020-11-11

install

pip3 install tensorflow

introduce

import tensorflow as tf

Execute options

with tf.compat.v1.Session() as session:
    session.run([...])
    #Execute initialization variables
    session.run(init)
    #Feed assignment
    print(session.run(iMul, feed_dict={input2: [7.0], input3: [3.0]}))

Constants and variables

#Declare constants
m1 = tf.compat.v1.constant([[3, 3]])
#Declare variables
var = tf.Variable([1, 2])
#Initialization variables
init = tf.compat.v1.global_variables_initializer()
#Variable assignment
update = tf.compat.v1.assign(counter, new_value)
#Place holder declaration variable
input = tf.compat.v1.placeholder(tf.float32)

Realization of y = ax + B linear model

#Linear model construction
tf.compat.v1.disable_eager_execution()
x_data = np.random.rand(100)
y_data = x_data * 0.1 + 0.2
k = tf.compat.v1.Variable(0.)
b = tf.compat.v1.Variable(0.)
y = k * x_data + b
#Quadratic cost function
loss = tf.compat.v1.reduce_mean(tf.square(y_data - y))
#Define gradient descent training optimizer
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.2)
#Minimizing cost function
train = optimizer.minimize(loss)
#Initialization variables
init = tf.compat.v1.global_variables_initializer()
#Define session
with tf.compat.v1.Session() as session:
    #Execute initialization variables
    session.run(init)
    #Fitting training
    for step in range(201):
        session.run(train)
        if step % 20 == 0:
            print(step, session.run([k, b]))

Operation results

0 [0.052299168, 0.09965591]
20 [0.10233624, 0.1987706]
40 [0.10136684, 0.19928078]
60 [0.10079966, 0.19957922]
80 [0.10046784, 0.19975384]
100 [0.100273706, 0.19985598]
120 [0.10016012, 0.19991575]
140 [0.10009368, 0.19995071]
160 [0.1000548, 0.19997117]
180 [0.10003207, 0.19998313]
200 [0.10001877, 0.19999012]

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint

Recommended Today

Can’t you tell a pile from a fool? This article tells you the best way to open heap in Java collection

In the “Java collection framework” in the last article, there is still one big problem that has not been mentioned, that is, priority queue, heap. What is heap? Heap is actually a special kind of queue priority queue. The ordinary queue game rule is very simple: first in first out; but this kind of priority […]