最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

softmax及python實(shí)現(xiàn)過(guò)程解析

 更新時(shí)間:2019年09月30日 08:42:50   作者:沙克的世界  
這篇文章主要介紹了softmax及python實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

相對(duì)于自適應(yīng)神經(jīng)網(wǎng)絡(luò)、感知器,softmax巧妙低使用簡(jiǎn)單的方法來(lái)實(shí)現(xiàn)多分類問(wèn)題。

  • 功能上,完成從N維向量到M維向量的映射
  • 輸出的結(jié)果范圍是[0, 1],對(duì)于一個(gè)sample的結(jié)果所有輸出總和等于1
  • 輸出結(jié)果,可以隱含地表達(dá)該類別的概率

softmax的損失函數(shù)是采用了多分類問(wèn)題中常見(jiàn)的交叉熵,注意經(jīng)常有2個(gè)表達(dá)的形式

  • 經(jīng)典的交叉熵形式:L=-sum(y_right * log(y_pred)), 具體
  • 簡(jiǎn)單版本是: L = -Log(y_pred),具體

這兩個(gè)版本在求導(dǎo)過(guò)程有點(diǎn)不同,但是結(jié)果都是一樣的,同時(shí)損失表達(dá)的意思也是相同的,因?yàn)樵诘谝环N表達(dá)形式中,當(dāng)y不是

正確分類時(shí),y_right等于0,當(dāng)y是正確分類時(shí),y_right等于1。

下面基于mnist數(shù)據(jù)做了一個(gè)多分類的實(shí)驗(yàn),整體能達(dá)到85%的精度。

'''
softmax classifier for mnist 

created on 2019.9.28
author: vince
'''
import math
import logging
import numpy 
import random
import matplotlib.pyplot as plt
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
from sklearn.metrics import accuracy_score

def loss_max_right_class_prob(predictions, y):
	return -predictions[numpy.argmax(y)];

def loss_cross_entropy(predictions, y):
	return -numpy.dot(y, numpy.log(predictions));
	
'''
Softmax classifier
linear classifier 
'''
class Softmax:

	def __init__(self, iter_num = 100000, batch_size = 1):
		self.__iter_num = iter_num;
		self.__batch_size = batch_size;
	
	def train(self, train_X, train_Y):
		X = numpy.c_[train_X, numpy.ones(train_X.shape[0])];
		Y = numpy.copy(train_Y);

		self.L = [];

		#initialize parameters
		self.__weight = numpy.random.rand(X.shape[1], 10) * 2 - 1.0;
		self.__step_len = 1e-3; 

		logging.info("weight:%s" % (self.__weight));

		for iter_index in range(self.__iter_num):
			if iter_index % 1000 == 0:
				logging.info("-----iter:%s-----" % (iter_index));
			if iter_index % 100 == 0:
				l = 0;
				for i in range(0, len(X), 100):
					predictions = self.forward_pass(X[i]);
					#l += loss_max_right_class_prob(predictions, Y[i]); 
					l += loss_cross_entropy(predictions, Y[i]); 
				l /= len(X);
				self.L.append(l);

			sample_index = random.randint(0, len(X) - 1);
			logging.debug("-----select sample %s-----" % (sample_index));

			z = numpy.dot(X[sample_index], self.__weight);
			z = z - numpy.max(z);
			predictions = numpy.exp(z) / numpy.sum(numpy.exp(z));
			dw = self.__step_len * X[sample_index].reshape(-1, 1).dot((predictions - Y[sample_index]).reshape(1, -1));
#			dw = self.__step_len * X[sample_index].reshape(-1, 1).dot(predictions.reshape(1, -1)); 
#			dw[range(X.shape[1]), numpy.argmax(Y[sample_index])] -= X[sample_index] * self.__step_len;

			self.__weight -= dw;

			logging.debug("weight:%s" % (self.__weight));
			logging.debug("loss:%s" % (l));
		logging.info("weight:%s" % (self.__weight));
		logging.info("L:%s" % (self.L));
	
	def forward_pass(self, x):
		net = numpy.dot(x, self.__weight);
		net = net - numpy.max(net);
		net = numpy.exp(net) / numpy.sum(numpy.exp(net)); 
		return net;

	def predict(self, x):
		x = numpy.append(x, 1.0);
		return self.forward_pass(x);


def main():
	logging.basicConfig(level = logging.INFO,
			format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
			datefmt = '%a, %d %b %Y %H:%M:%S');
			
	logging.info("trainning begin.");

	mnist = read_data_sets('../data/MNIST',one_hot=True)  # MNIST_data指的是存放數(shù)據(jù)的文件夾路徑,one_hot=True 為采用one_hot的編碼方式編碼標(biāo)簽

	#load data
	train_X = mnist.train.images        #訓(xùn)練集樣本
	validation_X = mnist.validation.images   #驗(yàn)證集樣本
	test_X = mnist.test.images         #測(cè)試集樣本
	#labels
	train_Y = mnist.train.labels        #訓(xùn)練集標(biāo)簽
	validation_Y = mnist.validation.labels   #驗(yàn)證集標(biāo)簽
	test_Y = mnist.test.labels         #測(cè)試集標(biāo)簽

	classifier = Softmax();
	classifier.train(train_X, train_Y);

	logging.info("trainning end. predict begin.");

	test_predict = numpy.array([]);
	test_right = numpy.array([]);
	for i in range(len(test_X)):
		predict_label = numpy.argmax(classifier.predict(test_X[i]));
		test_predict = numpy.append(test_predict, predict_label);
		right_label = numpy.argmax(test_Y[i]);
		test_right = numpy.append(test_right, right_label);

	logging.info("right:%s, predict:%s" % (test_right, test_predict));
	score = accuracy_score(test_right, test_predict);
	logging.info("The accruacy score is: %s "% (str(score)));


	plt.plot(classifier.L)
	plt.show();

