tensorflow入门笔记(一)

Tensorflow实现直线拟合

代码:

#用tensorflow做回归
#用的是tensorflow2版本做直线拟合
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.compat.v1.disable_eager_execution()
rng = np.random
learning_rate = 0.02 #学习率
training_epoch = 10000 #训练步数
display_step = 50 #显示步长
#训练数据
train_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.618,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.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.2,2.827,3.465,1.65,2.904,2.42,2.94,1.3])
n_samples_x = train_X.shape[0]
# n_samples_Y = train_Y.shape[0]
# print("长度分别是{:}和{:}".format(n_samples_x,n_samples_Y))
X = tf.compat.v1.placeholder(tf.float32)
Y = tf.compat.v1.placeholder(tf.float32)
#设置权重和偏执
W = tf.Variable(rng.random(),name= 'Weight')
b = tf.Variable(rng.random(),name= 'bias')
#设置线性回归方程
pred = tf.add(tf.multiply(X,W),b)
#设置均方差
cost = tf.reduce_sum(tf.pow(pred - Y,2))/(2*n_samples_x)
#设置梯度下降的方法
optimiziers = tf.compat.v1.train.GradientDescentOptimizer(learning_rate).minimize(cost)
#初始化所有的变量
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    sess.run(init)
    #灌入所有的训练数据
    for epochs in range(training_epoch):
        for (x,y) in zip(train_X,train_Y):#将列表变成字典
            sess.run(optimiziers,feed_dict={X:x,Y:y}) #开始进行训练模式

        if (epochs + 1)%display_step == 0:
            c = sess.run(cost,feed_dict={X:train_X,Y:train_Y})
            print('epochs:{:},cost:{:.9f},w:{:.3f},b:{:.3f}'.format(epochs,c,sess.run(W),sess.run(b)))

    print("Optimization Finished!")
    train_cost = sess.run(cost,feed_dict={X:train_X,Y:train_Y})
    Ww = sess.run(W)
    Bb = sess.run(b)
    print("Final cost:{:.9f},Final W:{:.3f},Final b:{:.3f}".format(train_cost,Ww,Bb))
    plt.plot(train_X,train_Y,'ro',label = 'Origin data')
    plt.plot(train_X,Ww*train_X+Bb,'b',label = 'Fitted Line')
    plt.legend()
    plt.show()

结果:

Optimization Finished!
Final cost:0.079473563,Final W:0.250,Final b:0.784

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值