torch
This commit is contained in:
parent
3b4dbb4dcd
commit
62daef8fb0
|
@ -11,6 +11,7 @@ print(y)
|
|||
# 过滤不符合条件的元素 从列表中选择符合条件的元素组成新的列表
|
||||
print('过滤不符合条件的元素 从列表中选择符合条件的元素组成新的列表'.center(50,'*'))
|
||||
x = [-1,-4,6,7.5,-2.3,9,-11]
|
||||
|
||||
y = [i for i in x if i>0]
|
||||
print(y)
|
||||
|
||||
|
@ -20,6 +21,30 @@ x = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
|
|||
print("[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]: ",x)
|
||||
|
||||
|
||||
import numpy as np
|
||||
x1 = [[x] for x in range(3)]
|
||||
print("x1 = [[x] for x in range(3)] ",x1)
|
||||
x2 = [x for x in range(3)]
|
||||
print("[x2= x for x in range(3)] ",x2)
|
||||
x3 = [np.random.randn(ch1) for ch1 in [4]]
|
||||
print("x3 = ",x3)
|
||||
x4 = [np.random.randn(ch1) for ch1 in [4,1,5]]
|
||||
print("x4 = ",x4)
|
||||
x5 = np.random.random((4,1))
|
||||
print("x5 = ",x5)
|
||||
np.random.seed(1)
|
||||
x6 = [np.random.randn(ch1,ch2) for ch1,ch2 in zip([4],[1])]
|
||||
print("x6 = ",x6)
|
||||
|
||||
w7 = [np.random.randn(ch1) for ch1 in ([4,2])]
|
||||
print("w7 = ",w7)
|
||||
# 注意: ch1 的列要与 ch2 行相同
|
||||
|
||||
w8 = [np.random.randn(ch1, ch2) for ch1, ch2 in zip([2,3], [3,1])]
|
||||
print("w8 = ",w8)
|
||||
w8 = [np.random.randn(ch1, ch2) for ch1, ch2 in zip([2,3], [3,1])]
|
||||
print("w8 = ",w8)
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
# https://blog.csdn.net/zjuxsl/article/details/77104382
|
||||
# 一、lambda函数也叫匿名函数,即,函数没有具体的名称。先来看一个最简单例子:
|
||||
|
||||
def f(x):
|
||||
return x**2
|
||||
print(f(4))
|
||||
|
@ -6,18 +8,19 @@ print(f(4))
|
|||
g = lambda x : x**2
|
||||
print (g(4))
|
||||
|
||||
# lambda语句中,冒号前是参数,可以有多个,用逗号隔开,冒号右边的返回值。lambda语句构建的其实是一个函数对象
|
||||
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
|
||||
print (filter(lambda x: x % 3 == 0, foo))
|
||||
# lambda语句中,冒号前是参数,可以有多个,用逗号隔开,冒号右边的返回值。
|
||||
# lambda语句构建的其实是一个函数对象
|
||||
from functools import reduce
|
||||
reduce(lambda x,y:x+y, [1,2,3]) #6
|
||||
reduce(lambda x,y:x * y, [1,2,4]) #8
|
||||
reduce(lambda x,y: x and y, [True,False,True]) #False
|
||||
|
||||
def f(x, y):
|
||||
return x + y
|
||||
reduce(lambda x, y: f(x, y), [1, 2, 3]) # 6
|
||||
|
||||
|
||||
|
||||
|
||||
# 二、lambda和普通的函数相比,就是省去了函数名称而已,同时这样的匿名函数,又不能共享在别的地方调用。
|
||||
#
|
||||
# 其实说的没错,lambda在Python这种动态的语言中确实没有起到什么惊天动地的作用,因为有很多别的方法能够代替lambda。
|
||||
#
|
||||
# 1. 使用Python写一些执行脚本时,使用lambda可以省去定义函数的过程,让代码更加精简。
|
||||
#
|
||||
# 2. 对于一些抽象的,不会别的地方再复用的函数,有时候给函数起个名字也是个难题,使用lambda不需要考虑命名的问题。
|
||||
#
|
||||
# 3. 使用lambda在某些时候让代码更容易理解。
|
||||
|
||||
|
||||
|
|
|
@ -1,4 +1,13 @@
|
|||
# reduce() 函数会对参数序列中元素进行累积。
|
||||
from functools import reduce
|
||||
def f(x, y):
|
||||
return x + y
|
||||
reduce(f, [1, 2, 3]) # 6
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
lst=[1,2,3,4]
|
||||
print(reduce(lambda x,y: x*y+1, lst))
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
class Spring(object):
|
||||
#season 为类的属性
|
||||
season = "the spring of class"
|
||||
print(Spring.__dict__)
|
||||
print(Spring.__dict__['season'])
|
||||
print("Spring.__dict__:",Spring.__dict__)
|
||||
print("Spring.__dict__['season'] ",Spring.__dict__['season'])
|
||||
# 实例属性的__dict__是空的,因为season是属于类属性
|
||||
s= Spring()
|
||||
print(s.__dict__)
|
||||
print("s.__dict__ ",s.__dict__)
|
|
@ -26,6 +26,11 @@ class Hero(Person):
|
|||
person = Person()
|
||||
print ('Person.__dict__: ', Person.__dict__)
|
||||
print ('person.__dict__: ', person.__dict__)
|
||||
# person.age = 22
|
||||
person.aaa = 22
|
||||
person.sex = 'girl'
|
||||
print ('person.__dict__: ', person.__dict__)
|
||||
|
||||
hero = Hero()
|
||||
print ('Hero.__dict__: ', Hero.__dict__ )
|
||||
print ('hero.__dict__: ', hero.__dict__)
|
||||
|
|
|
@ -1,138 +0,0 @@
|
|||
# In this notebook, you will simulate a system with of three nuclei AA , BB and CC where AA decays into BB and BB decays into CC . If exposed to a neutron flux nucleus CC can be activated into a nucleus AA .
|
||||
|
||||
import numpy
|
||||
from matplotlib import pyplot as plt
|
||||
import random
|
||||
|
||||
# Implement a function that tells whether a transition has occured,
|
||||
# based on the transition probability and a random number. Use the random number r from random.random()
|
||||
# and use the procedure described in the notes so that the checks can work in a reproducible way.
|
||||
|
||||
def has_transitioned(p):
|
||||
r = random.random()
|
||||
return True if p>r else False
|
||||
|
||||
random.seed(9867)
|
||||
assert [ has_transitioned(0.5) for i in range(10)] == [False, False, True, False, False, False, False, True, False, True]
|
||||
|
||||
def evolveOne(currentState, rules):
|
||||
# YOUR CODE HERE
|
||||
for r in rules:
|
||||
if currentState == r[0]:
|
||||
return r[1] if has_transitioned(r[2]) else r[0]
|
||||
else:
|
||||
continue
|
||||
else:
|
||||
return currentState
|
||||
|
||||
|
||||
# these tests are worth 1 mark
|
||||
alwaysDecayRules = [
|
||||
('A', 'B', 1.0),
|
||||
('B', 'C', 1.0)
|
||||
]
|
||||
assert evolveOne('A', alwaysDecayRules) == 'B'
|
||||
assert evolveOne('B', alwaysDecayRules) == 'C'
|
||||
|
||||
# these tests are worth 2 mark
|
||||
random.seed(112211)
|
||||
testRules = [
|
||||
('A', 'B', 0.33),
|
||||
('B', 'C', 0.75)
|
||||
]
|
||||
assert evolveOne('A', testRules) == 'A'
|
||||
assert evolveOne('A', testRules) == 'A'
|
||||
assert evolveOne('A', testRules) == 'A'
|
||||
assert evolveOne('A', testRules) == 'A'
|
||||
assert evolveOne('A', testRules) == 'B'
|
||||
|
||||
assert evolveOne('B', testRules) == 'B'
|
||||
assert evolveOne('B', testRules) == 'C'
|
||||
assert evolveOne('B', testRules) == 'C'
|
||||
assert evolveOne('B', testRules) == 'C'
|
||||
assert evolveOne('B', testRules) == 'C'
|
||||
|
||||
# with no rules there should be no change
|
||||
assert evolveOne('C', testRules) == 'C'
|
||||
|
||||
# Now implement a function that takes a list of states and transition them according to the rules passed as argument.
|
||||
# This function should return a new vector of states, it should not modify the state passed as an argument!
|
||||
|
||||
|
||||
def evolveMany(states, rules):
|
||||
newState = []
|
||||
# YOUR CODE HERE
|
||||
for s in states:
|
||||
newState.append(evolveOne(s,rules))
|
||||
return newState
|
||||
|
||||
# these tests are worth 1 mark
|
||||
random.seed(112287)
|
||||
testRules = [
|
||||
('A', 'B', 0.33),
|
||||
('B', 'C', 0.75)
|
||||
]
|
||||
initialTestArray = ['A','B','C']*5
|
||||
evolvedTest = evolveMany(initialTestArray, testRules)
|
||||
targetArray = ['B', 'C', 'C', 'A', 'C', 'C', 'A', 'B', 'C', 'A', 'C', 'C', 'B', 'C', 'C']
|
||||
assert evolvedTest == targetArray
|
||||
# checks the initial array is left unchanged
|
||||
assert initialTestArray == ['A','B','C']*5
|
||||
|
||||
# Define a function that evolves a system that starts with initial amounts NA, NB and NC of AA ,
|
||||
# BB and CC nuclei and evolved it in n_timestep from time t=0t=0 to t=tmaxt=tmax .
|
||||
# The function should return three arrays, one for each atom type, of the number of nuclei
|
||||
# of that type at each time step. Each array should contain n_timestep+1 elements including the initial amount.
|
||||
|
||||
def evolve_system(NA, NB, NC, rules, n_step):
|
||||
state = (['A'] * NA)+(['B'] * NB)+(['C'] * NC)
|
||||
|
||||
A_count = numpy.empty(n_step + 1, dtype=int)
|
||||
B_count = numpy.empty(n_step + 1, dtype=int)
|
||||
C_count = numpy.empty(n_step + 1, dtype=int)
|
||||
|
||||
# YOUR CODE HERE
|
||||
A_count[0] = NA
|
||||
B_count[0] = NB
|
||||
C_count[0] = NC
|
||||
for i in range(n_step):
|
||||
state = evolveMany(state, rules)
|
||||
A_count[i+1] = state.count('A')
|
||||
B_count[i+1] = state.count('B')
|
||||
C_count[i+1] = state.count('C')
|
||||
return A_count, B_count, C_count
|
||||
|
||||
|
||||
# these tests are worth 2 marks
|
||||
rules = [
|
||||
('A', 'B', 0.0033),
|
||||
('B', 'C', 0.0075),
|
||||
('C', 'A', 0.009)
|
||||
|
||||
]
|
||||
|
||||
r1, r2, r3 = evolve_system(0, 0, 250, rules, 17)
|
||||
assert len(r1) == 18
|
||||
assert len(r2) == 18
|
||||
assert len(r3) == 18
|
||||
|
||||
# these tests are worth 2 marks
|
||||
testrules = [
|
||||
('A', 'B', 0.086),
|
||||
('B', 'C', 0.075),
|
||||
('C', 'A', 0.19)
|
||||
|
||||
]
|
||||
|
||||
random.seed(9485)
|
||||
r1, r2, r3 = evolve_system(200, 200, 200, testrules, 20)
|
||||
print(r1)
|
||||
print(r2)
|
||||
print(r3)
|
||||
assert (r1 == [200, 213, 233, 250, 258, 251, 266, 263, 259, 260, 265, 259, 256,
|
||||
255, 258, 256, 259, 253, 249, 247, 253]).all()
|
||||
assert (r2 == [200, 198, 201, 206, 205, 214, 214, 212, 216, 221, 225, 234, 236,
|
||||
238, 234, 235, 231, 245, 253, 256, 252]).all()
|
||||
assert (r3 == [200, 189, 166, 144, 137, 135, 120, 125, 125, 119, 110, 107, 108,
|
||||
107, 108, 109, 110, 102, 98, 97, 95]).all()
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
x = np.linspace(0,100,100)
|
||||
np.random.seed(111)
|
||||
y1 = np.random.normal(0,1,100)
|
||||
# y1 = np.linalg.norm(y1,ord = 2)
|
||||
|
||||
plt.plot(x,y1)
|
||||
plt.show()
|
|
@ -0,0 +1,37 @@
|
|||
import numpy as np
|
||||
# 可以由元组创建 , 也可由列表创建
|
||||
a = np.array(((1,2,3,4,5),(6,7,8,9,10),(11,12,13,14,15),(22,33,44,55,66)))
|
||||
print(f"a = {a}")
|
||||
a1 = a[np.ix_([0,2,3],[1,2])]
|
||||
print(f"a1 = {a1}")
|
||||
a2 = a[1,2]
|
||||
print(f"a2 = {a2}")
|
||||
a3 = a[0:2,:]
|
||||
print(f"a3 = {a3}")
|
||||
# 数组改变形状
|
||||
a4 = a.reshape(2,10)
|
||||
print(f"a4 = {a4}")
|
||||
a5 = a.ravel()
|
||||
print(f"a5 = {a5}")
|
||||
a6 = a.ravel()
|
||||
print(f"a6 = {a6}")
|
||||
a7 = a.reshape(-1)
|
||||
print(f"a7 = {a7}")
|
||||
|
||||
a8 = np.vstack([a7,a6])
|
||||
print(f"a8 = {a8}")
|
||||
|
||||
a9 = np.hstack([a7,a6])
|
||||
print(f"a9 = {a9}")
|
||||
|
||||
a = np.array(((1,2,3,4,5),(6,7,8,9,10),(11,12,13,14,15),(22,33,44,55,66)))
|
||||
b = np.array(((22,33,44,55,66),(6,7,8,9,10),(11,12,13,14,15),(1,2,3,4,5)))
|
||||
|
||||
a10 = a[a==b]
|
||||
print(f"a10 = {a10}")
|
||||
|
||||
a11 = np.where(a>10,100,a)
|
||||
print(f"a11 = {a11}")
|
||||
|
||||
a12 = np.where(a>10,100,-100)
|
||||
print(f"a12 = {a12}")
|
|
@ -0,0 +1,16 @@
|
|||
import numpy as np
|
||||
|
||||
a = np.arange(0,12,2).reshape(2,3)
|
||||
b = np.arange(3)
|
||||
|
||||
print(f"a = {a}")
|
||||
print(f"b = {b}")
|
||||
a1 = a+b
|
||||
print(f"a1 = {a1}")
|
||||
a2 = np.row_stack([a,b])
|
||||
print(f"a2 = {a2}")
|
||||
|
||||
a = np.arange(12).reshape(4,3)
|
||||
b = np.array([5,15,25])
|
||||
a3 = a+b
|
||||
print(f"a3 = {a3}")
|
|
@ -0,0 +1,95 @@
|
|||
import numpy as np
|
||||
a = np.array([[1,2,3],[3,2,1]])
|
||||
b = np.array([[1,2],[2,1],[3,1]])
|
||||
aa,bb = np.array([[1,2,3],[1,1,1]]),np.array([[3,2,1],[1,1,1]])
|
||||
# 二维数组的点积
|
||||
a1 = np.dot(a,b)
|
||||
a11 = np.matmul(a,b)
|
||||
a111 = np.matmul(aa,bb.T)
|
||||
print(f"a1 = {a1} a11 = {a11} a111 = {a111}")
|
||||
|
||||
# 二维数组的乘积
|
||||
a2 = a*0.5
|
||||
a22 = a*a
|
||||
a222 = a*(a[:,0].reshape(2,1))
|
||||
a2222 = a*(a[0,:].reshape(1,-1))
|
||||
print(f"a2 = {a2}, "
|
||||
f"a22 = {a22},\n"
|
||||
f"a222 = {a222}\n,"
|
||||
f"a2222 = {a2222}\n,"
|
||||
f"a2 sum = {a2[:,0].sum()}")
|
||||
|
||||
# a22 = a*(b[0].reshape(-1).T)
|
||||
# print(f"a22 a*b = {a22}")
|
||||
|
||||
# 二维数组的行
|
||||
|
||||
c = np.arange(16).reshape(4,-1)
|
||||
# 二维数组的对角线元素
|
||||
a3 = np.diag(c)
|
||||
print(f"a3 = {a3}")
|
||||
# 以元素为对角线产生二维数组
|
||||
a4 = np.diag(a3)
|
||||
print(f"a4 = {a4}")
|
||||
# 特征根与特征向量
|
||||
a5 = np.linalg.eig(c)
|
||||
print(f"a5 = {a5}")
|
||||
|
||||
# 线性方程组求解 ax=b
|
||||
a = np.array([[1,2,3],[2,3,1],[3,2,1]])
|
||||
b = np.array([24,39,26])
|
||||
x = np.linalg.solve(a,b)
|
||||
print(f"x = {x}")
|
||||
|
||||
# 范数的计算
|
||||
c = np.arange(1,3).reshape(-1)
|
||||
a6 = np.linalg.norm(c,ord = 2)
|
||||
print(f"c = {c}, a6 = {a6}")
|
||||
|
||||
a7 = np.zeros((3,4))
|
||||
print(f"a7 = {a7}")
|
||||
a8 = np.eye(2,3)
|
||||
print(f"a8 = {a8}")
|
||||
a9 = np.ones((3,3))
|
||||
print(f"a9 = {a9}")
|
||||
# 矩阵主对角线元素之和
|
||||
a10 = np.trace(a9)
|
||||
print(f"a10 = {a10}")
|
||||
# 两个数组内积
|
||||
|
||||
# 矩阵a的列 必须与 矩阵b的行相同
|
||||
a111 = np.array([[1,2,3],[1,1,1]])
|
||||
b111 = np.array([[3,2,1],[1,1,1]])
|
||||
c111 = np.array([[1],[2]])
|
||||
a11 = np.inner(a111,b111)
|
||||
a12 = np.dot(a111,b111.T)
|
||||
# 两个数组对应元素相乘
|
||||
b11 = a111*b111
|
||||
print(f"b11 = {b11}")
|
||||
b112 = np.multiply(a111,b111)
|
||||
print(f"b112 = {b112}")
|
||||
b12 = a111*2
|
||||
print(f"b12 = {b12}")
|
||||
b13 = a111*c111
|
||||
print(f"b13 = {b13}")
|
||||
# 以下四种一样
|
||||
a13 = np.mat(a111)@np.mat(b111.T)
|
||||
a14 = np.mat(a111)*np.mat(b111.T)
|
||||
a15 = np.dot(np.mat(a111),np.mat(b111.T))
|
||||
a16 = np.inner(np.mat(a111),np.mat(b111))
|
||||
print(f"a11 = {a11}")
|
||||
print(f"a12 = {a12}")
|
||||
print(f"a13 = {a13}")
|
||||
print(f"a14 = {a14}")
|
||||
print(f"a15 = {a15}")
|
||||
print(f"a16 = {a16}")
|
||||
|
||||
a17 = np.zeros((3,2))
|
||||
print(f"a17 = {a17}")
|
||||
|
||||
a18 = np.empty((3,2))
|
||||
print(f"a18 = {a18}")
|
||||
|
||||
a19 = np.array([1,1])
|
||||
a18[1]= a19
|
||||
print(a18)
|
|
@ -0,0 +1,14 @@
|
|||
# 导入第三方模块
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# 构造数据
|
||||
edu = [0.2515,0.3724,0.3336,0.0368,0.0057]
|
||||
labels = ['中专','大专','本科','硕士','其他']
|
||||
|
||||
# 绘制饼图
|
||||
plt.pie(x = edu, # 绘图数据
|
||||
labels=labels, # 添加教育水平标签
|
||||
autopct='%.1f%%' # 设置百分比的格式,这里保留一位小数
|
||||
)
|
||||
# 显示图形
|
||||
plt.show()
|
|
@ -0,0 +1,15 @@
|
|||
from mpl_toolkits.mplot3d import Axes3D
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
import numpy as np
|
||||
from matplotlib import cm
|
||||
|
||||
fig=plt.figure()
|
||||
ax=fig.add_subplot(111,projection='3d')
|
||||
|
||||
u=np.linspace(-1,1,100)
|
||||
x,y=np.meshgrid(u,u)
|
||||
z=x**2+y**2
|
||||
|
||||
ax.plot_surface(x,y,z,rstride=4,cstride=4,cmap=cm.YlGnBu_r)
|
||||
plt.show()
|
|
@ -5,15 +5,15 @@ import numpy as np
|
|||
x = np.linspace(0, 2 * np.pi, 50)
|
||||
y = np.sin(x)
|
||||
|
||||
plt.plot(x, y)
|
||||
plt.show()
|
||||
plt.plot(x, y)
|
||||
plt.plot(x, y * 2)
|
||||
plt.title("sin(x) & 2sin(x)")
|
||||
plt.show()
|
||||
# plt.plot(x, y)
|
||||
# plt.show()
|
||||
# plt.plot(x, y)
|
||||
# plt.plot(x, y * 2)
|
||||
# plt.title("sin(x) & 2sin(x)")
|
||||
# plt.show()
|
||||
|
||||
plt.plot(x, y, label="sin(x)")
|
||||
plt.plot(x, y * 2, label="2sin(x)")
|
||||
# plt.legend()
|
||||
plt.legend(loc='best')
|
||||
plt.legend(loc='best bbbbbbbbbb')
|
||||
plt.show()
|
|
@ -0,0 +1,31 @@
|
|||
YearsExperience,Salary
|
||||
1.1,39343.00
|
||||
1.3,46205.00
|
||||
1.5,37731.00
|
||||
2.0,43525.00
|
||||
2.2,39891.00
|
||||
2.9,56642.00
|
||||
3.0,60150.00
|
||||
3.2,54445.00
|
||||
3.2,64445.00
|
||||
3.7,57189.00
|
||||
3.9,63218.00
|
||||
4.0,55794.00
|
||||
4.0,56957.00
|
||||
4.1,57081.00
|
||||
4.5,61111.00
|
||||
4.9,67938.00
|
||||
5.1,66029.00
|
||||
5.3,83088.00
|
||||
5.9,81363.00
|
||||
6.0,93940.00
|
||||
6.8,91738.00
|
||||
7.1,98273.00
|
||||
7.9,101302.00
|
||||
8.2,113812.00
|
||||
8.7,109431.00
|
||||
9.0,105582.00
|
||||
9.5,116969.00
|
||||
9.6,112635.00
|
||||
10.3,122391.00
|
||||
10.5,121872.00
|
|
|
@ -0,0 +1,70 @@
|
|||
# https://www.cnblogs.com/judejie/p/8999832.html
|
||||
|
||||
# 工作年限与收入之间的散点图
|
||||
# 导入第三方模块
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
import numpy as np
|
||||
# 导入数据集
|
||||
# income = pd.read_csv(r'Salary_Data.csv')
|
||||
# 绘制散点图
|
||||
# sns.lmplot(x = 'YearsExperience', y = 'Salary', data = income, ci = None)
|
||||
# 显示图形
|
||||
|
||||
|
||||
class GD():
|
||||
def __init__(self,data,w,b, lr, nstep):
|
||||
self.data = data
|
||||
self.w = w
|
||||
self.b = b
|
||||
self.lr = lr
|
||||
self.nstep = nstep
|
||||
|
||||
def loss(self,w,b):
|
||||
x,y = self.data[:, 0],self.data[:, 1]
|
||||
loss = 0
|
||||
for i in range(data.shape[0]):
|
||||
loss += (w*x[i]+b-y[i])**2
|
||||
print(f"loss {loss}")
|
||||
return loss/float(data.shape[0])
|
||||
|
||||
def step_grad(self,w,b):
|
||||
x, y = self.data[:, 0], self.data[:, 1]
|
||||
w_gradient = 0
|
||||
b_gradient = 0
|
||||
for i in range(data.shape[0]):
|
||||
w_gradient += 2*(w*x[i]+b-y[i])*x[i]
|
||||
b_gradient += 2 * (w * x[i] + b - y[i])
|
||||
|
||||
w_new = w - w_gradient/data.shape[0]*self.lr
|
||||
b_new = b - b_gradient /data.shape[0] * self.lr
|
||||
return w_new,b_new
|
||||
|
||||
def gradientDescent(self):
|
||||
# history = np.empty( (self.nstep+1, 2) )
|
||||
error = np.zeros(self.nstep)
|
||||
w,b = self.w,self.b
|
||||
for i in range(self.nstep):
|
||||
w,b = self.step_grad(w, b)
|
||||
error[i]=self.loss(w,b)
|
||||
return w,b,error
|
||||
w = 12
|
||||
b =12
|
||||
income = pd.read_csv(r'Salary_Data.csv')
|
||||
data = np.array(income.values)
|
||||
nstep = 1000
|
||||
lr = 0.001
|
||||
gd = GD(data,w,b,lr,nstep)
|
||||
w,b,error = gd.gradientDescent()
|
||||
print("w,b is :",w,b)
|
||||
x = data[:,0]
|
||||
y = data[:,1]
|
||||
plt.scatter(x,y)
|
||||
# plt.legend()
|
||||
plt.plot(x, w*x+b, 'r')
|
||||
plt.show()
|
||||
|
||||
plt.plot(np.arange(nstep), error, 'r')
|
||||
plt.show()
|
||||
# 回归参数w,b的值:w,b is : 11768.548124439758 10167.865862562581
|
Loading…
Reference in New Issue