pytHon深度学习(3.4)
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)的更多相关文章
- 利用python深度学习算法来绘图
可以画画啊!可以画画啊!可以画画啊! 对,有趣的事情需要讲三遍. 事情是这样的,通过python的深度学习算法包去训练计算机模仿世界名画的风格,然后应用到另一幅画中,不多说直接上图! 这个是世界名画& ...
- 好书推荐计划:Keras之父作品《Python 深度学习》
大家好,我禅师的助理兼人工智能排版住手助手条子.可能非常多人都不知道我.由于我真的难得露面一次,天天给禅师做底层工作. wx_fmt=jpeg" alt="640? wx_fmt= ...
- 参考分享《Python深度学习》高清中文版pdf+高清英文版pdf+源代码
学习深度学习时,我想<Python深度学习>应该是大多数机器学习爱好者必读的书.书最大的优点是框架性,能提供一个"整体视角",在脑中建立一个完整的地图,知道哪些常用哪些 ...
- 7大python 深度学习框架的描述及优缺点绍
Theano https://github.com/Theano/Theano 描述: Theano 是一个python库, 允许你定义, 优化并且有效地评估涉及到多维数组的数学表达式. 它与GPUs ...
- 基于python深度学习的apk风险预测脚本
基于python深度学习的apk风险预测脚本 为了有效判断安卓apk有无恶意操作,利用python脚本,通过解包apk文件,对其中xml文件进行特征提取,通过机器学习构建模型,预测位置的apk包是否有 ...
- Python深度学习(Deep Learning with Python) 中文版+英文版+源代码
Keras作者.谷歌大脑François Chollet最新撰写的深度学习Python教程实战书籍(2017年12月出版)介绍深入学习使用Python语言和强大Keras库,详实新颖.PDF高清中文版 ...
- 关于python深度学习网站
大数据文摘作品,转载要求见文末 编译团队|姚佳灵 裴迅 简介 ▼ 深度学习,是人工智能领域的一个突出的话题,被众人关注已经有相当长的一段时间了.它备受关注是因为在计算机视觉(Computer Vi ...
- java web应用调用python深度学习训练的模型
之前参见了中国软件杯大赛,在大赛中用到了深度学习的相关算法,也训练了一些简单的模型.项目线上平台是用java编写的web应用程序,而深度学习使用的是python语言,这就涉及到了在java代码中调用p ...
- Python深度学习读书笔记-3.神经网络的数据表示
标量(0D 张量) 仅包含一个数字的张量叫作标量(scalar,也叫标量张量.零维张量.0D 张量).在Numpy 中,一个float32 或float64 的数字就是一个标量张量(或标量数组).你可 ...
- python深度学习培训概念整理
对于公司组织的人工智能学习,每周日一天课程共计五周,已经上了三次,一天课程下来讲了两本书的知识.发现老师讲的速度太快,深度不够,而且其他公司学员有的没有接触过python知识,所以有必要自己花时间多看 ...
随机推荐
- OleDbCommand 的用法
OleDbCommand 的用法 OleDbConnection con=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; dat ...
- Spark RDD 宽窄依赖
RDD 宽窄依赖 RDD之间有一系列的依赖关系, 可分为窄依赖和宽依赖 窄依赖 从 RDD 的 parition 角度来看 父 RRD 的 parition 和 子 RDD 的 parition 之间 ...
- Windows 2000 栈溢出 利用异常
当在一个函数(test)里面自定义了异常处理,如下: 那么在运行时,它会把自定义的异常处理函数MyExceptionhandler()的地址放入栈中(PUSH 004013CC) 然后把fs:[0]的 ...
- sed -i添加到第一行
用sed的i\命令在第一行前面插入即可,加上 -i 选项直接操作文件. sed -i '1i\要添加的内容' yourfile 查看插入第一行是否成功 sed -n '1,1p' yourfile
- Windows2008R2安装DNS和SQLServer200r2服务 (9.18第七天)
原文网址:https://www.cnblogs.com/yankaohaitaiwei/p/11538205.html 二.IIS搭建web服务器 1.格式化D盘,一定要选择NTFS!!!不然后面添 ...
- UVA - 818 Cutting Chains(切断圆环链)(dfs + 二进制法枚举子集)
题意:有n个圆环(n<=15),已知已经扣在一起的圆环,现在需要打开尽量少的圆环,使所有圆环可以组成一条链. 分析:因为不知道要打开哪个环,如果列举所有的可能性,即枚举打开环的所有子集,最多才2 ...
- Day2-T3
原题目 Describe:质数问题 code: #pragma GCC optimize(2) #include<bits/stdc++.h> #define KKK 1200 using ...
- UIWindow的那些事
UIView是视图的基类,UIViewController是视图控制器的基类,UIResponder是表示一个可以在屏幕上响应触摸事件的对象: 一.UIWindow是一种特殊的UIView,通常在一个 ...
- 海外Essay写作如何减少重复用词
很多海外留学生在Essay写作时往往不善于对单词进行变化,不能将同一个意思用不同的方式表达出来,使得Essay显得单调乏味最终拿不到高分.小编建议大家应该尽量减少Essay写作中的重复用词.本文将为大 ...
- linux部分环境搭建
连接数据库: mysql -hrm-uf6b23117l3s5t69zjo.mysql.rds.aliyuncs.com -uwswl -pwswl@2019 显示用户: show databases ...