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. ELK 安装Elasticsearch

    章节 ELK 介绍 ELK 安装Elasticsearch ELK 安装Kibana ELK 安装Beat ELK 安装Logstash ELK栈要安装以下开源组件: Elasticsearch Ki ...

  2. Java JDK for Windows

    目录 JDK简介下载安装配置JAVA_HOME和Path测试禁止Java自动更新(可选操作) JDK简介 JDK是Java语言的软件开发工具包,主要用于移动设备.嵌入式设备上的java应用程序.JDK ...

  3. P 1022 D进制的A+B

    转跳点 :

  4. UVA - 1612 Guess (猜名次)(贪心)

    题意:有n(n<=16384)位选手参加编程比赛.比赛有3道题目,每个选手的每道题目都有一个评测之前的预得分(这个分数和选手提交程序的时间相关,提交得越早,预得分越大).接下来是系统测试.如果某 ...

  5. python--多线程的应用

    python 多线程执行函数,以及调用函数时传参 import threading def func1(): print('this is function1') def func2(x,y): pr ...

  6. Essay写作的六大黄金法则以及四大禁区

    虽然Essay这么难写,但是,也有一些可以拿高分的准则,本文小编就为大家分享高分Essay写作必知黄金法则,希望对想要在Essay拿高分的留学生小伙伴们有些帮助. 黄金法则1.关注相关问题的重点词汇 ...

  7. react-native-tab-view 导航栏切换插件讲解

    首先引入插件 yarn add react-native-tab-view 如果用的原生环境要安装另外几个插件 yarn add react-native-reanimated react-nativ ...

  8. 吴裕雄--天生自然C++语言学习笔记:C++ 存储类

    存储类定义 C++ 程序中变量/函数的范围(可见性)和生命周期.这些说明符放置在它们所修饰的类型之前.下面列出 C++ 程序中可用的存储类: auto register static extern m ...

  9. Android自定义View——实现字母导航栏

    1.自定义View实现字母导航栏 2.ListView实现联系人列表 3.字母导航栏滑动事件处理 4.字母导航栏与中间字母的联动 5.字母导航栏与ListView的联动 1.先看主布局,方便后面代码的 ...

  10. php和js的小区别

    1.今天看了下php的api感觉还可以,不是很难,可能没看到深入的地方, (1)和js很相似 目前感觉它和js的最大区别 js的  点  被替换成 -> function setCate($pa ...