Tensorflow tfkeras

分类问题与回归问题

分类问题预测的是类别,模型的输出是概率分布
[0.2,0.7,0.9]
回归问题预测的是值,模型的输出是一个实数值
如预测房价

目标函数

为什么需要?
参数是逐步调整的
目标函数可以衡量模型好坏
Model a:[0.1 ,0.4, 0.5 ]
Model b:[0.1,0.4,0.5]

分类问题

需要衡量目标类别与当前预测的差距
__ __ 三分类问题输出例子: [0.2,0.4,0.1] _ _ _ _ _ _ _ — -预测结果为第一类(0.4)
___ _ 三分类真实类别 : 2 -> one_hot -> [0,0,1]__ _ _ ----第二类(1)
______________----- one-hot编 码 : 把正整数变为向量表达
生成一个长度不小于正整数的向量,只有正整数的位置为一,其他是零

在这里插入图片描述

回归问题

预测值与真实值的差距
平方差损失
绝对值损失

模型的训练就是调整参数,使得目标函数逐渐变小的过程
import matplotlib as mpl
import matplotlib.pyplot as plt
# %matplotlib inline
import numpy as np
import sklearn 
import pandas as pd
import os
import sys
import time
import tensorflow as tf

from tensorflow import keras
print(tf.__version__)
print(sys.version_info)
for module in mpl,np,pd,sklearn,tf,keras:
	print(module.__name__,module.__version__)
fashion_mnist = keras.datasets.fashion_mnist
(x_train_all,y_train_all),(x_test,y_test) = fashion_mnist.load_data()
# 把训练集拆分为训练集和验证集
# 前五千张作为验证集,后面的(55000张)作为训练集
x_valid,x_train = x_train_all[:5000],x_train_all[5000:]
y_valid,y_train = y_train_all[:5000],y_train_all[5000:]
print(x_valid.shape,y_valid.shape)#验证集
print(x_train.shape,y_train.shape)#训练集
print(x_test.shape,y_test.shape)#测试集


def show_singel_image(img_arr):
	plt.imshow(img_arr,cmap = "binary") # 以灰度图片显示
	plt.show()
def show_imgs(n_rows,n_cols,x_data,y_data,class_names):
	assert len(x_data) == len(y_data)
	assert n_rows * n_cols < len(x_data)
	plt.figure(figsize = (n_cols * 1.4 ,n_rows * 1.6))
	for row in range(n_rows):
		for col in range(n_cols):
			index = n_cols * row + col # 计算位置
			plt.subplot(n_rows,n_cols,index + 1)#放图
			plt.imshow(x_data[index],cmap="binary",
						interpolation = "nearest")#紧密放置
			plt.axis('off')# 关闭坐标系
			plt.title(class_names[y_data[index]])# 可见 y_data 中存入的是标号,用于辨识,分类
	plt.show()	
class_names = ['T-shirt','Trouser','Pullover','Dress','Coat',
				'Sandal','Shirt','Sneaker','Bag','Ankle boot']
show_imgs(3,5,x_train,y_train,class_names)# 显示3行5列
						
	
# show_singel_image(x_train[0])

# print(y_train[0]) 结果为 4
# tf.keras.models.Sequential()
"""
model = keras.models.Sequential()#建立对象
model.add(keras.layers.Flatten(input_shape=[28,28]))#展平输入
#把二维矩阵展成28*28的一维向量
model.add(keras.layers.Dense(300,activation="relu"))
# 全链接层  activation 是激活函数
# :让下一层的所有单元一一的与上一层连接
model.add(keras.layers.Dense(100,activation="relu"))
model.add(keras.layers.Dense(10,activation="softmax"))
"""
model = keras.models.Sequential(
[
keras.layers.Flatten(input_shape=[28,28]),
keras.layers.Dense(300,activation="relu"),
keras.layers.Dense(100,activation="relu"),
keras.layers.Dense(10,activation="softmax")
])

# relu: y = max(0,x)当x大于0时,输出x,否则输出0
# softmax: 将向量变成概率分布,x=[x1,x2,x3]
#			y = [e^x1/sum, e^x2/sum, e^x3/sum ],
#			sum = e^x1 + e^x2 + e^x3
#    reson for sparse: y是个数 需要 one_hot成向量
#  如果y是一个向量,直接用categorical_crossentropy
model.compile(loss="sparse_categorical_crossentropy",
			optimizer = "sgd",#模型的求解方法,调整方法
			metrics = ["accuracy"])

print(model.layers)
print(model.summary())
#	235500 = 784 * 300 + 784
# [none ,784] * w + b -> [None, 300]  w->[784,300] , b = [300]
history = model.fit(x_train,y_train,epochs=10,# 训练集遍历10次
					validation_data=(x_valid,y_valid))# 验证集
# 开启训练
print(type(history))
print(history.history)
def plot_learning_curves(history):
	pd.DataFrame(history.history).plot(figsize=(8 , 5))
	# 把数据转换成DataFrame(一种数据结构) 图的大小 (8 ,5)
	plt.grid(True)# 显示网格
	plt.gca().set_ylim(0,1)# 设置y坐标轴的范围
	plt.show()

plot_learning_curves(history)

在这里插入图片描述
在这里插入图片描述在这里插入图片描述

·

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值