【TensorFlow】第二课数据拟合的一般步骤

来源:互联网 发布:linux查看重启日志 编辑:程序博客网 时间:2024/06/08 13:44

一,简单的线性回归

1.数据准备

实际的数据大家可以通过pandas等package读入。

此处的数据是自己造的。

%matplotlib inlineimport numpy as npimport tensorflow as tfimport matplotlib.pyplot as pltplt.rcParams["figure.figsize"] = (14,8)n_observations = 100xs = np.linspace(-3, 3, n_observations)ys = np.sin(xs) + np.random.uniform(-0.5, 0.5, n_observations)plt.scatter(xs, ys)plt.show()

2.准备好placeholder

X = tf.placeholder(tf.float32, name='X')Y = tf.placeholder(tf.float32, name='Y')

3.初始化参数/权重

W = tf.Variable(tf.random_normal([1]), name='weight')b = tf.Variable(tf.random_normal([1]), name='bias')

4.计算预测结果

Y_pred = tf.add(tf.multiply(X, W), b)

5.计算损失函数值

loss = tf.square(Y - Y_pred, name='loss')

6.初始化optimizer

learning_rate = 0.01optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

7.指定迭代次数,并在session里执行graph


n_samples = xs.shape[0]with tf.Session() as sess:# 记得初始化所有变量sess.run(tf.global_variables_initializer()) writer = tf.summary.FileWriter('./graphs/linear_reg', sess.graph)# 训练模型for i in range(50):total_loss = 0for x, y in zip(xs, ys):# 通过feed_dic把数据灌进去_, l = sess.run([optimizer, loss], feed_dict={X: x, Y:y}) total_loss += lif i%5 ==0:print('Epoch {0}: {1}'.format(i, total_loss/n_samples))# 关闭writerwriter.close() # 取出w和b的值W, b = sess.run([W, b]) 


plt.plot(xs, ys, 'bo', label='Real data')plt.plot(xs, xs * W + b, 'r', label='Predicted data')plt.legend()plt.show()

拟合结果如下图所示:








原创粉丝点击