Linear Regression by tensorflow

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import tensorflow as tf
import numpy as np
x_data=np.random.rand(100).astype(np.float32)
y_data=x_data*0.1+0.3
weights=tf.Variable(tf.random_uniform([1],-1,1))#difine the weights,the range of weights is (-1,1) and the dim is 1
biases=tf.Variable(tf.zeros([1]))#

y=x_data*weights+biases

Loss=tf.reduce_mean(tf.square(y-y_data))#difine the loss

optimizor=tf.train.GradientDescentOptimizer(0.5)#define the optimizor,the learnning rate is 0.5

train=optimizor.minimize(Loss)

init=tf.initialize_all_variables() #it is very important to initialize

sess=tf.Session()

sess.run(init)

for step in range(201):
    sess.run(train)
    if step%20==0:
        print(step,sess.run(weights),sess.run(biases))
(0, array([0.4592144], dtype=float32), array([0.16408798], dtype=float32))
(20, array([0.20675611], dtype=float32), array([0.25004813], dtype=float32))
(40, array([0.13285665], dtype=float32), array([0.28462616], dtype=float32))
(60, array([0.11011239], dtype=float32), array([0.29526836], dtype=float32))
(80, array([0.10311233], dtype=float32), array([0.29854372], dtype=float32))
(100, array([0.10095789], dtype=float32), array([0.2995518], dtype=float32))
(120, array([0.10029479], dtype=float32), array([0.2998621], dtype=float32))
(140, array([0.10009072], dtype=float32), array([0.29995757], dtype=float32))
(160, array([0.10002792], dtype=float32), array([0.29998696], dtype=float32))
(180, array([0.10000859], dtype=float32), array([0.299996], dtype=float32))
(200, array([0.10000265], dtype=float32), array([0.29999876], dtype=float32))

猜你喜欢

转载自blog.csdn.net/elite666/article/details/80641924