本文共 1645 字,大约阅读时间需要 5 分钟。
#!/usr/bin/env python3# -*- coding: utf-8 -*-import numpy as np import matplotlib.pyplot as plt #使用 matplotlib 可视化数据x_train = np.linspace(-1, 1, 101) #输入值为 -1 到 1 之间的 101 个均匀间隔的数字y_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33 #生成输出值,与输入值成正比并附加噪声plt.scatter(x_train, y_train) #使用 matplotlib 的函数绘制散点图plt.show()
#!/usr/bin/env python3# -*- coding: utf-8 -*-import tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt# 定义学习算法使用的一些常数,称为超参数# learning_rate是每次进行训练时在最陡的梯度方向上所采取的「步」长;它也被称作学习率(learning rate)。learning_rate = 0.01training_epochs = 100 # 初始化线性模拟数据x_train = np.linspace(-1, 1, 101)y_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33# 将输入和输出节点设置为占位符,而真实数值将传入 x_train 和 y_trainX = tf.placeholder("float")Y = tf.placeholder("float")# 将回归模型定义为 y=w*xdef model(X, w): return tf.multiply(X, w)# 设置权重变量w = tf.Variable(0.0, name="weights")#成本函数的一个简单样例是每个数据点所代表的实际输出与预测输出之间偏差的绝对值总和(实际结果到最佳拟合曲线的垂直投影)。#成本函数往往是实际输出和预测输出之间的方差,因为差值有时是负数;这也称为最小二乘法。# 定义成本函数y_model = model(X, w)#tf.square()是对每一个元素求平方cost = tf.square(Y - y_model)# 有了线性模型、成本函数和数据,我们就可以开始执行梯度下降从而最小化代价函数# 定义在学习算法的每次迭代中将被调用的操作train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)# 设置会话并初始化所有变量sess = tf.Session()init = tf.global_variables_initializer()sess.run(init)# 多次循环遍历数据集for epoch in range(training_epochs): for (x, y) in zip(x_train, y_train): # 循环遍历数据集中的每个数据 sess.run(train_op, feed_dict={ X: x, Y: y}) # 更新模型参数以尝试最小化成本函数w_val = sess.run(w) # 得到最终参数值sess.close() # 关闭会话# 绘制原始数据plt.scatter(x_train, y_train)# 绘制最佳拟合直线y_learned = x_train*w_valplt.plot(x_train, y_learned, 'r')plt.show()
转载地址:http://vgvab.baihongyu.com/