4、python简单线性回归代码案例(完整)_python 实现一个简单的线性回归案例

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# @File : 自实现一个线性回归.py

# @Author: 赵路仓

# @Date : 2020/4/12

# @Desc :

# @Contact : 398333404@qq.com

import os

import tensorflow as tf

def linear_regression():

"""

自实现一个线性回归

:return:

"""

# 命名空间

with tf.variable_scope("prepared_data"):

# 准备数据

x = tf.random_normal(shape=[100, 1], name="Feature")

y_true = tf.matmul(x, [[0.08]]) + 0.7

# x = tf.constant([[1.0], [2.0], [3.0]])

# y_true = tf.constant([[0.78], [0.86], [0.94]])

with tf.variable_scope("create_model"):

# 2.构造函数

# 定义模型变量参数

weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1], name="Weights"))

bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1], name="Bias"))

y_predit = tf.matmul(x, weights) + bias

with tf.variable_scope("loss_function"):

# 3.构造损失函数

error = tf.reduce_mean(tf.square(y_predit - y_true))

with tf.variable_scope("optimizer"):

# 4.优化损失

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)

# 收集变量

tf.summary.scalar("error", error)

tf.summary.histogram("weights", weights)

tf.summary.histogram("bias", bias)

# 合并变量

merged = tf.summary.merge_all()

# 创建saver对象

saver = tf.train.Saver()

# 显式的初始化变量

init = tf.global_variables_initializer()

# 开启会话

with tf.Session() as sess:

# 初始化变量

sess.run(init)

# 创建事件文件

file_writer = tf.summary.FileWriter("E:/tmp/linear", graph=sess.graph)

# print(x.eval())

# print(y_true.eval())

# 查看初始化变量模型参数之后的值

print("训练前模型参数为:权重%f,偏置%f" % (weights.eval(), bias.eval()))

# 开始训练

for i in range(1000):

sess.run(optimizer)

print("第%d次参数为:权重%f,偏置%f,损失%f" % (i + 1, weights.eval(), bias.eval(), error.eval()))

# 运行合并变量操作

summary = sess.run(merged)

# 将每次迭代后的变量写入事件

file_writer.add_summary(summary, i)

# 保存模型

if i == 999:

saver.save(sess, "./tmp/model/my_linear.ckpt")

# # 加载模型

# if os.path.exists("./tmp/model/checkpoint"):

# saver.restore(sess, "./tmp/model/my_linear.ckpt")

print("参数为:权重%f,偏置%f,损失%f" % (weights.eval(), bias.eval(), error.eval()))

pre = [[0.5]]

prediction = tf.matmul(pre, weights) + bias

sess.run(prediction)

print(prediction.eval())

return None

if __name__ == "__main__":

