tensorflow实例
时间: 2023-06-24 10:08:40 浏览: 76
tensorflow examples
以下是一个使用TensorFlow实现简单线性回归模型的例子:
```python
import tensorflow as tf
import numpy as np
# 创建训练数据
x_train = np.linspace(-1, 1, 101)
y_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33
# 创建占位符,用于输入训练数据
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# 定义模型参数
W = tf.Variable(tf.random_normal([1]), name="weight")
b = tf.Variable(tf.zeros([1]), name="bias")
# 定义模型
Y_pred = tf.add(tf.multiply(X, W), b)
# 定义损失函数
cost = tf.reduce_mean(tf.square(Y_pred - Y))
# 设置优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
# 初始化变量
init = tf.global_variables_initializer()
# 开始训练
with tf.Session() as sess:
sess.run(init)
for epoch in range(50):
for x, y in zip(x_train, y_train):
sess.run(optimizer, feed_dict={X: x, Y: y})
# 每训练10次输出一次损失函数的值
if (epoch + 1) % 10 == 0:
c = sess.run(cost, feed_dict={X: x_train, Y: y_train})
print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(c), \
"W=", sess.run(W), "b=", sess.run(b))
# 训练结束,输出最终的模型参数
print("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={X: x_train, Y: y_train})
print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b))
```
以上代码实现了一个简单的线性回归模型,其中使用了TensorFlow的占位符、变量、优化器等常用功能。在训练过程中,通过反复迭代来最小化损失函数,并输出当前模型参数的值。最终,模型会输出最优的W和b值,以及训练的代价。
阅读全文