python3下tensorflow練習(一)
阿新 • • 發佈:2019-01-05
1.瞭解tensorflow基本架構
2.用梯度下降的方法訓練處模型
3.視覺化樣本資料,視覺化訓練出的模型以及視覺化損失函式
""" Created on Wed May 2 09:40:08 2018 @author: jiangcheng """ import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # create data x_data = np.random.rand(100).astype(np.float32) y_data = x_data*0.1 + 0.3 #打印出準備訓練的樣本 fig = plt.figure() plt.xlabel('X') #設定Y軸標籤 plt.ylabel('Y') plt.scatter(x_data,y_data,c = 'r',marker = 'x') #'o'---圓點,‘s’---方塊 #設定圖示 ,左上角的圖示 plt.legend('x') #顯示所畫的圖 plt.show() ### tensorflow structure 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)#梯度下降,學習速率為0.5 train = optimizer.minimize(loss) init = tf.initialize_all_variables() ### tensorflow structure end ### sess = tf.Session() sess.run(init) # Very important cost=[] for step in range(201): sess.run(train) if step % 20 == 0: # print(step, sess.run(Weights), sess.run(biases)) print("Cost after iteration {}: {}".format(step, np.squeeze(sess.run(loss)))) cost.append(sess.run(loss)) ####訓練出的模型 fig = plt.figure() #設定X軸標籤 plt.xlabel('Xmodel') #設定Y軸標籤 plt.ylabel('Ymodel') #畫散點圖 plt.scatter(x_data,sess.run(y),c = 'y',marker = 'o') #'o'---圓點,‘s’---方塊 #設定圖示 ,左上角的圖示 plt.legend('xmodel') plt.show() ###列印代價 plt.plot(np.squeeze(cost)) #壓縮 plt.ylabel('cost') plt.xlabel('iterations (per 20)') plt.title("Learning rate =" +str( 0.5)) plt.show()
1.訓練的資料視覺化
2.模型視覺化
3.損失函式視覺化