(编辑:jimmy 日期: 2024/11/15 浏览:2)
本文使用TensorFlow实现最简单的线性回归模型,供大家参考,具体内容如下
线性拟合y=2.7x+0.6,代码如下:
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt n = 201 # x点数 X = np.linspace(-1, 1, n)[:,np.newaxis] # 等差数列构建X,[:,np.newaxis]这个是shape,这一行构建了一个n维列向量([1,n]的矩阵) noise = np.random.normal(0, 0.5, X.shape) # 噪声值,与X同型 Y = X*2.7 + 0.6 + noise # Y xs = tf.placeholder(tf.float32, [None, 1]) # 下面两行是占位符tf.placeholder(dtype, shape) ys = tf.placeholder(tf.float32, [None, 1]) w = tf.Variable(1.1) # 这两行是weight变量,bias变量,括号中是初始值 b = tf.Variable(0.2) ypredict = tf.add(w*xs,b) # 根据 w, b 产生的预测值 loss = tf.reduce_sum(tf.pow(ys-ypredict,2.0))/n # 损失函数,tf.reduce_sum()按某一维度元素求和,默认为按列 optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(loss) # 梯度下降优化器,0.01学习率,最小化losss init = tf.global_variables_initializer() # 初始化所有变量 with tf.Session() as sess: sess.run(init) # 运行初始化 for i in range (1000): # 迭代1000次 sess.run(optimizer, feed_dict = {xs:X,ys:Y}) # 运行优化器,梯度下降用到loss,计算loss需要xs, ys所以后面需要feed_dict if i%50==0: # 每隔50次迭代输出w,b,loss # 下面sess.run(w),sess.run(b)里面没有feed_dict是因为打印w,b不需要xs,ys,而打印loss需要 print ("w:",sess.run(w),"\t b:", sess.run(b), "\t loss:", sess.run(loss,feed_dict={xs:X,ys:Y})) plt.plot(X,X*sess.run(w)+sess.run(b)) # 运行迭代之后绘制拟合曲线,这需要在sess里面运行是因为要用到w,b plt.scatter(X,Y) # 绘制被拟合数据(散点) plt.show() # 绘制图像
结果:
w: 1.1106868 b: 0.2086223 loss: 1.2682248 w: 1.5626049 b: 0.4772562 loss: 0.7024503 w: 1.8849733 b: 0.57508457 loss: 0.47280872 w: 2.1149294 b: 0.61071056 loss: 0.36368176 w: 2.278966 b: 0.6236845 loss: 0.30917725 w: 2.3959787 b: 0.6284093 loss: 0.2815788 w: 2.4794474 b: 0.6301298 loss: 0.26755357 w: 2.5389886 b: 0.63075644 loss: 0.26041925 w: 2.5814607 b: 0.6309848 loss: 0.2567894 w: 2.611758 b: 0.6310678 loss: 0.25494233 w: 2.6333694 b: 0.6310981 loss: 0.25400248 w: 2.6487865 b: 0.631109 loss: 0.2535242 w: 2.659784 b: 0.63111293 loss: 0.25328085 w: 2.6676288 b: 0.6311139 loss: 0.25315702 w: 2.6732242 b: 0.6311139 loss: 0.25309405 w: 2.6772156 b: 0.6311139 loss: 0.25306198 w: 2.6800632 b: 0.6311139 loss: 0.25304565 w: 2.6820953 b: 0.6311139 loss: 0.25303733 w: 2.6835444 b: 0.6311139 loss: 0.25303313 w: 2.684578 b: 0.6311139 loss: 0.25303096
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。