笔记---Tensorflow 搭建自己的神经网络 (莫烦 Py

2019-07-21  本文已影响0人  Shine_Zhang

Tensorflow 搭建自己的神经网络 (莫烦 Python 教程)

1.例子1

Code:

import tensorflow as tf
import numpy as np
# create data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
### create tensorflow sturcture start ###
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))
biases = tf.Variable(tf.zeros([1]))
y = Weights * x_data + biases
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.initialize_all_variables()
### create tensorflow sturcture start ###
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))

Result:

0 [-0.42743844] [0.8432702]
20 [-0.04861213] [0.38219658]
40 [0.06516342] [0.31926793]
60 [0.09183386] [0.30451667]
80 [0.09808574] [0.30105877]
100 [0.09955128] [0.3002482]
120 [0.09989484] [0.3000582]
140 [0.09997535] [0.30001363]
160 [0.09999423] [0.3000032]
180 [0.09999865] [0.30000076]
200 [0.0999997] [0.3000002]

2.Session的用法

Code:

import tensorflow as tf
import numpy as np
#创建矩阵
matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
                       [2]])
#矩阵相乘
product = tf.matmul(matrix1,matrix2) 

# method 1
sess = tf.Session()
print("method1:",sess.run(product))
sess.close()

# method2
with tf.Session() as sess:
    print("method2:",sess.run(product))
    

Result:

method1: [[12]]
method2: [[12]]

3.Variable 变量

Code:

import tensorflow as tf
#创建变量,赋值0,变量名:counter
state = tf.Variable(0,name='counter')
#创建常量
one = tf.constant(1)
#相加
new_value = tf.add(state,one)
#将new_value的值传给state
update = tf.assign(state,new_value)
#初始化变量
init = tf.initialize_all_variables()# must have if define variable

with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

Result:

1
2
3
上一篇下一篇

猜你喜欢

热点阅读