linear_regression()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是一个简单Python线性回归代码案例: ```python import numpy as np import matplotlib.pyplot as plt # 定义数据 x = np.array([1, 2, 3, 4, 5]) y = np.array([3, 5, 7, 9, 11]) # 计算斜率和截距 slope, intercept = np.polyfit(x, y, 1) # 绘制数据和拟合直线 plt.scatter(x, y) plt.plot(x, slope*x + intercept, color='r') plt.show() ``` 这个代码案例中,我们首先定义了一组数据,然后使用`np.polyfit`函数计算出线性回归的斜率和截距。最后,我们使用`matplotlib`库绘制出原始数据和拟合直线的图像。 ### 回答2: Python是一种非常流行的编程语言,它拥有强大的数据分析和处理能力,尤其在机器学习领域中得到广泛的应用。其中,线性回归一个基本但重要的机器学习算法,下面将介绍使用python实现简单线性回归完整代码。 首先,需要导入所需的库,包括pandas、numpy、sklearn、matplotlib等。具体代码如下: ``` import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from matplotlib import pyplot as plt ``` 接下来,读取数据并进行简单的数据预处理。这里假设数据集中只有一个特征和一个目标变量,即只进行一元线性回归。 ``` data = pd.read_csv('data.csv') X = data.iloc[:, 0].values.reshape(-1, 1) # 特征变量 y = data.iloc[:, 1].values.reshape(-1, 1) # 目标变量 ``` 然后,将数据集分为训练集和测试集,一般采用80:20的比例。 ``` from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) ``` 接着,使用sklearn库中的LinearRegression类来拟合线性回归模型。 ``` regressor = LinearRegression() regressor.fit(X_train, y_train) ``` 模型拟合完成后,可以通过绘制散点图和拟合直线来可视化模型的拟合效果。 ``` plt.scatter(X_train, y_train, color='blue') plt.plot(X_train, regressor.predict(X_train), color='red') plt.title('Training set') plt.xlabel('Feature') plt.ylabel('Target') plt.show() ``` 最后,使用测试集来评估模型的性能,并计算相关指标,如R方、均方误差等。 ``` from sklearn.metrics import r2_score, mean_squared_error y_pred = regressor.predict(X_test) print('R2 score: ', r2_score(y_test, y_pred)) print('MSE: ', mean_squared_error(y_test, y_pred)) ``` 完整代码如下所示: ``` import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from matplotlib import pyplot as plt data = pd.read_csv('data.csv') X = data.iloc[:, 0].values.reshape(-1, 1) y = data.iloc[:, 1].values.reshape(-1, 1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) regressor = LinearRegression() regressor.fit(X_train, y_train) plt.scatter(X_train, y_train, color='blue') plt.plot(X_train, regressor.predict(X_train), color='red') plt.title('Training set') plt.xlabel('Feature') plt.ylabel('Target') plt.show() y_pred = regressor.predict(X_test) print('R2 score: ', r2_score(y_test, y_pred)) print('MSE: ', mean_squared_error(y_test, y_pred)) ``` ### 回答3: Python是一种高级编程语言,适用于数据科学和机器学习中的数据分析任务。在数据科学和机器学习领域中,最常见的任务之一就是线性回归简单线性回归是一种建立两个变量之间的数学关系的方法,其中一个变量是自变量,另一个变量是因变量。 下面将介绍一个完整Python程序来实现简单线性回归代码案例。 1. 导入必要的库 我们首先要导入必要的库,如numpy、matplotlib和pandas。numpy和pandas可以用于数据操作和运算,而matplotlib用于数据的可视化。 ```python import numpy as np import matplotlib.pyplot as plt import pandas as pd ``` 2. 读取数据集 在实验之前,我们需要从数据集中读取数据。可以使用pandas中的read_csv函数来读取数据。我们可以利用该函数将数据读取到一个数据框中,使得数据非常容易操作。 ```python dataset = pd.read_csv('studentscores.csv') X = dataset.iloc[ : , : 1 ].values Y = dataset.iloc[ : , 1 ].values ``` 3. 拟合简单线性回归模型 现在,我们可以拟合简单线性回归模型了。可以在scikit-learn库中找到线性回归模型。下面就是利用Scikit-Learn库中的线性回归模型来构建一个简单线性回归模型: ```python from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor = regressor.fit(X, Y) ``` 4. 数据的可视化 现在我们可以将原始数据和拟合的回归线绘制出来。由于该数据集只有一个特征,因此我们可以绘制散点图和回归直线。 ```python plt.scatter(X, Y, color = 'red') plt.plot(X, regressor.predict(X), color = 'blue') plt.title('Student\'s scores vs number of hours studied') plt.xlabel('Number of hours studied') plt.ylabel('Scores') plt.show() ``` 在绘制完成后,我们就可以在图形上看到数据的趋势线,以及预测结果相对于原数据的表现情况。 完整代码如下: ```python import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('studentscores.csv') X = dataset.iloc[ : , : 1 ].values Y = dataset.iloc[ : , 1 ].values from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor = regressor.fit(X,Y) plt.scatter(X , Y, color = 'red') plt.plot(X , regressor.predict(X), color ='blue') plt.title('Student Scores vs Number of Hours Studied') plt.xlabel('Number of Hours Studied') plt.ylabel('Scores') plt.show() ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值