tensorflow入门

一元线性回归

import tensorflow as tf
import numpy as np

learning_rate = 0.02#学习率
training_epochs = 100#跌打次数

train_X = np.array([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
                         7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y = np.array([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
                         2.827,3.465,1.65,2.904,2.42,2.94,1.3])
n_samples = train_X.shape[0]

#占位符
X = tf.placeholder("float")
Y = tf.placeholder("float")

#定义变量,更新时会变
W = tf.Variable(np.random.randn(), name="weight")
b = tf.Variable(np.random.randn(), name="bias")

#定义预测值和损失函数
pre = tf.add(tf.multiply(X,W),b)
cost = tf.reduce_sum(tf.pow(pre-Y, 2))/(2*n_samples)

optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)#优化器

init = tf.global_variables_initializer()#初始化所有变量



with tf.Session() as sess:
    sess.run(init)

    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        
        if (epoch+1) % 50 == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))


    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b))
    
    test_X = np.array([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])
    test_Y = np.array([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03])
    testing_cost = sess.run(tf.reduce_sum(tf.pow(pre - Y, 2)) / (2 * test_X.shape[0]),
                        feed_dict={X: test_X, Y: test_Y}) 
    print("Test LOSS=", testing_cost)
    print("Final Loss:", abs(training_cost - testing_cost))
Epoch: 0050 cost= 0.156731546 W= 0.4030323 b= -0.3285281
Epoch: 0100 cost= 0.139268920 W= 0.38494474 b= -0.19669534
Training cost= 0.13926892 W= 0.38494474 b= -0.19669534
Test LOSS= 0.12271086
Final Loss: 0.016558059

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值