机器学习——线性回归

概念

对于监督学习,给出一个方程的确切数字,比如在物理学领域,我们需要根据温度和湿度的历史数据,来预测未来的湿度和温度,我们把这类要得到确切数值的问题成为回归分析。

损失函数

线性回归首先需要选择一个误差函数(损失函数cost function)还函数的值,表征模型对于问题的合适程度。

实例

__author__ = 'ding'
'''
线性回归  单变量线性回归
'''
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

# 在(-1,1)之间随机产生101个点连接成一条直线
trX = np.linspace(-1, 1, 101)
# 在直线附近给出随机偏置的点
trY = 2 * trX + np.random.randn(*trX.shape) * 0.4 + 0.2
plt.figure()
plt.scatter(trX, trY)
plt.plot(trX, .2 + 2 * trX)
plt.show()

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

# 定义Model域
with tf.name_scope('Model'):
    def model(X, w, b):
        return tf.multiply(X, w) + b


    w = tf.Variable(-1.0, name='w')
    b = tf.Variable(-2.0, name='b')
    y_model = model(X, w, b)

# 定义CostFunction
with tf.name_scope('CostFunction'):
    cost = tf.pow(Y - y_model, 2)

# 定义优化函数 初始为0.05
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost)


# tf.summary 能够保存训练过程以及参数分布图并在tensorboard显示
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    merged = tf.summary.merge_all()
    cost_op = tf.summary.scalar('loss', cost)
    tf.train.write_graph(sess.graph, './file', 'graph.pbtxt')
    writer = tf.summary.FileWriter('./file', sess.graph)
    for i in range(100):
        for x, y in zip(trX, trY):
            sess.run(train_op, feed_dict={X: x, Y: y})
            summary_str = sess.run(cost_op, feed_dict={X: x, Y: y})
            writer.add_summary(summary_str, i)
        b_tmp = b.eval(sess)
        w_tmp = w.eval(sess)
        plt.plot(trX, b_tmp + w_tmp * trX)
    print(sess.run(w))
    print(sess.run(b))

    plt.scatter(trX, trY)
    plt.plot(trX, sess.run(b) + trX * sess.run(w))
    plt.show()

定义的随机点

这里写图片描述

计算之后

这里写图片描述

此处使用TensorBoard来观测loss值的改变

这里写图片描述

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值