if __name__ == "__main__":
	main();

損失函數(shù)收斂情況

Sun, 29 Sep 2019 18:08:08 softmax.py[line:104] INFO trainning end. predict begin.
Sun, 29 Sep 2019 18:08:08 softmax.py[line:114] INFO right:[7. 2. 1. ... 4. 5. 6.], predict:[7. 2. 1. ... 4. 8. 6.]
Sun, 29 Sep 2019 18:08:08 softmax.py[line:116] INFO The accruacy score is: 0.8486 

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python中.py文件打包成exe可執(zhí)行文件詳解

    Python中.py文件打包成exe可執(zhí)行文件詳解

    這篇文章主要給大家介紹了在Python中.py文件打包成exe可執(zhí)行文件的相關(guān)資料,文中介紹的非常詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。
    2017-03-03
  • Python isinstance函數(shù)介紹

    Python isinstance函數(shù)介紹

    這篇文章主要介紹了Python isinstance函數(shù)介紹,本文用實(shí)例講解了判斷變量是否是某個(gè)指定類型,需要的朋友可以參考下
    2015-04-04
  • Python Flask請(qǐng)求擴(kuò)展與中間件相關(guān)知識(shí)總結(jié)

    Python Flask請(qǐng)求擴(kuò)展與中間件相關(guān)知識(shí)總結(jié)

    今天帶大家學(xué)習(xí)的是關(guān)于Python Flask的相關(guān)知識(shí),文章圍繞著Flask請(qǐng)求擴(kuò)展與中間件的知識(shí)展開,文中有非常詳細(xì)的介紹,需要的朋友可以參考下
    2021-06-06
  • Python自定義logger模塊的實(shí)例代碼

    Python自定義logger模塊的實(shí)例代碼

    Python標(biāo)準(zhǔn)庫(kù)中的logging模塊提供了日志記錄的功能,自定義 Logger 可以根據(jù)項(xiàng)目的需求定制化日志記錄,滿足特定的日志記錄格式、輸出目標(biāo)和日志級(jí)別等要求,本文給大家介紹了Python自定義logger模塊的實(shí)例代碼,需要的朋友可以參考下
    2024-02-02
  • python基礎(chǔ)入門之列表(一)

    python基礎(chǔ)入門之列表(一)

    在Python中,列表(list)是常用的數(shù)據(jù)類型。列表由一系列按照特定順序排列的項(xiàng)(item)組成。
    2021-06-06
  • pytorch如何對(duì)image和label同時(shí)進(jìn)行隨機(jī)翻轉(zhuǎn)

    pytorch如何對(duì)image和label同時(shí)進(jìn)行隨機(jī)翻轉(zhuǎn)

    這篇文章主要介紹了pytorch如何對(duì)image和label同時(shí)進(jìn)行隨機(jī)翻轉(zhuǎn)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 使用Python實(shí)現(xiàn)橋接模式的代碼詳解

    使用Python實(shí)現(xiàn)橋接模式的代碼詳解

    橋接模式是一種結(jié)構(gòu)型設(shè)計(jì)模式,它將抽象部分與其實(shí)現(xiàn)部分分離,使它們都可以獨(dú)立地變化,本文將給大家介紹如何使用Python實(shí)現(xiàn)橋接模式,需要的朋友可以參考下
    2024-02-02
  • pycharm修改主題顏色和注釋顏色的詳細(xì)圖文教程

    pycharm修改主題顏色和注釋顏色的詳細(xì)圖文教程

    PyCharm是一款強(qiáng)大的Python編輯器,相信很多人都已經(jīng)用上了它,這篇文章主要給大家介紹了關(guān)于pycharm修改主題顏色和注釋顏色的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2024-04-04
  • Python的Django框架中自定義模版標(biāo)簽的示例

    Python的Django框架中自定義模版標(biāo)簽的示例

    這篇文章主要介紹了Python的Django框架中自定義模版標(biāo)簽的示例,標(biāo)簽的用處比過(guò)濾器更多,需要的朋友可以參考下
    2015-07-07
  • 學(xué)習(xí)python如何處理需要登錄的網(wǎng)站步驟

    學(xué)習(xí)python如何處理需要登錄的網(wǎng)站步驟

    這篇文章主要為大家介紹了python如何處理需要登錄的網(wǎng)站步驟學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-10-10

最新評(píng)論

平邑县| 武穴市| 当涂县| 冷水江市| 亳州市| 阳西县| 若羌县| 辽宁省| 申扎县| 郎溪县| 滨州市| 金沙县| 涪陵区| 仪陇县| 麻江县| 嘉峪关市| 工布江达县| 开原市| 渝北区| 湾仔区| 玉溪市| 富民县| 广汉市| 陆良县| 凤凰县| 鸡东县| 正安县| 鞍山市| 普兰县| 通城县| 鹿泉市| 庐江县| 永宁县| 宝丰县| 万盛区| 盱眙县| 崇信县| 河北省| 灌云县| 武清区| 闽侯县|