作业1答案,待完善

来自cluster
Cluster讨论 | 贡献2021年12月7日 (二) 04:47的版本 (Created page with "# 当前答案有误,请自行检查 import numpy as np import os from PIL import Image def loss(y_pred,y_true):#y_pred shape->vector return sum((y_pred - y_true)**2)...")
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳到导航 跳到搜索
  1. 当前答案有误,请自行检查

import numpy as np import os from PIL import Image

def loss(y_pred,y_true):#y_pred shape->vector

   return sum((y_pred - y_true)**2)

def df(x):

   pass

def random_init(shape):

   return np.random.rand(shape)

def load_dataset(path):

   ab = os.listdir(path)
   ba = [i for i in ab if 'jpg' in i]
   x = []
   y = []
   for i in range(len(ba)):
       xi = Image.open(os.path.join(path,ba[i])).convert('L')
       xii = np.array(xi)
       xii = xii[:200,:200]
       yi = sum(sum(xii))
       x.append(xii)
       y.append(yi)
   x = np.array(x)
   y = np.array(y)
   return x,y
     

def bp(w,b,c,yi,ai,lr):

   for i in range(len(w)):
       w[i] = w[i] - lr * 2*(yi-c)*ai[i]
   b = b - lr * 2*(yi-c)*1
   return w,b

def forword(x,w,b):

   return sum(x*w)+b

def train(x,y,w,b,lr):

   for i in range(x.shape[0]):
       c = forword(x[i],w,b)
       los = loss(c,y[i])
       w,b = bp(w,b,c,y[i],x[i],lr)
       print('Loss:\t',los)
   return w,b
   

def main():

   path = r'C:\Users\mtju\Desktop'
   lr = 0.01
   a , y= load_dataset(path)
   x = a.reshape(a.shape[0],-1)
   w = random_init(x.shape[1])
   b = random_init(1)
   for i in range(10):
       w1,b1 = train(x,y,w,b,lr)
   return w1,b1
  1. a = random_init(10)
  2. b = np.random.rand(10,20)
  3. b = b.reshape(5,5,-1)
  4. c = loss(a,b)

w , b = main()