autodiff
2023-02-15 本文已影响0人
Lonelyroots
autodiff
importtensorflowastf
importnumpyasnp
fromsklearn.datasetsimportfetch_california_housing
fromsklearn.preprocessingimportStandardScaler
#前面的代码执行的不错,但是它需要数学上通过损失函数MSE来求导梯度
#在线性回归的例子中,这样是可以的,看起来通过数学公式去求解不难
#但是如果是深度学习,我们很难这样去做,会比较头疼,会很容易出错
#幸运的是,TensorFlow提供的autodiff特性可以自动的并有效的计算梯度为我们
#reverse-modeautodiff
n_epochs=10000
learning_rate=0.001
housing=fetch_california_housing()
m,n=housing.data.shape
housing_data_plus_bias=np.c_[np.ones((m,1)),housing.data]
#可以使用TensorFlow或者Numpy或者sklearn的StandardScaler去进行归一化
scaler=StandardScaler().fit(housing_data_plus_bias)
scaled_housing_data_plus_bias=scaler.transform(housing_data_plus_bias)
X=tf.constant(scaled_housing_data_plus_bias,dtype=tf.float32,name='X')
y=tf.constant(housing.target.reshape(-1,1),dtype=tf.float32,name='y')
#random_uniform函数创建图里一个节点包含随机数值,给定它的形状和取值范围,就像numpy里面rand()函数
theta=tf.Variable(tf.random_uniform([n+1,1],-1.0,1.0),name='theta')
y_pred=tf.matmul(X,theta,name="predictions")
error=y_pred-y
mse=tf.reduce_mean(tf.square(error),name="mse")
#梯度的公式:(y_pred-y)*xj
#gradients=2/m*tf.matmul(tf.transpose(X),error)
gradients=tf.gradients(mse,[theta])[0]
#赋值函数对于BGD来说就是theta_new=theta-(learning_rate*gradients)
training_op=tf.assign(theta,theta-learning_rate*gradients)
init=tf.global_variables_initializer()
withtf.Session()assess:
sess.run(init)
forepochinrange(n_epochs):
ifepoch%100==0:
print("Epoch",epoch,"MSE=",mse.eval())
sess.run(training_op)
best_theta=theta.eval()
print(best_theta)
文章到这里就结束了!希望大家能多多支持Python(系列)!六个月带大家学会Python,私聊我,可以问关于本文章的问题!以后每天都会发布新的文章,喜欢的点点关注!一个陪伴你学习Python的新青年!不管多忙都会更新下去,一起加油!
Editor:Lonelyroots