keras绘制损失函数曲线

# -*- coding: utf-8 -*-
'''Trains a simple deep NN on the MNIST dataset.
Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
''' from __future__ import print_function import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop
import matplotlib.pyplot as plt batch_size = 128
num_classes = 10
epochs = 20 # the data, shuffled and split between train and test sets
# (x_train, y_train), (x_test, y_test) = mnist.load_data() (x_train, y_train), (x_test, y_test) = mnist.load_data(path='/home/duchao/下载/mnist.npz') # import numpy as np
#
# path = '/home/duchao/下载/mnist.npz'
# f = np.load(path)
# x_train, y_train = f['x_train'], f['y_train']
# x_test, y_test = f['x_test'], f['y_test']
# f.close() x_train = x_train.reshape(60000, 784).astype('float32')
x_test = x_test.reshape(10000, 784).astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices
# label为0~9共10个类别,keras要求格式为binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes) # add by hcq-20171106
# Dense of keras is full-connection.
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy',
optimizer=RMSprop(),
metrics=['accuracy']) history = model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1]) history_dict=history.history
loss_value=history_dict["loss"]
val_loss_value=history_dict["val_loss"] epochs=range(1,len(loss_value)+1)
plt.plot(epochs,loss_value,"bo",label="Training loss")
plt.plot(epochs,val_loss_value,"b",label="Validation loss")
plt.xlabel("epochs")
plt.ylabel("loss")
plt.legend()
plt.show()
# -*- coding: utf-8 -*-
'''Trains a simple deep NN on the MNIST dataset.
Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
''' from __future__ import print_function import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop
import matplotlib.pyplot as plt batch_size = 128
num_classes = 10
epochs = 40 # the data, shuffled and split between train and test sets
# (x_train, y_train), (x_test, y_test) = mnist.load_data() (x_train, y_train), (x_test, y_test) = mnist.load_data(path='/home/duchao/下载/mnist.npz') # import numpy as np
#
# path = '/home/duchao/下载/mnist.npz'
# f = np.load(path)
# x_train, y_train = f['x_train'], f['y_train']
# x_test, y_test = f['x_test'], f['y_test']
# f.close() x_train = x_train.reshape(60000, 784).astype('float32')
x_test = x_test.reshape(10000, 784).astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices
# label为0~9共10个类别,keras要求格式为binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes) # add by hcq-20171106
# Dense of keras is full-connection.
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy',
optimizer=RMSprop(),
metrics=['accuracy']) history = model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1]) # ##绘制训练损失和验证损失
# history_dict=history.history
# loss_value=history_dict["loss"]
# val_loss_value=history_dict["val_loss"]
#
# epochs=range(1,len(loss_value)+1)
# plt.plot(epochs,loss_value,"bo",label="Training loss")
# plt.plot(epochs,val_loss_value,"b",label="Validation loss")
# plt.xlabel("epochs")
# plt.ylabel("loss")
# plt.legend()
# plt.show() ##绘制训练精度和验证精度 plt.clf()
history_dict=history.history
acc=history_dict["acc"]
val_acc=history_dict["val_acc"] loss_value=history_dict["loss"]
val_loss_value=history_dict["val_loss"] epochs=range(1,len(val_acc)+1) plt.plot(epochs,acc,"bo",label="Training acc")
plt.plot(epochs,val_acc,"b",label="Validation acc") plt.plot(epochs,loss_value,"bo",label="Training loss")
plt.plot(epochs,val_loss_value,"b",label="Validation loss") plt.xlabel("epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()
# -*- coding: utf-8 -*-
'''Trains a simple deep NN on the MNIST dataset.
Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
'''
#
# from keras import layers
# from keras.datasets import boston_housing
#
#
# (train_data, train_labels), (test_data, test_labels) = boston_housing.load_data() from keras.datasets import boston_housing
from keras import models
from keras import layers
import numpy as np
import matplotlib.pyplot as plt # train_data.shape:(404, 13),test_data.shape:(102, 13),
# train_targets.shape:(404,),test_targets.shape:(102,)
# the data compromises 13 features
# the targets are the median values of owner-occupied homes,in thousands of dollars
(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()
# feature-wise normalization
mean = train_data.mean(axis=0)
train_data -= mean
std = train_data.std(axis=0)
train_data /= std
# never use any quantity computed on the test data
test_data -= mean
test_data /= std # build the model
# because we need to build a model several times,we use function to cons
def build_model():
model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1],)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(1))
model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
return model #
# # K-fold validation
# k = 4
# num_val_samples = len(train_data) // k
# num_epochs = 500
# all_scores = []
# all_mae_histories = []
# K-fold validation and logs
k = 4
num_val_samples = len(train_data) // k
num_epochs = 50
all_scores = []
all_mae_histories = []
for i in range(k):
print('正在处理fold #', i)
# preparing the validation data:data from partition #k
val_data = train_data[i * num_val_samples:(i + 1) * num_val_samples]
val_targets = train_targets[i * num_val_samples:(i + 1) * num_val_samples]
# preparing the training data:data from all other partitions
partial_train_data = np.concatenate(
[train_data[:i * num_val_samples],
train_data[((i + 1) * num_val_samples):]],
axis=0
)
partial_train_targets = np.concatenate(
[train_targets[:i * num_val_samples],
train_targets[((i + 1) * num_val_samples):]],
axis=0
)
# build the model
model = build_model()
# train the model,silent mode
history = model.fit(partial_train_data, partial_train_targets, validation_data=(val_data, val_targets),
epochs=num_epochs, batch_size=1, verbose=0)
# evaluate the model in the validation data
mae_history = history.history['val_mean_absolute_error']
val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)
all_scores.append(val_mae)
all_mae_histories.append(mae_history) print("Complete!")
average_mae_history = [
np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]
mean_score = np.mean(all_scores)
print("mean_score:", mean_score) #plotting validation scores
plt.plot(range(1,len(average_mae_history)+1),average_mae_history)
plt.xlabel('Epochs')
plt.ylabel('Validation MAE')
plt.show()
 
 

