线性回归问题—解析法实现一元线性回归
步骤1. 导入库
import tensorflow as tf
import pandas as pd
步骤2. 导入数据集,查看数据集
dataset = pd.read_csv('./lianxi1.csv')
dataset.head()
| x | y |
---|
0 | 32.502345 | 31.707006 |
---|
1 | 53.426804 | 68.777596 |
---|
2 | 61.530358 | 62.562382 |
---|
3 | 47.475640 | 71.546632 |
---|
4 | 59.813208 | 87.230925 |
---|
dataset.shape
(100, 2)
dataset.info
<bound method DataFrame.info of x y
0 32.502345 31.707006
1 53.426804 68.777596
2 61.530358 62.562382
3 47.475640 71.546632
4 59.813208 87.230925
.. ... ...
95 50.030174 81.536991
96 49.239765 72.111832
97 50.039576 85.232007
98 48.149859 66.224958
99 25.128485 53.454394
[100 rows x 2 columns]>
dataset.describe()
| x | y |
---|
count | 100.000000 | 100.000000 |
---|
mean | 48.958341 | 72.735051 |
---|
std | 9.746379 | 16.658187 |
---|
min | 25.128485 | 31.707006 |
---|
25% | 41.526164 | 60.788586 |
---|
50% | 49.634970 | 72.179542 |
---|
75% | 56.762631 | 83.215080 |
---|
max | 70.346076 | 118.591217 |
---|
步骤3. 提取特征和标签
feature_column = ['x']
label_column = ['y']
feature = dataset[feature_column]
label = dataset[label_column]
feature.head()
| x |
---|
0 | 32.502345 |
---|
1 | 53.426804 |
---|
2 | 61.530358 |
---|
3 | 47.475640 |
---|
4 | 59.813208 |
---|
X = feature.values
Y = label.values
X.shape
(100, 1)
步骤4. 计算w,b
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f2075dd287ef933e206f83abd8ac8548.png)
meanX = tf.reduce_mean(X)
meanY = tf.reduce_mean(Y)
sumXY = tf.reduce_sum((X-meanX)*(Y-meanY))
sumX = tf.reduce_sum((X-meanX)**2)
w = sumXY/sumX
b = meanY - w*meanX
print('w=',w.numpy())
print('w=',b.numpy())
w= 1.3224310226878684
w= 7.991020985734451