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