pytHon深度学习(3.4)的更多相关文章

  1. 利用python深度学习算法来绘图

    可以画画啊!可以画画啊!可以画画啊! 对,有趣的事情需要讲三遍. 事情是这样的,通过python的深度学习算法包去训练计算机模仿世界名画的风格,然后应用到另一幅画中,不多说直接上图! 这个是世界名画& ...

  2. 好书推荐计划:Keras之父作品《Python 深度学习》

    大家好,我禅师的助理兼人工智能排版住手助手条子.可能非常多人都不知道我.由于我真的难得露面一次,天天给禅师做底层工作. wx_fmt=jpeg" alt="640? wx_fmt= ...

  3. 参考分享《Python深度学习》高清中文版pdf+高清英文版pdf+源代码

    学习深度学习时,我想<Python深度学习>应该是大多数机器学习爱好者必读的书.书最大的优点是框架性,能提供一个"整体视角",在脑中建立一个完整的地图,知道哪些常用哪些 ...

  4. 7大python 深度学习框架的描述及优缺点绍

    Theano https://github.com/Theano/Theano 描述: Theano 是一个python库, 允许你定义, 优化并且有效地评估涉及到多维数组的数学表达式. 它与GPUs ...

  5. 基于python深度学习的apk风险预测脚本

    基于python深度学习的apk风险预测脚本 为了有效判断安卓apk有无恶意操作,利用python脚本,通过解包apk文件,对其中xml文件进行特征提取,通过机器学习构建模型,预测位置的apk包是否有 ...

  6. Python深度学习(Deep Learning with Python) 中文版+英文版+源代码

    Keras作者.谷歌大脑François Chollet最新撰写的深度学习Python教程实战书籍(2017年12月出版)介绍深入学习使用Python语言和强大Keras库,详实新颖.PDF高清中文版 ...

  7. 关于python深度学习网站

      大数据文摘作品,转载要求见文末 编译团队|姚佳灵 裴迅 简介 ▼ 深度学习,是人工智能领域的一个突出的话题,被众人关注已经有相当长的一段时间了.它备受关注是因为在计算机视觉(Computer Vi ...

  8. java web应用调用python深度学习训练的模型

    之前参见了中国软件杯大赛,在大赛中用到了深度学习的相关算法,也训练了一些简单的模型.项目线上平台是用java编写的web应用程序,而深度学习使用的是python语言,这就涉及到了在java代码中调用p ...

  9. Python深度学习读书笔记-3.神经网络的数据表示

    标量(0D 张量) 仅包含一个数字的张量叫作标量(scalar,也叫标量张量.零维张量.0D 张量).在Numpy 中,一个float32 或float64 的数字就是一个标量张量(或标量数组).你可 ...

  10. python深度学习培训概念整理

    对于公司组织的人工智能学习,每周日一天课程共计五周,已经上了三次,一天课程下来讲了两本书的知识.发现老师讲的速度太快,深度不够,而且其他公司学员有的没有接触过python知识,所以有必要自己花时间多看 ...

随机推荐

  1. 吴裕雄--天生自然C++语言学习笔记:C++ STL 教程

    C++ STL(标准模板库)是一套功能强大的 C++ 模板类,提供了通用的模板类和函数,这些模板类和函数可以实现多种流行和常用的算法和数据结构,如向量.链表.队列.栈. C++ 标准模板库的核心包括以 ...

  2. .net微软企业库的事务回滚

    事务是自定义的一个操作序列. 其中的操作要么全部执行要么全部不执行,是一个不可分割的工作单位.通过事务,SQL Server能将逻辑相关的一组操作绑定在一起,以便服务器保持数据的完整性. Databa ...

  3. 《ES6标准入门》(阮一峰)--2.let 和 const 命令

    1.let命令 基本用法 let只在命令所在的代码块内(花括号内)有效. for循环的计数器,就很合适使用let命令. //var var a = []; for (var i = 0; i < ...

  4. EUI库 - 9 - 数据集合 - 列表

      List 和DataGroup的区别 1 选中一项 会触发 eui.ItemEvent.ITEM_TAP 事件, 2 有选中项的概念,可以设置 List 里的默认选中项    selectedIn ...

  5. java多线程并发(一)-- 相关基础知识

    java多线程的知识是java程序员都应该掌握的技能,目前我接触的项目上用的不多,花点时间熟悉熟悉. 一.基础知识 1.什么是进程? 进程是具有一定独立功能的正在运行过程中的程序,是操作系统进行资源分 ...

  6. Objective-C 和 Swift 第三方库使用

    https://www.jianshu.com/p/6be32a047ca7 原文地址: Objective-C 和 Swift 第三方库使用 注1:文章写于2016年9月,(swift 3.0.Xc ...

  7. 基于磁盘的Kafka为什么这么快

    专注于Java领域优质技术,欢迎关注 作者: Wyman 大数据手稿笔记 Kafka是大数据领域无处不在的消息中间件,目前广泛使用在企业内部的实时数据管道,并帮助企业构建自己的流计算应用程序.Kafk ...

  8. Notepad++配置

    笔记来源于视频: http://baidu.iqiyi.com/watch/498601896985630918.html?page=videoMultiNeed notepad++ 有个很重要问题, ...

  9. CountUp.js 数字跳转效果小插件

    CountUp.js  实现数字跳转效果的小插件 //调用方法 const easingFn = function (t, b, c, d) { var ts = (t /= d) * t; var ...

  10. html—表单控件

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...