python Tensoflow的线性回归示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Tensoflow的线性回归示例相关的知识,希望对你有一定的参考价值。

import numpy as np
import tensorflow as tf

# Model parameters
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)
# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
# training data
x_train = [1,2,3,4]
y_train = [0,-1,-2,-3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
  sess.run(train, {x:x_train, y:y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x:x_train, y:y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))

以上是关于python Tensoflow的线性回归示例的主要内容,如果未能解决你的问题,请参考以下文章

何时不使用线性回归?

维度问题线性回归 Python scikit 学习

股票实战--线性回归

将非线性单变量回归拟合到 Python 中的时间序列数据

在 Python 中使用简单线性回归包的不同结果:statsmodel.api vs sklearn

R线性回归模型构建示例