机器学习_python_linear-regression_基础知识

1. 一键求偏导

from sympy import *
#作用:导入模块sympy模块下所有函数
#sympy用于:表达式求值求偏导求积分
x, y = symbols('x, y')
z = x ** 2 + y ** 2 + x * y + 2
print(z)

x2 + x*y + y2 + 2

dx = diff(z, x)  # 对x求偏导
dy = diff(z, y)  # 对y求偏导
list1 = [dx,dy]
print(dx)
print(dy)
print(list1[0])

2x + y
x + 2
y
2*x + y

result = list1[0].subs([(x,1), (y,2)])  # 用数值分别对x、y进行替换
print(result)

4

2.生成随机数

samples=10;
x1234 = np.zeros((3,samples))
for i in range(3):
    for j in range(samples):
        x1234[i][j]=random.uniform(0-i*5,10+i*10);
print(x1234)

[[ 0.6368847 0.21968948 4.11102096 9.41313659 6.77233311 7.45444663
2.53787123 6.68336218 8.36420599 1.04561676]
[13.92519355 11.8178671 16.04400894 1.56813507 3.4082561 0.43102163
13.18596095 -4.03980048 16.02815584 9.38436655]
[29.40857603 -2.15801778 -3.52800737 25.18005422 -2.18444001 -5.50439369
2.55979245 6.1651788 27.25273547 1.6267535 ]]

3.矩阵点乘

a=np.array([[1],[2],[3]])
b=np.array([[1,1,1],[2,2,2],[3,3,3]])
print(b.dot(a))

[[ 6]
[12]
[18]]

sum(b.dot(a))

array([36])

sum(b.dot(a)) == 36

array([True])

sum(sum(b.dot(a))) == 36

True

4.多元线性回归函数

from sympy import *
import numpy as np
w1,w2,w3,x1,x2,x3,y=symbols('w1,w2,w3,x1,x2,x3,y'
w=[w1,w2,w3]
x=[x1,x2,x3]
y=np.dot(w,x)+exp(5)

(w1x1 + w2x2 + w3*x3 - 2 + exp(5))**2

diff(z,w[0]).subs([(x1,1),(x2,2),(x3,3),(w[1],2),(w[2],3)]

你可能感兴趣的:(python,机器学习,linear,regression,Gradient,descent,python基础,python培训)