tensorflow49 《面向机器智能的TensorFlow实战》笔记-04-01 线性回归

# 《面向机器智能的Tensor Flow实战》04 机器学习基础
# win10 Tensorflow-gpu1.1.0 python3.5.3
# CUDA v8.0 cudnn-8.0-windows10-x64-v5.1
# 原书代码(tensorflow0.8):https://github.com/backstopmedia/tensorflowbook
# tensorflow不同版本api变化:https://github.com/tensorflow/tensorflow/releases
# filename:tfmi04.01.py # 线性回归

import tensorflow as tf

W = tf.Variable(tf.zeros([2, 1]), name="weights")
b = tf.Variable(0., name="bias")

def inference(X):
    return tf.matmul(X, W) + b

def loss(X, Y):
    Y_predicted = inference(X)
    return tf.reduce_sum(tf.squared_difference(Y, Y_predicted))

def inputs():
    # Data from http://people.sc.fsu.edu/~jburkardt/datasets/regression/x09.txt
    weight_age = [[84, 46], [73, 20], [65, 52], [70, 30], [76, 57], [69, 25], [63, 28], [72, 36], [79, 57], [75, 44], [27, 24], [89, 31], [65, 52], [57, 23], [59, 60], [69, 48], [60, 34], [79, 51], [75, 50], [82, 34], [59, 46], [67, 23], [85, 37], [55, 40], [63, 30]]
    blood_fat_content = [354, 190, 405, 263, 451, 302, 288, 385, 402, 365, 209, 290, 346, 254, 395, 434, 220, 374, 308, 220, 311, 181, 274, 303, 244]

    return tf.to_float(weight_age), tf.to_float(blood_fat_content)

def train(total_loss):
    learning_rate = 0.0000001
    return tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)

def evaluate(sess, X, Y):
    print("inference([[80., 25.]]):", sess.run(inference([[80., 25.]])))
    print("inference([[65., 25.]]):", sess.run(inference([[65., 25.]])))

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    X, Y = inputs()
    total_loss = loss(X, Y)
    train_op = train(total_loss)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)

    training_steps = 1000
    for step in range(training_steps):
        sess.run([train_op])
        if step % 100 == 0:
            print("loss: ", sess.run([total_loss]))

    evaluate(sess, X, Y)

    coord.request_stop()
    coord.join(threads)
    sess.close()
'''
loss:  [7608773.0]
loss:  [5341925.0]
loss:  [5339993.0]
loss:  [5338747.0]
loss:  [5337539.0]
loss:  [5336333.5]
loss:  [5335129.5]
loss:  [5333926.0]
loss:  [5332724.5]
loss:  [5331523.0]
inference([[80., 25.]]): [[ 320.64968872]]
inference([[65., 25.]]): [[ 267.78182983]]
'''
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值