基于TensorFlow的2个机器学习简单应用实例

33 篇文章 4 订阅
13 篇文章 0 订阅

根据数据建立了一个线性模型,并设计了一个损失模型。 在我们的线性模型 y=W×x+b中,不断的改变W和b的值,来找到一个使loss最小的值。使用梯度下降(Gradient Descent)优化算法,通过不断的改变模型中变量的值,来找到最小损失值。

1、实例一

#引入TensorFlow模块
import tensorflow as tf

#创建节点保存W和b,并初始化
W = tf.Variable([0.1],  tf.float32)
b = tf.Variable([-0.1], tf.float32)

#定义节点x,保存输入x数据
x = tf.placeholder(tf.float32)

#定义线性模型
linear_model = W * x + b

#定义节点y,保存输入y数据
y = tf.placeholder(tf.float32)

#定义损失函数
loss = tf.reduce_sum(tf.square(linear_model - y))

#初始化
init = tf.global_variables_initializer()

#定义session
sess = tf.Session()

#训练数据
x_train = [1,2,3,6,8]
y_train = [4.8,8.5,10.4,21.0,25.3]

sess.run(init)

#定义优化器
opti = tf.train.GradientDescentOptimizer(0.001)
train = opti.minimize(loss)

#迭代
for i in range(10000):
    sess.run(train, {x:x_train, y:y_train})

#打印结果
print('W:%s  b:%s  loss:%s' %(sess.run(W), sess.run(b), sess.run(loss, {x:x_train, y:y_train})))

结果如下:

2、实例二

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# Prepare train data
train_X = np.linspace(-1, 1, 100)
train_Y = 2 * train_X + np.random.randn(*train_X.shape) * 0.33 + 10

# Define the model
X = tf.placeholder("float")
Y = tf.placeholder("float")
w = tf.Variable(0.0, name="weight")
b = tf.Variable(0.0, name="bias")
loss = tf.square(Y - X*w - b)
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

# Create session to run
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    epoch = 1
    for i in range(10):
        for (x, y) in zip(train_X, train_Y):
            _, w_value, b_value = sess.run([train_op, w, b],feed_dict={X: x,Y: y})
        print("Epoch: {}, w: {}, b: {}".format(epoch, w_value, b_value))
        epoch += 1


#draw
plt.plot(train_X,train_Y,"+")
plt.plot(train_X,train_X.dot(w_value)+b_value)
plt.show()

结果如下:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值