1.需求描述
在做仿真模拟实验的时候,我们总是因为缺少数据,所以我们假设产生的数据服从
y
=
w
∗
x
+
b
y=w*x+b
y=w∗x+b
为了方便,我们设计的X包含X1,X2,以及一个Y:
Y
=
0.2
∗
X
1
+
0.3
∗
X
+
1.4
Y=0.2*X1+0.3*X+1.4
Y=0.2∗X1+0.3∗X+1.4
2.导入模块
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(1)
## 2.1 定义一个上面的描述的函数
def linear_fun(x1,x2,w1 = 0.2,w2 = 0.3,b=3.5):
return w1 * x1 + w2 * x2 + b
## 2.2 生成噪声数据
def generate_data(linear_fun,N):
# 均匀分布
x1 = np.random.uniform(-1,1,N)
x2 = np.random.uniform(-1,1,N)
y = linear_fun(x1,x2)
# 添加噪声数据
epsilon = np.random.normal(0,0.1,N)
y += epsilon
return x1,x2,y
# 测试
x1,x2,y = generate_data(linear_fun,5)
print(x1,'\n',x2,'\n',y)
[ 0.44583039 -0.64690193 0.72393312 -0.9604498 0.72047399]
[ 0.11780762 -0.19355906 0.51749386 0.433858 0.97465235]
[3.54870163 3.3253896 3.9760763 3.53472137 4.00779541]
3.数据保存
df = pd.DataFrame({'x1':x1,'x2':x2,'y':y})
df.to_excel('仿真模拟数据.xlsx')