Q: 来一个从0到100,间隔是5.3的数组:
np.arange(0., 100., 5.3)
#array([ 0. , 5.3, 10.6, 15.9, 21.2, 26.5, 31.8, 37.1, 42.4, 47.7, 53. ,58.3, 63.6, 68.9, 74.2, 79.5, 84.8, 90.1, 95.4])
Q: 来5个全部都是1的数组:
np.full(5, 1.0)
#array([1., 1., 1., 1., 1.])
Q: 来5个全部都是0的数组:
np.zeros(5)
#array([0., 0., 0., 0., 0.])
Q: 数组变matrix怎么搞?
np.arange(0, 10, 1).reshape(2, 5)
#array([[0, 1, 2, 3, 4],
# [5, 6, 7, 8, 9]])
Q: randn咋用?
np.random.randn(5, 2)
#array([[ 0.8644362 , -0.74216502],
# [ 2.26975462, -1.45436567],
# [ 0.04575852, -0.18718385],
# [ 1.53277921, 1.46935877],
# [ 0.15494743, 0.37816252]])
Q: matrix 运算
x = np.arange(0, 6, 1).reshape(2, 3)
y = np.arange(1, 7, 1).reshape(3, 2)
np.dot(x, y)
'''array([[13, 16],
[40, 52]])
'''
np.dot(y, x)
'''array([[ 6, 9, 12],
[12, 19, 26],
[18, 29, 40]])
'''
Q: gradient descent 运算写法:
theta = np.random.randn(2)
x = np.arange(1.0, 10.0, 0.2)
x0 = np.full(len(x), 1.0)
# combine
input_data = np.column_stack([x0, x])
'''
[[1. 0. ]
[1. 0.2]
[1. 0.4]
[1. 0.6]
[1. 0.8]]
'''
target_data = 2 * x + 5 + np.random.randn(m)
alpha = 0.001
sum_m = np.zeros(2)
count = 0
while count < 10000:
count += 1
for i in range(len(x)):
aL_atheta = (np.dot(theta, input_data[i]) - target_data[i]) * input_data[i]
#遍历后,把每个row加起来,最后就是一个1x2vector。分别是[theta0, theta1]
sum_m += aL_atheta
# alpha => learning rate.更新theta的值
theta = theta - alpha*sum_m