Chapter 04 神經(jīng)網(wǎng)絡(luò)的學(xué)習(xí)

均方誤 與交叉熵誤差

def mean_squared_error(y,t):
    return 0.5*np.sum((y-t)**2)

def cross_entropy_error(y,t):  #t為真實值商乎,y為預(yù)測值
    delta=1e-7
    return -np.sum(t*np.log(y+delta))

t = np.array([0, 0, 1, 0, 0, 0, 0, 0, 0, 0])
y1 = np.array([0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0])
y2 = np.array([0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0])
print(mean_squared_error(t,y1))
print(mean_squared_error(t,y2))
print(cross_entropy_error(y1,t))
print(cross_entropy_error(y2,t))

0.09750000000000003
0.5975
0.510825457099338
2.302584092994546

mini-batch學(xué)習(xí)

(x_train, t_train), (x_test, t_test) = load_mnist(
    normalize=True, one_hot_label=True)
train_size = x_train.shape[0]
batch_size = 10
batch_mask = np.random.choice(train_size, batch_size)  #從0-59999中隨機抽出10個
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]

mini-batch版交叉熵誤差的實現(xiàn)

#訓(xùn)練數(shù)據(jù)是one-hot形式
def cross_entropy_error(y, t):
    if y.ndim == 1:
        t = t.reshape(1, t.size)
        y = y.reshape(1, t.size)
    else:
        batch_size = y.shape[0]
        return -np.sum(t * np.log(y + 1e-7)) / batch_size

#訓(xùn)練數(shù)據(jù)不是one-hot形式
#def cross_entropy_error(y, t):
#    if y.ndim == 1:
#        t = t.reshape(1, t.size)
#        y = y.reshape(1, y.size)
#    batch_size = y.shape[0]
#    return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size

導(dǎo)數(shù)的計算

def numerical_diff(f, x):
    h = 1e-4
    return (f(x + h) - f(x - h)) / (2 * h)

def square(x):
    return x * x

func = square
print(numerical_diff(func, 2))

4.000000000004

定義函數(shù)f(x_0,x_1)=x_0^2+x_1^2

def function_2(x):
    return x[0]**2+x[1]**2

求f在x_0=3,x_1=4時的偏導(dǎo)數(shù)

def function_tmp1(x0):
    return x0 * x0 + 4**2

def function_tmp2(x1):
    return x1 * x1 + 3**2

print(numerical_diff(function_tmp1, 3))
print(numerical_diff(function_tmp2, 4))

6.00000000000378
7.999999999999119

由全部變量的偏導(dǎo)數(shù)匯總而成的向量稱為梯度

def numerical_gradient(f, x):
    h = 1e-4
    grad = np.zeros_like(x)  #存放結(jié)果
    for idx in range(x.size):
        tmp_val = x[idx]
        x[idx] = tmp_val + h
        fxh1 = f(x)
        x[idx] = tmp_val - h
        fxh2 = f(x)
        grad[idx] = (fxh1 - fxh2) / (2 * h)
        x[idx] = tmp_val
    return grad

print(numerical_gradient(function_2, np.array([0.0, 2.0])))

[0. 4.]

梯度下降

def gradient_descent(f,init_x,lr=0.01,step_num=100):
    x=init_x
    for i in range(step_num):
        grad=numerical_gradient(f,x)
        x-=lr*grad
    return x

init_x=np.array([2.0,3.0])
print(gradient_descent(function_2,init_x,lr=0.1))
print(gradient_descent(function_2,init_x,lr=10))

[4.07407195e-10 6.11110793e-10]
[-2.39906967e+12 -2.76179331e+12]

神經(jīng)網(wǎng)絡(luò)的梯度

def softmax(x):
    if x.ndim == 2:
        x = x.T
        x = x - np.max(x, axis=0)
        y = np.exp(x) / np.sum(np.exp(x), axis=0)
        return y.T

    x = x - np.max(x)  # 溢出對策
    return np.exp(x) / np.sum(np.exp(x))


def cross_entropy_error(y, t):
    if y.ndim == 1:
        t = t.reshape(1, t.size)
        y = y.reshape(1, y.size)

    # 監(jiān)督數(shù)據(jù)是one-hot-vector的情況下佩伤,轉(zhuǎn)換為正確解標(biāo)簽的索引
    if t.size == y.size:
        t = t.argmax(axis=1)

    batch_size = y.shape[0]
    return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size


class simpleNet:
    def __init__(self):
        self.W = np.random.randn(2, 3)  #高斯分布進行初始化

    def predict(self, x):
        return np.dot(x, self.W)

    def loss(self, x, t):
        z = self.predict(x)
        y = softmax(z)
        loss = cross_entropy_error(y, t)
        return loss

net = simpleNet()
print(net.W)
x = np.array([0.6, 0.9])
p = net.predict(x)
print(p)
t = np.array([0, 0, 1])
print(net.loss(x, t))

[[ 0.92716354 -0.14222582 0.29493579]
[-1.09513484 -0.03646633 1.0450259 ]]
[-0.42932323 -0.11815519 1.11748478]
0.4078456178864742

