Tensorflow实现多层感知函数逼近
生活随笔
收集整理的這篇文章主要介紹了
Tensorflow实现多层感知函数逼近
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#1:導入需要用到的模塊
import tensorflow as tf
import tensorflow.contrib.layers as layers
from sklearn import datasets
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
import seaborn as sns'''
只有一個隱藏層的多層前饋網絡足以逼近任何函數
同時還可以保證很高的精度和令人滿意的效果
使用MLP(多層感知機進行函數逼近,預測波士頓房價)
'''#2:加載數據集并創建Pandas數據幀來分析數據:boston = datasets.load_boston()
df = pd.DataFrame(boston.data,columns=boston.feature_names)
df['target'] = boston.target#3:了解一些數據的細節
df.describe()#4:三個參數RM,PTRATIO和LSTAT在幅度上輸出之間具有大于0.5的相關性
# 將數據集分解為訓練數據集和測試數據集。使用MinMaxScaler來規劃數據集
#由于神經網絡使用Sigmoid激活函數(Sigmoid的輸出只能在0-1之間)
#所以必須對目標值進行歸一化x_train,x_test,y_train,y_test = train_test_split(df[['RM','LSTAT','PTRATIO']],df[['target']],test_size=0.3,random_state=0)
#歸一化數據
X_train = MinMaxScaler().fit_transform(x_train)
X_test = MinMaxScaler().fit_transform(x_test)
Y_train = MinMaxScaler().fit_transform(y_train)
Y_test = MinMaxScaler().fit_transform(y_test)#5:定義常量和超參數
m = len(X_train)
n = 3 #特征的數量
n_hidden = 20 #隱藏層神經元的數量
#超參數
batch_size = 200
eta = 0.01 #學習率
max_epoch = 1000 #最大迭代數#6:創建一個單隱藏層的多層感知機模型
def multilayer_perceptron(x):fc1 = layers.fully_connected(x,n_hidden,activation_fn=tf.nn.relu,scope='fc1')out = layers.fully_connected(fc1,1,activation_fn=tf.sigmoid,scope='out')return out
#7:聲明訓練數據的占位符并定義損失和優化器
x = tf.compat.v1.placeholder(tf.float32,name='X',shape=[m,n])
y = tf.compat.v1.placeholder(tf.float32,name='Y')
y_hat = multilayer_perceptron(x)
correct_prediction = tf.square(y-y_hat)
mse = tf.reduce_mean(tf.cast(correct_prediction,'float'))
train = tf.train.AdamOptimizer(learning_rate=eta).minimize(mse)#8:執行計算圖
init = tf.global_variables_initializer()with tf.compat.v1.Session() as sess:sess.run(init)writer = tf.summary.FileWriter('g3',sess.graph)# 訓練模型100次迭代for i in range(max_epoch):_, l,p = sess.run([train,mse,y_hat],feed_dict={x:X_train,y:Y_train})if i %100 ==0:print('Epoch {0}:Loss {1}'.format(i,l))print("Training Done")print('Optimization Finished!')
#測試模型correct_prediction = tf.square(y-y_hat)
#計算準確度accuracy = tf.reduce_mean(tf.cast(correct_prediction,'float'))print('Mean ERROR:',accuracy.eval({x:X_train,y:Y_train}))plt.scatter(Y_train,p)writer.close()
總結
以上是生活随笔為你收集整理的Tensorflow实现多层感知函数逼近的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Selenium简介以及selenium
- 下一篇: 常用的寄存器( bss段的作用)