tensorflow实现线性回归

import tensorflow as tf
import numpy as np

# 用数据集进行线性回归
def linear_regression():

    # 1、准备数据
    path = r'C:\Users\User_name\Desktop\Con-LSTM\Salary_Data.csv'
    dataset = np.loadtxt(path, skiprows=1, delimiter=',')
    x_train, x_test, y_train, y_test = dataset[:28, 0], dataset[-2:, 0], dataset[:28, 1], dataset[-2:, 1]
    # print(dataset.shape)
    # print(x_train, y_train)

    # 2、构建回归模型
    x_true = tf.cast(tf.reshape(x_train, shape=[28, 1]), dtype=tf.float32)
    y_true = tf.cast(tf.reshape(y_train, shape=[28, 1]), dtype=tf.float32)
    weights = tf.Variable(initial_value=tf.random.normal(shape=[1, 1]))
    bias = tf.Variable(initial_value=tf.random.normal(shape=[1, 1]))
    y_predict = tf.add(tf.matmul(x_true, weights), bias)
    # print(y_predict.shape)
    # print(type(y_predict))

    # 3、构造损失函数
    #      损失用均方误差表示
    loss = tf.reduce_mean(tf.square(y_predict - y_true))

    # 4、优化损失
    #      用梯度下降方法定义优化器
    optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.03).minimize(loss)

    init = tf.compat.v1.global_variables_initializer()
    with tf.compat.v1.Session() as sess:
        sess.run(init)

        for i in range(1000):
            sess.run(optimizer)
        print("model weights:\n", weights.eval())
        print("model bias:\n", bias.eval())
        # # 5、输出测试集准确值和预测值
        print("测试集中的真实值y_test:\n", y_test)
        x_test32 = tf.reshape(tf.cast(x_test, dtype=tf.float32), shape=[2, 1])
        y_test32 = tf.cast(tf.reshape(y_test, shape=[2, 1]), dtype=tf.float32)
        y_test_predict = tf.add(tf.matmul(x_test32, weights), bias)
        loss_test = tf.sqrt(tf.reduce_mean(tf.square(y_test_predict - y_test32)))
        sess.run(loss_test)
        print("loss: \n", loss_test.eval())
        print("对测试集的预测值y_test_predict: \n", y_test_predict.eval().tolist())
    return None

# 用已知函数进行线性回归
# def linear_regression():
#     # 1、准备数据
#     x = tf.random_normal(shape=[100, 1])
#     y_true = tf.matmul(x, [[0.8]]) + 1.2
#     # 2、创建回归模型
#     weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
#     bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
#     y_predict = tf.add(tf.matmul(x, weights), bias)
#     # 3、构造损失函数
#     error = tf.reduce_mean(tf.square(y_predict - y_true))
#     # 4、创建优化器,优化损失
#     optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.01).minimize(error)
#
#     init = tf.compat.v1.global_variables_initializer()
#     with tf.compat.v1.Session() as sess:
#         sess.run(init)
#
#         for i in range(1000):
#             sess.run(optimizer)
#             print("weights = %f\t bias = %f\t error = %f" % (weights.eval(), bias.eval(), error.eval()))
#
#     return None


if __name__ == "__main__":
    linear_regression()

数据集下载地址:https://pan.baidu.com/s/1HaBVhEmSaBKBfZVRMww56Q
密码:qlge

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值