寫一個2 層神經(jīng)網(wǎng)絡(luò)的類

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def numerical_gradient(f, x):
    h = 1e-4  # 0.0001
    grad = np.zeros_like(x)

    it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
    while not it.finished:
        idx = it.multi_index
        tmp_val = x[idx]
        x[idx] = float(tmp_val) + h
        fxh1 = f(x)  # f(x+h)

        x[idx] = tmp_val - h
        fxh2 = f(x)  # f(x-h)
        grad[idx] = (fxh1 - fxh2) / (2 * h)

        x[idx] = tmp_val  # 還原值
        it.iternext()

    return grad

class TwoLayerNet:
    def __init__(self,
                 input_size,
                 hidden_size,
                 output_size,
                 weight_init_std=0.01):
        self.params = {}
        self.params['W1'] = weight_init_std * np.random.randn(
            input_size, hidden_size)
        self.params['b1'] = np.zeros(hidden_size)
        self.params['W2'] = weight_init_std * np.random.randn(
            hidden_size, output_size)
        self.params['b2'] = np.zeros(output_size)

    def predict(self, x):
        W1, W2 = self.params['W1'], self.params['W2']
        b1, b2 = self.params['b1'], self.params['b2']
        a1 = np.dot(x, W1) + b1
        z1 = sigmoid(a1)
        a2 = np.dot(z1, W2) + b2
        y = softmax(a2)
        return y

    def loss(self, x, t):
        y = self.predict(x)
        return cross_entropy_error(y, t)

    def accurary(self, x, t):
        y = self.predict(x)
        y = np.argmax(y, axis=1)
        t = np.argmax(t, axis=1)
        accurary = np.sum(y == t) / float(x.shape[0])
        return accurary

    def numerical_gradient(self, x, t):
        loss_W = lambda W: self.loss(x, t)
        grads = {}
        grads['W1'] = numerical_gradient(loss_W, self.params['W1'])
        grads['b1'] = numerical_gradient(loss_W, self.params['b1'])
        grads['W2'] = numerical_gradient(loss_W, self.params['W2'])
        grads['b2'] = numerical_gradient(loss_W, self.params['b2'])
        return grads

net=TwoLayerNet(input_size=784,hidden_size=100,output_size=10)
x=np.random.rand(100,784)
y=net.predict(x)
t=np.random.rand(100,10)
print(net.accurary(x,t))

0.1

mini-batch的實現(xiàn)

(x_train, t_train), (x_test, t_test) =  load_mnist(normalize=True, one_hot_label = True)

train_loss_list = []
train_acc_list = []
test_acc_list = []

# 超參數(shù)
iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1

# 平均每個epoch的重復(fù)次數(shù)
iter_per_epoch = max(train_size / batch_size, 1)

network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
for i in range(iters_num):
    print(i,end='')
    batch_mask = np.random.choice(train_size, batch_size)
    x_batch = x_train[batch_mask]
    t_batch = t_train[batch_mask]
    grad = network.numerical_gradient(x_batch, t_batch)
    for key in ('W1', 'b1', 'W2', 'b2'):
        network.params[key] -= learning_rate * grad[key]
    loss = network.loss(x_batch, t_batch)
    train_loss_list.append(loss)
    #計算每個epoch的識別精度
    if i % iter_per_epoch == 0:
        train_acc = network.accurary(x_train, t_train)
        test_acc = network.accurary(x_test, t_test)
        train_acc_list.append(train_acc)
        test_acc_list.append(test_acc)
        print("train acc, test acc | " + str(train_acc) + ", " + str(test_acc))

這個沒有運行結(jié)果谭胚,大約一分鐘一次迭代,1W次循環(huán)要七天七夜吊输,撐不住……

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子狂巢,更是在濱河造成了極大的恐慌胚吁,老刑警劉巖牙躺,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異腕扶,居然都是意外死亡孽拷,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門蕉毯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來乓搬,“玉大人,你說我怎么就攤上這事代虾〗希” “怎么了?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵棉磨,是天一觀的道長江掩。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么环形? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任策泣,我火速辦了婚禮,結(jié)果婚禮上抬吟,老公的妹妹穿的比我還像新娘萨咕。我一直安慰自己,他們只是感情好火本,可當(dāng)我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布危队。 她就那樣靜靜地躺著,像睡著了一般钙畔。 火紅的嫁衣襯著肌膚如雪茫陆。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天擎析,我揣著相機與錄音簿盅,去河邊找鬼。 笑死揍魂,一個胖子當(dāng)著我的面吹牛桨醋,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播愉烙,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼讨盒,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了步责?” 一聲冷哼從身側(cè)響起返顺,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蔓肯,沒想到半個月后遂鹊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡蔗包,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年秉扑,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片调限。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡舟陆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出耻矮,到底是詐尸還是另有隱情秦躯,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布裆装,位于F島的核電站踱承,受9級特大地震影響倡缠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜茎活,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一昙沦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧载荔,春花似錦盾饮、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至煌珊,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間泌豆,已是汗流浹背定庵。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留踪危,地道東北人蔬浙。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像贞远,于是被迫代替她去往敵國和親畴博。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,515評論 2 359

推薦閱讀更多精彩內(nèi)容