這次就用TensorFlow寫個神經(jīng)網(wǎng)絡(luò),這個神經(jīng)網(wǎng)絡(luò)寫的很簡單,就三種層,輸入層--隱藏層----輸出層;
首先導入我們要使用的包
# -*- coding: utf-8 -*-import tensorflow as tfimport matplotlib.pyplot as pltimport numpy as npimport matplotlibfrom sklearn import datasetsfrom matplotlib.font_manager import FontProperties
然后在設(shè)定一下我們畫圖的時候要顯示中文的字體,因為Python自帶的不支持中文的解釋
#設(shè)置中文font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)zhfont1 = matplotlib.font_manager.FontProperties(fname=r'c:\windows\fonts\simsun.ttc')
定義一個會話,因為圖是必須在會話中啟動的
#定義一個圖會話sess=tf.Session()
這里我選用公開的數(shù)據(jù)鶯尾花的數(shù)據(jù)集,這個數(shù)據(jù)集雖然都被大家 玩爛了,不過這個是一個學習代碼,就不計較那么多了;
#鶯尾花數(shù)據(jù)集iris=datasets.load_iris()x_vals=np.array([x[0:3] for x in iris.data])y_vals=np.array([x[3] for x in iris.data])
這里設(shè)置一個隨機種子,為了可以讓大家把結(jié)果復(fù)現(xiàn)出來
#設(shè)置一個種子求結(jié)果seed=211tf.set_random_seed(seed)8np.random.seed(seed)
開始有模有樣的劃分數(shù)據(jù)集了,一個是訓練集,一個是測試集,訓練集占80%,測試集占20%
#劃分測試機和訓練集train_indices=np.random.choice(len(x_vals),round(len(x_vals)*0.8),replace=True)test_indices=np.array(list(set(range(len(x_vals)))-set(train_indices)))x_vals_train=x_vals[train_indices]x_vals_test = x_vals[test_indices]y_vals_train = y_vals[train_indices]y_vals_test = y_vals[test_indices]
在這里我們在將特征進行一個歸一化,也就是將數(shù)值型特征全部都轉(zhuǎn)換為0-1之間的數(shù)值,用特征最大距離作為分母;還有一些其他的標準化方法,有興趣可以了解,這個好處就是能夠讓迭代更加快速,還有就是消除量綱,就是單位之間影響;
使用nan_to_num這個函數(shù)主要是為了消除None值帶來的計算影響
#歸一化函數(shù)def normalize_cols(m): col_max = m.max(axis=0) col_min = m.min(axis=0) return (m - col_min) / (col_max - col_min)#數(shù)據(jù)歸一化并轉(zhuǎn)空集x_vals_train=np.nan_to_num(normalize_cols(x_vals_train))x_vals_test=np.nan_to_num(normalize_cols(x_vals_test))
好了,上面已經(jīng)生成了我們想要的數(shù)據(jù)集;在這里我們在設(shè)置一次訓練的數(shù)據(jù)集多大,一般是選擇2^N倍數(shù),因為是計算機是二進制存儲,這樣就快,這里我就隨意選擇了個25,因為數(shù)據(jù)集比較小,沒什么影響
batch_size=25
在這里定義一下訓練變量Y和X,順便設(shè)置為浮點類型
x_data=tf.placeholder(shape=[None,3],dtype=tf.float32)y_target=tf.placeholder(shape=[None,1],dtype=tf.float32)
在這里我們設(shè)置一下隱藏層連接數(shù)
#設(shè)置隱藏層hidden_layer_nodes=5
開始定義各層的參數(shù)變量,因為輸入變量是三個
#定義各層變量,初始變量為3個A1=tf.Variable(tf.random_normal(shape=[3,hidden_layer_nodes]))b1=tf.Variable(tf.random_normal(shape=[hidden_layer_nodes]))A2=tf.Variable(tf.random_normal(shape=[hidden_layer_nodes,1]))b2=tf.Variable(tf.random_normal(shape=[1]))
這里我們使用relu函數(shù)作為激活函數(shù),以及輸出結(jié)果也使用relu函數(shù)
#定義隱藏層的輸出和輸出層的輸出hidden_output=tf.nn.relu(tf.add(tf.matmul(x_data,A1),b1))final_output = tf.nn.relu(tf.add(tf.matmul(hidden_output, A2),b2))
這里我們在定義一下?lián)p失函數(shù),有用最大似然估計的,這里我們使用均方誤差方式
loss=tf.reduce_mean(tf.square(y_target-final_output))
定義一下參數(shù)的更新方式和學習速率,這里我們使用梯度下降方法更新,下一次我們講解用其他方式更新,和學習速率隨著迭代次數(shù)減少,tfboys就是那么任性
#聲明算法初始變量opt=tf.train.GradientDescentOptimizer(0.005)train_step=opt.minimize(loss)#變量進行初始化init=tf.initialize_all_variables()sess.run(init)
定義兩個list,用來存放在訓練中的測試集和訓練集的誤差
#訓練過程loss_vec=[]test_loss=[]
開始迭代,這里我們設(shè)置迭代次數(shù)為5000
for i in range(5000): #選取batch_size大小的數(shù)據(jù)集 rand_index=np.random.choice(len(x_vals_train),size=batch_size) #選取出數(shù)據(jù)集 rand_x=x_vals_train[rand_index] rand_y=np.transpose([y_vals_train[rand_index]]) #開始訓練步驟 sess.run(train_step,feed_dict={x_data:rand_x,y_target:rand_y}) #保存損失結(jié)果 temp_loss=sess.run(loss,feed_dict={x_data:rand_x,y_target:rand_y}) #保存損失函數(shù) loss_vec.append(np.sqrt(temp_loss)) test_temp_loss = sess.run(loss, feed_dict={x_data: x_vals_test, y_target: np.transpose([y_vals_test])}) test_loss.append(np.sqrt(test_temp_loss)) #打印損失函數(shù),沒五十次打印一次 if (i+1)%50==0: print('Generation: ' + str(i + 1) + '. Train_Loss = ' + str(temp_loss)+ '. test_Loss = ' + str(test_temp_loss))
迭代最后結(jié)果為
接下來我們在看看誤差隨著迭代變化的趨勢,下降的還不夠快,這些代碼其實還是很粗糙,太多地方需要優(yōu)化了;下次在寫個優(yōu)化版本的
#畫圖plt.plot(loss_vec, '', label='訓練 Loss')plt.plot(test_loss, 'r--', label='測試 Loss')plt.title('均方誤差分布', fontproperties=font)plt.xlabel('迭代步數(shù)', fontproperties=font)plt.ylabel('Loss')plt.legend(prop=zhfont1)plt.show()
-
神經(jīng)網(wǎng)絡(luò)
+關(guān)注
關(guān)注
42文章
4811瀏覽量
103041 -
深度學習
+關(guān)注
關(guān)注
73文章
5557瀏覽量
122580 -
tensorflow
+關(guān)注
關(guān)注
13文章
330瀏覽量
61071
原文標題:用TensorFlow寫個簡單的神經(jīng)網(wǎng)絡(luò)
文章出處:【微信號:AI_shequ,微信公眾號:人工智能愛好者社區(qū)】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。
發(fā)布評論請先 登錄
TF之CNN:Tensorflow構(gòu)建卷積神經(jīng)網(wǎng)絡(luò)CNN的嘻嘻哈哈事之詳細攻略
【PYNQ-Z2試用體驗】神經(jīng)網(wǎng)絡(luò)基礎(chǔ)知識
【案例分享】ART神經(jīng)網(wǎng)絡(luò)與SOM神經(jīng)網(wǎng)絡(luò)
【AI學習】第3篇--人工神經(jīng)網(wǎng)絡(luò)
如何構(gòu)建神經(jīng)網(wǎng)絡(luò)?
如何使用TensorFlow將神經(jīng)網(wǎng)絡(luò)模型部署到移動或嵌入式設(shè)備上
如何使用Numpy搭建神經(jīng)網(wǎng)絡(luò)

谷歌正式發(fā)布TensorFlow 圖神經(jīng)網(wǎng)絡(luò)
用Python從頭實現(xiàn)一個神經(jīng)網(wǎng)絡(luò)來理解神經(jīng)網(wǎng)絡(luò)的原理1

用Python從頭實現(xiàn)一個神經(jīng)網(wǎng)絡(luò)來理解神經(jīng)網(wǎng)絡(luò)的原理2

用Python從頭實現(xiàn)一個神經(jīng)網(wǎng)絡(luò)來理解神經(jīng)網(wǎng)絡(luò)的原理3

用Python從頭實現(xiàn)一個神經(jīng)網(wǎng)絡(luò)來理解神經(jīng)網(wǎng)絡(luò)的原理4

評論