Tensorflow学习笔记:多项式拟合

#coding:utf-8
'''
多项式
'''

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

# 定义模型
def model(X,w):
    terms = []
    for i in range(num_coeffs):
        term = tf.multiply(w[i],tf.pow(X,i))
        terms.append(term)
    return tf.add_n(terms)

# 学习速率
learning_rate = 0.01

# 迭代次数
training_epochs = 40

# 生成模拟数据
train_X = np.linspace(-1,1,101)

# 设置多项式维度
num_coeffs = 6
train_Y_coeffs = [1,2,3,4,5,6]
train_Y = 0
for i in range(num_coeffs):
    train_Y += train_Y_coeffs[i] * np.power(train_X,i)

# 生成带有噪音的数据
train_Y += np.random.randn(*train_X.shape) * 1.5

# 定义训练参数
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

w = tf.Variable([0.] * num_coeffs,name='parameters')
y_model = model(X,w)

cost = (tf.pow(Y-y_model,2))
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

sess = tf.Session()
init_op = tf.global_variables_initializer()

sess.run(init_op)

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

w_val = sess.run(w)
print(w_val) 

sess.close()

plt.scatter(train_X, train_Y)

train_Y2 = 0
for i in range(num_coeffs):
    train_Y2 += w_val[i] * np.power(train_X, i)
plt.plot(train_X, train_Y2, 'r') 
plt.show() 

231432_X3PO_106657.png

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

视觉&物联智能

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值