Day01、入門—TensorFlow
教程源于:莫煩python:https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/
import tensorflow as tf
import numpy as np
# ###-------1怠益、---------最初例子-----------------------------
# #創(chuàng)建數(shù)據(jù)
# x_data = np.random.rand(100).astype(np.float32)
# y_data = x_data*0.1 + 0.3
#
# #用 tf.Variable 來創(chuàng)建描述 y 的參數(shù),把 y_data = x_data*0.1 + 0.3
# #想象成 y=Weights * x + biases, 然后神經(jīng)網(wǎng)絡也就是學著把
# # Weights 變成 0.1, biases 變成 0.3.
#
# #搭建模型
# 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)
#
# #訓練
# #先初始化所有之前定義的Variable
# init = tf.global_variables_initializer()
#
# #創(chuàng)建回話Session
# sess = tf.Session()
# sess.run()
#
# for step in range(201):
# sess.run(train)
# if step % 20 == 0:
# print(step,sess.run(Weights),sess.run(biases))
# ###-------2剔蹋、-----簡單應用----session會話控制--------------
#
# import tensorflow as tf
#
# matrix1 = tf.constant([[4,3]])
# print("matrix1:",matrix1)
#
# matrix2 = tf.constant([[2],[2]])
# print("matrix2:",matrix2)
#
# product = tf.matmul(matrix1,matrix2)
# print(product)
#
# #因為 product 不是直接計算的步驟, 所以我們會要使用 Session 來激活 product 并得到計算結果.
# #有兩種形式使用會話控制 Session
# #方法1:
# sess = tf.Session()
# result = sess.run(product)
# print(result) #[[14]]
# sess.close()
# #方法2:
# with tf.Session as sess:
# result2 = sess.run(product)
# print(result2) #[[14]]
# ###------3、------簡單應用----Variable--------------
#
# import tensorflow as tf
#
# state = tf.Variable(0,name='counter')
#
# #定義常量 one
# one = tf.constant(1)
#
# #定義加法步驟(注:此步并沒有直接計算)
# new_value = tf.add(state, one)
#
# #將State 更新成new_value
# update = tf.assign(state,new_value)
#
# #如果你在 Tensorflow 中設定了變量坯苹,那么初始化變量是最重要的!!
# #所以定義了變量以后, 一定要定義 init = tf.initialize_all_variables() .
# #init = tf.initialize_all_variables() #tf馬上要廢棄這種寫法
# init = tf.global_variables_initializer() #替換成這樣寫就好
#
# #使用session
# with tf.Session() as sess:
# sess.run(init)
# for step in range(3):
# print("before:",sess.run(state))
# sess.run(update)
# print("after",sess.run(state))
# ###輸出結果:
# # before: 0
# # after 1
# # before: 1
# # after 2
# # before: 2
# # after 3
# ###------4、------簡單應用----Variable--------------
#
# import tensorflow as tf
#
# #在 Tensorflow 中需要定義 placeholder 的 type 濒募,一般為 float32 形式
# input1 = tf.placeholder(tf.float32)
# input2 = tf.placeholder(tf.float32)
#
# #mul = multiply 是將input1和input2 做乘法運算,并輸出為 output
# output = tf.multiply(input1,input2)
#
# #同理圾结,傳值工作交給sess.run(), 需要傳入的值放在了feed_dict={} 并一一對應每一個 input.
# #placeholder 與 feed_dict={} 是綁定在一起出現(xiàn)的瑰剃。
# with tf.Session() as sess:
# print(sess.run(output,feed_dict={input1:[7.],input2:[2.]})) #[14.]
# print(sess.run(output, feed_dict={input1: [1,3], input2: [2,4]})) #[ 2. 12.]
# print(sess.run(output, feed_dict={input1: 3, input2: 2})) #6.0
###------5、----------add_layer()--------------
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
##!!!!!!!!!!!!!!!!!!add_layer()!!!!!!!!!!!!!!!!!!!!!!!!!!
#定義添加神經(jīng)層的函數(shù)def add_layer(),它有四個參數(shù):輸入值筝野、輸入的大小晌姚、輸出的大小和激勵函數(shù),我們設定默認的激勵函數(shù)是None
def add_layer(inputs,in_size,out_size,activation_function=None):
#神經(jīng)層里常見的參數(shù)通常有weights歇竟、biases和激勵函數(shù)挥唠。
Weights = tf.Variable(tf.random_normal([in_size,out_size]))
biases = tf.Variable(tf.zeros([1,out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs,Weights) + biases #定義Wx_plus_b, 即神經(jīng)網(wǎng)絡未激活的值
#當activation_function——激勵函數(shù)為None時,輸出就是當前的預測值——Wx_plus_b焕议,
#不為None時宝磨,就把Wx_plus_b傳到activation_function()函數(shù)中得到輸出。
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
##!!!!!!!!!!!!!!!!!!!!!!!!!構建神經(jīng)網(wǎng)絡!!!!!!!!!!!!!!!!!!!!!!
#導入數(shù)據(jù)
#構建所需數(shù)據(jù)盅安,這里的x_data和y_data并不是嚴格的一元二次函數(shù)的關系唤锉,因為我們多加了一個noise,這樣看起來會更像真實情況
x_data = np.linspace(-1,1,300,dtype = np.float32)[:,np.newaxis]
noise = np.random.normal(0,0.05,x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise
#利用占位符定義我們所需的神經(jīng)網(wǎng)絡的輸入。
#tf.placeholder()就是代表占位符别瞭,這里的None代表無論輸入有多少都可以窿祥,因為輸入只有一個特征,所以這里是1蝙寨。
xs = tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])
#搭建網(wǎng)絡
l1 = add_layer(xs,1,10,activation_function=tf.nn.relu)
prediction = add_layer(l1,10,1,activation_function=None)
#計算預測值prediction和真實值的誤差壁肋,對二者差的平方求和再取平均。
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss) #以0.1的效率來最小化誤差loss
#使用變量時籽慢,都要對變量進行初始化浸遗,必不可少
init = tf.global_variables_initializer()
#定義Session,并用Session來執(zhí)行init初始化步驟
sess = tf.Session()
sess.run(init)
#訓練
#讓機器學習1000次箱亿,機器學習的內(nèi)容是train_step跛锌,用Session來run每一次training的數(shù)據(jù),逐步提升神經(jīng)網(wǎng)絡的預測準確率
for i in range(1000):
#training
sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
if i % 50 == 0:
try:
ax.lines.remove(lines[0])
except Exception:
pass
#每50步輸出一下機器學習的誤差
print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
prediction_value = sess.run(prediction,feed_dict={xs:x_data})
# 可視化
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data)
# plt.ion()
lines = ax.plot(x_data,prediction_value,'r-',lw=5)
plt.pause(0.1)
plt.show()