用tensorflow写一个房价线性回归代码
时间: 2024-05-05 09:17:11 浏览: 153
以下是一个使用 TensorFlow 实现的房价线性回归模型的代码示例:
```python
import tensorflow as tf
import numpy as np
# 定义训练数据
train_X = np.array([[1.0, 2.0, 3.0, 4.0, 5.0],
[2.0, 4.0, 6.0, 8.0, 10.0],
[3.0, 6.0, 9.0, 12.0, 15.0],
[4.0, 8.0, 12.0, 16.0, 20.0],
[5.0, 10.0, 15.0, 20.0, 25.0]])
train_Y = np.array([10.0, 20.0, 30.0, 40.0, 50.0])
# 定义模型参数
learning_rate = 0.01
training_epochs = 100
display_step = 20
# 定义 TensorFlow 计算图
X = tf.placeholder(tf.float32, [None, 5], name="X")
Y = tf.placeholder(tf.float32, [None], name="Y")
W = tf.Variable(tf.zeros([5, 1]), name="W")
b = tf.Variable(tf.zeros([1]), name="b")
pred = tf.matmul(X, W) + b
# 定义损失函数和优化器
cost = tf.reduce_mean(tf.square(pred - Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# 初始化 TensorFlow 变量
init = tf.global_variables_initializer()
# 在 TensorFlow 会话中运行计算图
with tf.Session() as sess:
sess.run(init)
# 训练模型
for epoch in range(training_epochs):
_, c = sess.run([optimizer, cost], feed_dict={X: train_X, Y: train_Y})
if (epoch + 1) % display_step == 0:
print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(c))
print("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b))
# 使用模型进行预测
test_X = np.array([[6.0, 7.0, 8.0, 9.0, 10.0]])
print("Predicted house price:", sess.run(pred, feed_dict={X: test_X}))
```
该代码定义了一个训练数据集 `train_X` 和 `train_Y`,其中 `train_X` 是一个 5 行 5 列的矩阵,每行代表一个房屋的 5 个特征值,`train_Y` 是一个包含 5 个房屋价格的向量。通过 TensorFlow 定义了一个线性回归模型,使用梯度下降算法进行训练,并使用该模型进行预测。在训练过程中,每隔一定次数输出训练损失。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)