numpy生成随机数据实例
一、总结
一句话总结:
A、用np的随机数函数:有正有负:np.random.randn(3,3) #三行三列正态分布随机数据
B、y3 = 0.89*x + 1.47 + 0.2*np.random.randn(100):注意x有多少维,随机数就应该是多少,比如x是100维,随机数也是100维
1、生成 y = 0.89x + 1.47 的随机数据?
x = np.linspace(-1,1,100)
y3 = 0.89*x + 1.47 + 0.2*np.random.randn(100) # x是n为数据,随机数也整成n维数据,这样方便一一相加
2、如下代码生成y = 0.89x + 1.47随机数据的问题?
|||-begin
x = np.linspace(-1,1,100)
y3 = 0.89*x + 1.47 + 0.2*np.random.randn(1)
|||-end
导致每个y加的随机数一样,没达到随机数的目的,可以变成y3 = 0.89*x + 1.47 + 0.2*np.random.randn(100)
二、numpy生成随机数据实例
博客对应课程的视频位置:
import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1,1,100) # print(x)
In [15]:
# 设置散点图y数据
y = [] for i in range(len(x)): yy = 0.89*x[i] + 1.47 + 0.2*np.random.randn(1) # print(yy) y.append(yy) # print(np.array(y)) # 这样做太笨了 # 这里不行,因为10*np.random.randn(1) 固定了,导致每一个x都加了一样的10*np.random.randn(1)
In [45]:
y3 = 0.89*x + 1.47 + 0.2*np.random.randn(100) y3
Out[45]:
In [2]:
y = 0.89*x + 1.47 + 0.2*np.random.randn(100) y
Out[2]:
In [11]:
# for i in range(100):
# print(np.random.randn(1))
In [3]:
# 设置直线数据
y2 = 0.89*x + 1.47
In [4]:
plt.scatter(x,y) # yy = 0.89*x[i] + 1.47 plt.plot(x,y2,c='r') plt.show()
In [5]:
# 随机生成直线的x和y
random_w = np.random.randn(120) random_b = np.random.randn(120) #print(random_x) #print(random_y)
In [7]:
# 让直线变动,动态生成图
from matplotlib import animation from matplotlib import pylab %pylab fig,ax=plt.subplots() # print(fig,ax) line,=ax.plot(x,y2) def animate(i): # line.set_ydata((0.89+i)*x + 1.47) # line.set_ydata((0.89+0.5*i)*x + 1.47+0.3*i) line.set_ydata((random_w[i])*x + random_b[i]) # print(i) return line, def init(): line.set_ydata(y2) return line, ani=animation.FuncAnimation(fig=fig,func=animate,frames=100,init_func=init,interval=200,blit=False) ani.save('test.gif', writer='imagemagick', fps=30) plt.show()
In [ ]: