tqdm
q-learning
import numpy as npimport pandas as pdimport timenp.random.seed(2) # reproducibleN_STATES = 6 # the length of the 1 dimensional world 一维状态空间ACTIONS = ['left', 'right'] # available actions 可以采取的行动EPSILON = 0.9 # greedy police 贪婪率ALPHA = 0.1 # learning rate 学习率GAMMA = 0.9 # discount factor 衰减因数MAX_EPISODES = 10 # maximum episodes 最大训练轮次,三四轮就快了FRESH_TIME = 0.3 # fresh time for one move # 每一步移动的刷新时间def build_q_table(n_states, actions):table = pd.DataFrame(np.zeros((n_states, len(actions))), # q_table initial valuescolumns=actions, # actions's name)# print(table) # show tablereturn tabledef choose_action(state, q_table):# This is how to choose an actionstate_actions = q_table.iloc[state, :] # 取Q表的第state这一行# 目的就是跳出全局最优if (np.random.uniform() > EPSILON) or ((state_actions == 0).all()):# act non-greedy or state-action have no valueaction_name = np.random.choice(ACTIONS)else: # act greedyaction_name = state_actions.idxmax()# replace argmax to idxmax as argmax means a different function in newer version of pandasreturn action_namedef get_env_feedback(S, A):# This is how agent will interact with the environmentif A == 'right': # move rightif S == N_STATES - 2: # terminateS_ = 'terminal' # s_ 是s的下一个状态R = 1else:S_ = S + 1R = 0else: # move leftR = 0if S == 0: # s代表位置S_ = S # reach the wallelse:S_ = S - 1return S_, R # 这里只是返回了 一个R(值为0或1),我还能反馈一下步数def update_env(S, episode, step_counter):# This is how environment be updatedenv_list = ['-'] * (N_STATES - 1) + ['T'] # '---------T' our environmentif S == 'terminal':interaction = 'Episode %s: total_steps = %s' % (episode + 1, step_counter)print('\r{}'.format(interaction), end='')time.sleep(2)print('\r ', end='')else:env_list[S] = 'o' # 画出当前点在哪儿,为了做可视化interaction = ''.join(env_list)print('\r{}'.format(interaction), end='')time.sleep(FRESH_TIME)def rl():# main part of RL loopq_table = build_q_table(N_STATES, ACTIONS)for episode in range(MAX_EPISODES): # 最多迭代MAX_EPISODES次step_counter = 0S = 0is_terminated = Falseupdate_env(S, episode, step_counter) # 每一次迭代之前都要初始化起点和终点while not is_terminated:A = choose_action(S, q_table)S_, R = get_env_feedback(S, A) # take action & get next state and rewardq_predict = q_table.loc[S, A] # 预测值就是表中原来的值if S_ != 'terminal':q_target = R + GAMMA * q_table.iloc[S_, :].max() # next state is not terminal# Q-现实 等于 走到这个点得到的反馈 + 原来的最大值*衰减因子(原来的最大值应该就是A对应的这一列)else:q_target = R # next state is terminalis_terminated = True # terminate this episodeq_table.loc[S, A] += ALPHA * (q_target - q_predict) # update 更新Q表S = S_ # move to next stateupdate_env(S, episode, step_counter + 1)step_counter += 1 # 缺乏一个步数限制return q_tableif __name__ == "__main__":q_table = rl()print('\r\nQ-table:\n')print(q_table)
1. 初始化Q表
N_STATES = 6 # the length of the 1 dimensional world 一维状态空间
ACTIONS = ['left', 'right'] # available actions 可以采取的行动
def build_q_table(n_states, actions):
table = pd.DataFrame(
np.zeros((n_states, len(actions))), # q_table initial values
columns=actions, # actions's name
)
print(table) # show table
return table
q_table = build_q_table(N_STATES, ACTIONS)
2. 动作选择

上图中o代表我所处的位置, 对应的Q表中下标为1,T代表目标位置
那我此时应该采取的动作,应该是选择第2行(下标为1的行)中最大值对应的动作,即选择向右移动
也就是书中所说的:我用的Q预测进行选择下一步的动作,所谓的**Q预测**就是在我选择下一个动作的时候,Q表中的数据
3. Q表的更新
while not is_terminated:
A = choose_action(S, q_table)
S_, R = get_env_feedback(S, A) # take action & get next state and reward
q_predict = q_table.loc[S, A] # 预测值就是表中原来的值
if S_ != 'terminal':
q_target = R + GAMMA * q_table.iloc[S_, :].max() # next state is not terminal
# Q-现实 等于 走到这个点得到的反馈 + 原来的最大值*衰减因子(原来的最大值应该就是A对应的这一列)
else:
q_target = R # next state is terminal
is_terminated = True # terminate this episode
q_table.loc[S, A] += ALPHA * (q_target - q_predict) # update 更新Q表
S = S_ # move to next state
update_env(S, episode, step_counter + 1)
step_counter += 1
q_predict:Q预测q_target: Q现实,就是我根据Q预测采取行动之后,得到的反馈R加上衰减因子GAMMA乘以原来的数值,对于下面这张图来说就是,R + GAMMA * 0.000073
更新Q表:ALPHA * (q_target - q_predict),即 学习率*``(Q现实-Q预测)
即,将0.000073更新为ALPHA * (q_target - q_predict)
蚁群算法
# -*- coding: utf-8 -*-
import random
import copy
import time
import sys
import math
import tkinter # //GUI模块
import threading
from functools import reduce
# 参数
'''
ALPHA:信息启发因子,值越大,则蚂蚁选择之前走过的路径可能性就越大
,值越小,则蚁群搜索范围就会减少,容易陷入局部最优
BETA:Beta值越大,蚁群越就容易选择局部较短路径,这时算法收敛速度会
加快,但是随机性不高,容易得到局部的相对最优
'''
(ALPHA, BETA, RHO, Q) = (1.0, 2.0, 0.5, 100.0)
# 城市数,蚁群
(city_num, ant_num) = (50, 50)
distance_x = [ # 优化:随机城市坐标
178, 272, 176, 171, 650, 499, 267, 703, 408, 437, 491, 74, 532,
416, 626, 42, 271, 359, 163, 508, 229, 576, 147, 560, 35, 714,
757, 517, 64, 314, 675, 690, 391, 628, 87, 240, 705, 699, 258,
428, 614, 36, 360, 482, 666, 597, 209, 201, 492, 294]
distance_y = [
170, 395, 198, 151, 242, 556, 57, 401, 305, 421, 267, 105, 525,
381, 244, 330, 395, 169, 141, 380, 153, 442, 528, 329, 232, 48,
498, 265, 343, 120, 165, 50, 433, 63, 491, 275, 348, 222, 288,
490, 213, 524, 244, 114, 104, 552, 70, 425, 227, 331]
# 城市距离和信息素
distance_graph = [[0.0 for col in range(city_num)] for raw in range(city_num)]
pheromone_graph = [[1.0 for col in range(city_num)] for raw in range(city_num)] # 信息素矩阵
# ----------- 蚂蚁 -----------
class Ant(object):
# 初始化
def __init__(self, ID):
self.ID = ID # ID
self.__clean_data() # 随机初始化出生点
# 初始数据
def __clean_data(self):
self.path = [] # 当前蚂蚁的路径
self.total_distance = 0.0 # 当前路径的总距离
self.move_count = 0 # 移动次数
self.current_city = -1 # 当前停留的城市
self.open_table_city = [True for i in range(city_num)] # 探索城市的状态,true可以访问的城市
city_index = random.randint(0, city_num - 1) # 随机初始出生点
self.current_city = city_index
self.path.append(city_index)
self.open_table_city[city_index] = False
self.move_count = 1
# 选择下一个城市
def __choice_next_city(self):
next_city = -1
select_citys_prob = [0.0 for i in range(city_num)] # 存储去下个城市的概率
total_prob = 0.0 # 可以去的城市的总概率
# 获取去下一个城市的概率
for i in range(city_num):
if self.open_table_city[i]:
try:
# 计算概率:与信息素浓度成正比,与距离成反比,,,,,Beta大的话容易陷入局部最优
select_citys_prob[i] = pow(pheromone_graph[self.current_city][i], ALPHA) * pow(
(1.0 / distance_graph[self.current_city][i]), BETA)
total_prob += select_citys_prob[i]
except ZeroDivisionError as e:
print('Ant ID: {ID}, current city: {current}, target city: {target}'.format(ID=self.ID,
current=self.current_city,
target=i))
sys.exit(1)
# 轮盘选择城市
if total_prob > 0.0:
# 产生一个随机概率,0.0-total_prob
temp_prob = random.uniform(0.0, total_prob)
for i in range(city_num):
if self.open_table_city[i]:
# 轮次相减
temp_prob -= select_citys_prob[i]
if temp_prob < 0.0:
next_city = i
break
# 未从概率产生,顺序选择一个未访问城市
# if next_city == -1:
# for i in range(city_num):
# if self.open_table_city[i]:
# next_city = i
# break
if (next_city == -1):
next_city = random.randint(0, city_num - 1)
while ((self.open_table_city[next_city]) == False): # if==False,说明已经遍历过了
next_city = random.randint(0, city_num - 1)
# 返回下一个城市序号
return next_city
# 计算路径总距离
def __cal_total_distance(self):
temp_distance = 0.0
for i in range(1, city_num):
start, end = self.path[i], self.path[i - 1]
temp_distance += distance_graph[start][end]
# 回路
end = self.path[0]
temp_distance += distance_graph[start][end]
self.total_distance = temp_distance
# 移动操作
def __move(self, next_city):
self.path.append(next_city)
self.open_table_city[next_city] = False
self.total_distance += distance_graph[self.current_city][next_city]
self.current_city = next_city
self.move_count += 1
# 搜索路径
def search_path(self):
# 初始化数据
self.__clean_data()
# 搜素路径,遍历完所有城市为止
while self.move_count < city_num:
# 移动到下一个城市
next_city = self.__choice_next_city()
self.__move(next_city)
# 计算路径总长度
self.__cal_total_distance()
# ----------- TSP问题 -----------
class TSP(object):
def __init__(self, root, width=800, height=600, n=city_num):
# 创建画布
self.root = root
self.width = width
self.height = height
# 城市数目初始化为city_num
self.n = n
# tkinter.Canvas
self.canvas = tkinter.Canvas(
root,
width=self.width,
height=self.height,
bg="#EBEBEB", # 背景白色
xscrollincrement=1,
yscrollincrement=1
)
self.canvas.pack(expand=tkinter.YES, fill=tkinter.BOTH)
self.title("TSP蚁群算法(n:初始化 e:开始搜索 s:停止搜索 q:退出程序)")
self.__r = 5
self.__lock = threading.RLock() # 线程锁
self.__bindEvents()
self.new()
# 计算城市之间的距离
for i in range(city_num):
for j in range(city_num):
temp_distance = pow((distance_x[i] - distance_x[j]), 2) + pow((distance_y[i] - distance_y[j]), 2)
temp_distance = pow(temp_distance, 0.5) # 求根号
distance_graph[i][j] = float(int(temp_distance + 0.5))
# 按键响应程序
def __bindEvents(self):
self.root.bind("q", self.quite) # 退出程序
self.root.bind("n", self.new) # 初始化
self.root.bind("e", self.search_path) # 开始搜索
self.root.bind("s", self.stop) # 停止搜索
# 更改标题
def title(self, s):
self.root.title(s)
# 初始化
def new(self, evt=None):
# 停止线程
self.__lock.acquire()
self.__running = False
self.__lock.release()
self.clear() # 清除信息
self.nodes = [] # 节点坐标
self.nodes2 = [] # 节点对象
# 初始化城市节点
for i in range(len(distance_x)):
# 在画布上随机初始坐标
x = distance_x[i]
y = distance_y[i]
self.nodes.append((x, y))
# 生成节点椭圆,半径为self.__r
node = self.canvas.create_oval(x - self.__r,
y - self.__r, x + self.__r, y + self.__r,
fill="#ff0000", # 填充红色
outline="#000000", # 轮廓白色
tags="node",
)
self.nodes2.append(node)
# 显示坐标
self.canvas.create_text(x, y - 10, # 使用create_text方法在坐标(302,77)处绘制文字
text='(' + str(x) + ',' + str(y) + ')', # 所绘制文字的内容
fill='black' # 所绘制文字的颜色为灰色
)
# 顺序连接城市
# self.line(range(city_num))
# 初始城市之间的距离和信息素
for i in range(city_num):
for j in range(city_num):
pheromone_graph[i][j] = 1.0 # 初始信息素为1.0
self.ants = [Ant(ID) for ID in range(ant_num)] # 初始蚁群,创建ant_num个Ant对象
self.best_ant = Ant(-1) # 初始最优解
self.best_ant.total_distance = 1 << 31 # 初始最大距离
self.iter = 1 # 初始化迭代次数
# 将节点按order顺序连线
def line(self, order):
# 删除原线
self.canvas.delete("line")
def line2(i1, i2):
p1, p2 = self.nodes[i1], self.nodes[i2]
self.canvas.create_line(p1, p2, fill="#000000", tags="line")
return i2
# order[-1]为初始值
reduce(line2, order, order[-1])
# 清除画布
def clear(self):
for item in self.canvas.find_all():
self.canvas.delete(item)
# 退出程序
def quite(self, evt):
self.__lock.acquire()
self.__running = False
self.__lock.release()
self.root.destroy()
print(u"\n程序已退出...")
sys.exit()
# 停止搜索
def stop(self, evt):
self.__lock.acquire()
self.__running = False
self.__lock.release()
# 开始搜索
def search_path(self, evt=None):
# 开启线程
self.__lock.acquire()
self.__running = True
self.__lock.release()
while self.__running:
# 遍历每一只蚂蚁
for ant in self.ants:
# 搜索一条路径
ant.search_path()
# 与当前最优蚂蚁比较
if ant.total_distance < self.best_ant.total_distance:
# 更新最优解
self.best_ant = copy.deepcopy(ant)
# 更新信息素
self.__update_pheromone_gragh()
print(u"迭代次数:", self.iter, u"最佳路径总距离:", int(self.best_ant.total_distance))
# 连线
self.line(self.best_ant.path)
# 设置标题
self.title("TSP蚁群算法(n:随机初始 e:开始搜索 s:停止搜索 q:退出程序) 迭代次数: %d" % self.iter)
# 更新画布
self.canvas.update()
self.iter += 1
# 更新信息素
def __update_pheromone_gragh(self):
# 获取每只蚂蚁在其路径上留下的信息素
temp_pheromone = [[0.0 for col in range(city_num)] for raw in range(city_num)]
for ant in self.ants:
for i in range(1, city_num):
start, end = ant.path[i - 1], ant.path[i]
# 在路径上的每两个相邻城市间留下信息素,与路径总距离反比
temp_pheromone[start][end] += Q / ant.total_distance
temp_pheromone[end][start] = temp_pheromone[start][end]
# 更新所有城市之间的信息素,旧信息素衰减加上新迭代信息素
for i in range(city_num):
for j in range(city_num):
pheromone_graph[i][j] = pheromone_graph[i][j] * RHO + temp_pheromone[i][j]
# 主循环
def mainloop(self):
self.root.mainloop()
# ----------- 程序的入口处 -----------
if __name__ == '__main__':
TSP(tkinter.Tk()).mainloop()
选择下一个城市
1. total_prob含义
2. next_city含义
next_city为-1,并不代表没有可选择城市了,只是因为可选择的城市的概率为0罢了
A3C


将旧数据和新数据堆叠起来竖直堆叠:
假设有
竖直堆叠之后有:
"""
Asynchronous Advantage Actor Critic (A3C) with continuous action space, Reinforcement Learning.
The Pendulum example.
View more on my tutorial page: https://morvanzhou.github.io/tutorials/
Using:
tensorflow 1.8.0
gym 0.10.5
"""
import multiprocessing
import threading
import tensorflow as tf
import numpy as np
import gym
import os
import shutil
import matplotlib.pyplot as plt
GAME = 'Pendulum-v1'
OUTPUT_GRAPH = True
LOG_DIR = './log'
N_WORKERS = multiprocessing.cpu_count()
MAX_EP_STEP = 200
MAX_GLOBAL_EP = 1000
GLOBAL_NET_SCOPE = 'Global_Net'
UPDATE_GLOBAL_ITER = 10
GAMMA = 0.9
ENTROPY_BETA = 0.01
LR_A = 0.0001 # learning rate for actor
LR_C = 0.001 # learning rate for critic
GLOBAL_RUNNING_R = []
GLOBAL_EP = 0
env = gym.make(GAME) # 构建环境
N_S = env.observation_space.shape[0]
N_A = env.action_space.shape[0]
A_BOUND = [env.action_space.low, env.action_space.high]
class ACNet(object):
def __init__(self, scope, globalAC=None):
'''
:param scope:
:param globalAC: 判断是不是一个全局网络
'''
if scope == GLOBAL_NET_SCOPE: # get global network
'''构建一个计算图'''
with tf.variable_scope(scope):
self.s = tf.placeholder(tf.float32, [None, N_S], 'S') # 占位符,n行 N_S列 取名S
self.a_params, self.c_params = self._build_net(scope)[-2:]
else: # local net, calculate losses
with tf.variable_scope(scope):
self.s = tf.placeholder(tf.float32, [None, N_S], 'S')
self.a_his = tf.placeholder(tf.float32, [None, N_A], 'A')
self.v_target = tf.placeholder(tf.float32, [None, 1], 'Vtarget')
mu, sigma, self.v, self.a_params, self.c_params = self._build_net(scope)
td = tf.subtract(self.v_target, self.v, name='TD_error') # 减法
with tf.name_scope('c_loss'): # 评判家的损失,评判家用的Q-learning
self.c_loss = tf.reduce_mean(tf.square(td)) # 平方,求平均,来作为一个损失
with tf.name_scope('wrap_a_out'):
mu, sigma = mu * A_BOUND[1], sigma + 1e-4 # A_BOUND = [env.action_space.low, env.action_space.high]
# 简化写法
# 不同于C语言
normal_dist = tf.distributions.Normal(mu, sigma) # 定义一个正态分布mu均值,sigma方差
with tf.name_scope('a_loss'): # 演员的损失 期望梯度上升算法,loss函数”其实是 期望回报 的对数 log 导数1/x
log_prob = normal_dist.log_prob(self.a_his) # 计算value在定义的正态分布(mean,1)中对应的概率的对数
exp_v = log_prob * tf.stop_gradient(td) # 只要数值,不要梯度 带梯度的
entropy = normal_dist.entropy() # encourage exploration熵值
self.exp_v = ENTROPY_BETA * entropy + exp_v
self.a_loss = tf.reduce_mean(-self.exp_v)
with tf.name_scope('choose_a'): # use local params to choose action
self.A = tf.clip_by_value(tf.squeeze(normal_dist.sample(1), axis=[0, 1]), A_BOUND[0],
A_BOUND[1]) # 压缩到0-1
with tf.name_scope('local_grad'):
self.a_grads = tf.gradients(self.a_loss, self.a_params)
self.c_grads = tf.gradients(self.c_loss, self.c_params)
with tf.name_scope('sync'): # 同步操作
with tf.name_scope('pull'): # 从全局网络拉参数
self.pull_a_params_op = [l_p.assign(g_p) for l_p, g_p in zip(self.a_params, globalAC.a_params)]
self.pull_c_params_op = [l_p.assign(g_p) for l_p, g_p in zip(self.c_params, globalAC.c_params)]
with tf.name_scope('push'): # 把woker网络的梯度回传
self.update_a_op = OPT_A.apply_gradients(zip(self.a_grads, globalAC.a_params))
self.update_c_op = OPT_C.apply_gradients(zip(self.c_grads, globalAC.c_params))
def _build_net(self, scope):
w_init = tf.random_normal_initializer(0., .1) # 随机初始化权重
with tf.variable_scope('actor'):
l_a = tf.layers.dense(self.s, 200, tf.nn.relu6, kernel_initializer=w_init, name='la') # 全连接层
mu = tf.layers.dense(l_a, N_A, tf.nn.tanh, kernel_initializer=w_init, name='mu')
sigma = tf.layers.dense(l_a, N_A, tf.nn.softplus, kernel_initializer=w_init, name='sigma')
with tf.variable_scope('critic'):
l_c = tf.layers.dense(self.s, 100, tf.nn.relu6, kernel_initializer=w_init, name='lc')
v = tf.layers.dense(l_c, 1, kernel_initializer=w_init, name='v') # state value
a_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/actor')
c_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/critic')
return mu, sigma, v, a_params, c_params
def update_global(self, feed_dict): # run by a local
SESS.run([self.update_a_op, self.update_c_op], feed_dict) # local grads applies to global net
def pull_global(self): # run by a local
SESS.run([self.pull_a_params_op, self.pull_c_params_op])
def choose_action(self, s): # run by a local
s = s[np.newaxis, :]
return SESS.run(self.A, {self.s: s})
class Worker(object):
def __init__(self, name, globalAC):
self.env = gym.make(GAME).unwrapped # 定义了虚拟环境
self.name = name # worker的名称
self.AC = ACNet(name, globalAC) # worker网络,与全局网络是一致的
def work(self):
global GLOBAL_RUNNING_R, GLOBAL_EP
total_step = 1
buffer_s, buffer_a, buffer_r = [], [], [] # 观察、动作、返回值
while not COORD.should_stop() and GLOBAL_EP < MAX_GLOBAL_EP:
s = self.env.reset()
ep_r = 0
for ep_t in range(MAX_EP_STEP):
# if self.name == 'W_0':
# self.env.render()
a = self.AC.choose_action(s)
s_, r, done, info = self.env.step(a)
done = True if ep_t == MAX_EP_STEP - 1 else False
ep_r += r
buffer_s.append(s)
buffer_a.append(a)
buffer_r.append((r + 8) / 8) # normalize
# 每达到一定的步数或者步数用完就进行一次同步操作
if total_step % UPDATE_GLOBAL_ITER == 0 or done: # update global and assign to local net
if done:
v_s_ = 0 # terminal
else:
v_s_ = SESS.run(self.AC.v, {self.AC.s: s_[np.newaxis, :]})[0, 0]
buffer_v_target = []
for r in buffer_r[::-1]: # reverse buffer r,保证离输出近的×的gamma小
v_s_ = r + GAMMA * v_s_ # 反馈值按距离衰减
buffer_v_target.append(v_s_)
buffer_v_target.reverse()
buffer_s, buffer_a, buffer_v_target = np.vstack(buffer_s), np.vstack(buffer_a), np.vstack(
buffer_v_target)
feed_dict = {
self.AC.s: buffer_s,
self.AC.a_his: buffer_a,
self.AC.v_target: buffer_v_target,
}
self.AC.update_global(feed_dict) # 推送梯度,将子网络参数传递到全局网络,
buffer_s, buffer_a, buffer_r = [], [], [] # 清空缓存
self.AC.pull_global() # 重新获取全局参数
s = s_
total_step += 1
if done:
if len(GLOBAL_RUNNING_R) == 0: # record running episode reward
GLOBAL_RUNNING_R.append(ep_r)
else:
GLOBAL_RUNNING_R.append(0.9 * GLOBAL_RUNNING_R[-1] + 0.1 * ep_r)
print(
self.name,
"Ep:", GLOBAL_EP,
"| Ep_r: %i" % GLOBAL_RUNNING_R[-1],
)
GLOBAL_EP += 1
break
if __name__ == "__main__":
SESS = tf.Session() # 开计算图,tf必须在计算之前将图画好,不难动态的变更图,pytorch就可以动态的添加你需要的模块
# 创建worker
print(N_WORKERS)
with tf.device("/cpu:0"):
OPT_A = tf.train.RMSPropOptimizer(LR_A, name='RMSPropA') # 优化器
OPT_C = tf.train.RMSPropOptimizer(LR_C, name='RMSPropC') # 优化器
GLOBAL_AC = ACNet(GLOBAL_NET_SCOPE) # we only need its params,定义一个网络
workers = []
# Create worker
for i in range(N_WORKERS): # 根据有多少个线程来开多少个线程
i_name = 'W_%i' % i # worker name
workers.append(Worker(i_name, GLOBAL_AC))
COORD = tf.train.Coordinator() # 管理多线程
SESS.run(tf.global_variables_initializer())
if OUTPUT_GRAPH:
if os.path.exists(LOG_DIR):
shutil.rmtree(LOG_DIR)
tf.summary.FileWriter(LOG_DIR, SESS.graph)
worker_threads = []
# 绑定线程
for worker in workers:
job = lambda: worker.work()
t = threading.Thread(target=job)
t.start()
worker_threads.append(t)
COORD.join(worker_threads)
plt.plot(np.arange(len(GLOBAL_RUNNING_R)), GLOBAL_RUNNING_R)
plt.xlabel('step')
plt.ylabel('Total moving reward')
plt.show()
AC
"""
Actor-Critic using TD-error as the Advantage, Reinforcement Learning.
The cart pole example. Policy is oscillated.
View more on my tutorial page: https://morvanzhou.github.io/tutorials/
Using:
tensorflow 1.0
gym 0.8.0
"""
import numpy as np
import tensorflow as tf
import gym
np.random.seed(2)
#tf.set_random_seed(2) # reproducible
# Superparameters
OUTPUT_GRAPH = False
MAX_EPISODE = 3000
DISPLAY_REWARD_THRESHOLD = 200 # renders environment if total episode reward is greater then this threshold
MAX_EP_STEPS = 1000 # maximum time step in one episode
RENDER = False # rendering wastes time
GAMMA = 0.9 # reward discount in TD error
LR_A = 0.001 # learning rate for actor
LR_C = 0.01 # learning rate for critic
env = gym.make('CartPole-v0')
env.seed(1) # reproducible
env = env.unwrapped
N_F = env.observation_space.shape[0]
N_A = env.action_space.n
class Actor(object):
def __init__(self, sess, n_features, n_actions, lr=0.001):
self.sess = sess
self.s = tf.placeholder(tf.float32, [1, n_features], "state")
self.a = tf.placeholder(tf.int32, None, "act")
self.td_error = tf.placeholder(tf.float32, None, "td_error") # TD_error
with tf.variable_scope('Actor'):
l1 = tf.layers.dense(
inputs=self.s,
units=20, # number of hidden units
activation=tf.nn.relu,
kernel_initializer=tf.random_normal_initializer(0., .1), # weights
bias_initializer=tf.constant_initializer(0.1), # biases
name='l1'
)
self.acts_prob = tf.layers.dense(
inputs=l1,
units=n_actions, # output units
activation=tf.nn.softmax, # get action probabilities
kernel_initializer=tf.random_normal_initializer(0., .1), # weights
bias_initializer=tf.constant_initializer(0.1), # biases
name='acts_prob'
)
with tf.variable_scope('exp_v'):
log_prob = tf.log(self.acts_prob[0, self.a])
self.exp_v = tf.reduce_mean(log_prob * self.td_error) # advantage (TD_error) guided loss
with tf.variable_scope('train'):
self.train_op = tf.train.AdamOptimizer(lr).minimize(-self.exp_v) # minimize(-exp_v) = maximize(exp_v)
def learn(self, s, a, td):
s = s[np.newaxis, :]
feed_dict = {self.s: s, self.a: a, self.td_error: td}
_, exp_v = self.sess.run([self.train_op, self.exp_v], feed_dict)
return exp_v
def choose_action(self, s):
s = s[np.newaxis, :]
probs = self.sess.run(self.acts_prob, {self.s: s}) # get probabilities for all actions
return np.random.choice(np.arange(probs.shape[1]), p=probs.ravel()) # return a int
class Critic(object):
def __init__(self, sess, n_features, lr=0.01):
self.sess = sess
self.s = tf.placeholder(tf.float32, [1, n_features], "state")
self.v_ = tf.placeholder(tf.float32, [1, 1], "v_next")
self.r = tf.placeholder(tf.float32, None, 'r')
with tf.variable_scope('Critic'):
l1 = tf.layers.dense(
inputs=self.s,
units=20, # number of hidden units
activation=tf.nn.relu, # None
# have to be linear to make sure the convergence of actor.
# But linear approximator seems hardly learns the correct Q.
kernel_initializer=tf.random_normal_initializer(0., .1), # weights
bias_initializer=tf.constant_initializer(0.1), # biases
name='l1'
)
self.v = tf.layers.dense(
inputs=l1,
units=1, # output units
activation=None,
kernel_initializer=tf.random_normal_initializer(0., .1), # weights
bias_initializer=tf.constant_initializer(0.1), # biases
name='V'
)
with tf.variable_scope('squared_TD_error'):
self.td_error = self.r + GAMMA * self.v_ - self.v
self.loss = tf.square(self.td_error) # TD_error = (r+gamma*V_next) - V_eval
with tf.variable_scope('train'):
self.train_op = tf.train.AdamOptimizer(lr).minimize(self.loss)
def learn(self, s, r, s_):
s, s_ = s[np.newaxis, :], s_[np.newaxis, :]
v_ = self.sess.run(self.v, {self.s: s_})
td_error, _ = self.sess.run([self.td_error, self.train_op],
{self.s: s, self.v_: v_, self.r: r})
return td_error
tf.compat.v1.disable_eager_execution()
sess = tf.compat.v1.Session()
actor = Actor(sess, n_features=N_F, n_actions=N_A, lr=LR_A)
critic = Critic(sess, n_features=N_F, lr=LR_C) # we need a good teacher, so the teacher should learn faster than the actor
sess.run(tf.global_variables_initializer())
if OUTPUT_GRAPH:
tf.summary.FileWriter("logs/", sess.graph)
for i_episode in range(MAX_EPISODE):
s = env.reset()
t = 0
track_r = []
while True:
if RENDER: env.render()
a = actor.choose_action(s)
s_, r, done, info = env.step(a)
if done: r = -20
track_r.append(r)
td_error = critic.learn(s, r, s_) # gradient = grad[r + gamma * V(s_) - V(s)]
actor.learn(s, a, td_error) # true_gradient = grad[logPi(s,a) * td_error]
s = s_
t += 1
if done or t >= MAX_EP_STEPS:
ep_rs_sum = sum(track_r)
if 'running_reward' not in globals():
running_reward = ep_rs_sum
else:
running_reward = running_reward * 0.95 + ep_rs_sum * 0.05
if running_reward > DISPLAY_REWARD_THRESHOLD: RENDER = True # rendering
print("episode:", i_episode, " reward:", int(running_reward))
break
遗传算法
遗传算法解决旅行商问题

from itertools import permutations
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from itertools import combinations, permutations
# matplotlib inline
def fitnessFunction(pop, num, city_num, x_position_add_end, y_position_add_end):
"""适应度函数,计算每个排列的适应度,并保存到pop矩阵第二维的最后一项"""
'''
num: 群体的数目
'''
for x1 in range(num):
square_sum = 0
for x2 in range(city_num):
square_sum += (x_position_add_end[int(pop[x1][x2])] - x_position_add_end[int(pop[x1][x2 + 1])]) ** 2 + \
(y_position_add_end[int(pop[x1][x2])] - y_position_add_end[int(pop[x1][x2 + 1])]) ** 2
# print(round(1/np.sqrt(square_sum),7))
pop[x1][-1] = round(1 / np.sqrt(square_sum), 7) # round四舍五入 7位,适应度为距离的倒数
def choiceFuction(pop):
"""
这里的做法:比如A当前种群中的最优解,B为经过交叉、变异后的最差解,把A作为最当前代中的最优解保存下来作为这一代的最优解,同时A也参与交叉
和变异。经过交叉、变异后的最差解为B,那么我再用A替代B。
:argument pop矩阵
:return 本代适应度最低的个体的索引值和本代适应度最高的个体
"""
yield np.argmin(pop[:, -1]) # return 最差群体
yield pop[np.argmax(pop[:, -1])] # return 最好群体
def choice(pop, num, city_num, x_position_add_end, y_position_add_end, b):
fitnessFunction(pop, num, city_num, x_position_add_end, y_position_add_end)
c, d = choiceFuction(pop) # c是最差的,d是最好的群体
# 上一代的最优值替代本代中的最差值
pop[c] = b
return pop
def drawPic(maxFitness, x_position, y_position, i):
'''
根据两个点画一条直线
:param maxFitness:
:param x_position:
:param y_position:
:param i:
:return:
'''
index = np.array(maxFitness[:-1], dtype=np.int32)
x_position_add_end = np.append(x_position[index], x_position[[index[0]]])
y_position_add_end = np.append(y_position[index], y_position[[index[0]]])
fig = plt.figure()
plt.plot(x_position_add_end, y_position_add_end, '-o')
plt.xlabel('x', fontsize=16)
plt.ylabel('y', fontsize=16)
plt.title('{iter}'.format(iter=i))
plt.show()
def matuingFuction(pop, pc, city_num, pm, num):
mating_matrix = np.array(1 - (np.random.rand(num) > pc), dtype=np.bool) # 交配矩阵,如果为true则进行交配
a = list(pop[mating_matrix][:, :-1]) # 进行交配的个体
b = list(pop[np.array(1 - mating_matrix, dtype=bool)][:, :-1]) # 未进行交配的个体,直接放到下一代
b = [list(i) for i in b] # 对b进行类型转换,避免下面numpy.array 没有index属性
# print(a)
if len(a) % 2 != 0:
b.append(a.pop())
# print('ab的长度:',len(a),len(b))
for i in range(int(len(a) / 2)):
# 随机初始化两个交配点,这里写得不好,这边的两个点初始化都是一个在中间位置偏左,一个在中间位置偏右 1 2 3 4
p1 = np.random.randint(1, int(city_num / 2) + 1)
p2 = np.random.randint(int(city_num / 2) + 1, city_num)
# 这个交换只能交换中间,很局限
x1 = list(a.pop())
x2 = list(a.pop())
matuting(x1, x2, p1, p2) # 进行群体交换
# 交配之后产生的个体进行一定概率上的变异
variationFunction(x1, pm, city_num)
variationFunction(x2, pm, city_num)
b.append(x1)
b.append(x2)
zero = np.zeros((num, 1))
# print('b的形状:',len(b))
temp = np.column_stack((b, zero))
return temp
# 0 1 理论上最少需要多少位的映射 10个城市2^10
def matuting(x1, x2, p1, p2): # 比较糟糕
# 以下进行交配
# 左边交换位置
temp = x1[:p1]
x1[:p1] = x2[:p1]
x2[:p1] = temp
# 右边交换位置
temp = x1[p2:]
x1[p2:] = x2[p2:]
x2[p2:] = temp
# 寻找重复的元素
center1 = x1[p1:p2]
center2 = x2[p1:p2]
while True: # x1左边
for i in x1[:p1]:
if i in center1:
# print(center1.index(i)) # 根据值找到索引
x1[x1[:p1].index(i)] = center2[center1.index(i)]
break
if np.intersect1d(x1[:p1], center1).size == 0: # 如果不存在交集,则循环结束
break
while True: # x1右边
for i in x1[p2:]:
if i in center1:
# print(center1.index(i)) # 根据值找到索引
x1[x1[p2:].index(i) + p2] = center2[center1.index(i)]
# print(x1)
break
if np.intersect1d(x1[p2:], center1).size == 0: # 如果不存在交集,则循环结束
break
while True: # x2左边
for i in x2[:p1]:
if i in center2:
# print(center2.index(i)) # 根据值找到索引
x2[x2[:p1].index(i)] = center1[center2.index(i)]
break
if np.intersect1d(x2[:p1], center2).size == 0: # 如果不存在交集,则循环结束
break
while True: # x2右边
for i in x2[p2:]:
if i in center2:
# print(center2.index(i)) # 根据值找到索引
x2[x2[p2:].index(i) + p2] = center1[center2.index(i)]
# print(x2)
break
if np.intersect1d(x2[p2:], center2).size == 0: # 如果不存在交集,则循环结束
break
def variationFunction(list_a, pm, city_num):
'''变异函数'''
if np.random.rand() < pm:
p1 = np.random.randint(1, int(city_num / 2) + 1)
p2 = np.random.randint(int(city_num / 2) + 1, city_num)
# print(p1,p2)
temp = list_a[p1:p2]
temp.reverse() # 这里变异就是将p1-p2这个片段反转
list_a[p1:p2] = temp
# print(list_a)
def main():
# 初始化
# plt.ion()
pop = [] # 存放访问顺序 和 每个个体适应度
num = 250 # 初始化群体的数目
city_num = 10 # 城市数目
pc = 0.9 # 每个个体的交配概率
pm = 0.2 # 每个个体的变异概率
x_position = np.random.randint(0, 100, size=city_num)
y_position = np.random.randint(0, 100, size=city_num)
x_position_add_end = np.append(x_position, x_position[0]) # 城市的位置x坐标
y_position_add_end = np.append(y_position, y_position[0]) # 城市的位置y坐标
for i in range(num):
pop.append(np.random.permutation(np.arange(0, city_num))) # 随机产生顺序
zero = np.zeros((num, 1))
pop = np.column_stack((pop, zero)) # 矩阵的拼接,存放 访问城市的顺序 和 适应度
fitnessFunction(pop, num, city_num, x_position_add_end, y_position_add_end) # 适应度函数计算每个个体的适应度
for i in range(180):
a, b = choiceFuction(pop) # a是最差群体, b是最好的群体
# print('索引值和适应度最大的个体:',a,b)
# pop[a]=b
if (i + 1) % 10 == 0: # 每隔10次画一次图
# plt.clf() # 清除图像
# a 为当代适应度最小的个体的索引,b为当代适应度最大的个体,这边要保留的是b
drawPic(b, x_position, y_position, i + 1) # 根据本代中的适应度最大的个体画图
# plt.pause(0.02)
pop_temp = matuingFuction(pop, pc, city_num, pm, num) # 交配变异
pop = choice(pop_temp, num, city_num, x_position_add_end, y_position_add_end, b)
# plt.ioff()
# plt.show()
main()
遗传算法
import math
import sys
if sys.version_info.major < 3:
import Tkinter
else:
import tkinter as Tkinter
from sko import GA
class TSP_WIN(object):
def __init__(self, aRoot, aLifeCount=100, aWidth=560, aHeight=330):
self.root = aRoot
self.lifeCount = aLifeCount
self.width = aWidth
self.height = aHeight
self.canvas = Tkinter.Canvas(
self.root,
width=self.width,
height=self.height,
)
self.canvas.pack(expand=Tkinter.YES, fill=Tkinter.BOTH)
self.bindEvents()
self.initCitys()
self.new()
self.title("TSP")
def initCitys(self):
self.citys = []
# 中国34城市经纬度
self.citys.append((116.46, 39.92))
self.citys.append((117.2, 39.13))
self.citys.append((121.48, 31.22))
self.citys.append((106.54, 29.59))
self.citys.append((91.11, 29.97))
self.citys.append((87.68, 43.77))
self.citys.append((106.27, 38.47))
self.citys.append((111.65, 40.82))
self.citys.append((108.33, 22.84))
self.citys.append((126.63, 45.75))
self.citys.append((125.35, 43.88))
self.citys.append((123.38, 41.8))
self.citys.append((114.48, 38.03))
self.citys.append((112.53, 37.87))
self.citys.append((101.74, 36.56))
self.citys.append((117, 36.65))
self.citys.append((113.6, 34.76))
self.citys.append((118.78, 32.04))
self.citys.append((117.27, 31.86))
self.citys.append((120.19, 30.26))
self.citys.append((119.3, 26.08))
self.citys.append((115.89, 28.68))
self.citys.append((113, 28.21))
self.citys.append((114.31, 30.52))
self.citys.append((113.23, 23.16))
self.citys.append((121.5, 25.05))
self.citys.append((110.35, 20.02))
self.citys.append((103.73, 36.03))
self.citys.append((108.95, 34.27))
self.citys.append((104.06, 30.67))
self.citys.append((106.71, 26.57))
self.citys.append((102.73, 25.04))
self.citys.append((114.1, 22.2))
self.citys.append((113.33, 22.13))
# 坐标变换
minX, minY = self.citys[0][0], self.citys[0][1]
maxX, maxY = minX, minY
for city in self.citys[1:]:
if minX > city[0]:
minX = city[0]
if minY > city[1]:
minY = city[1]
if maxX < city[0]:
maxX = city[0]
if maxY < city[1]:
maxY = city[1]
w = maxX - minX
h = maxY - minY
xoffset = 30
yoffset = 30
ww = self.width - 2 * xoffset
hh = self.height - 2 * yoffset
xx = ww / float(w)
yy = hh / float(h)
r = 5
self.nodes = []
self.nodes2 = []
for city in self.citys:
x = (city[0] - minX) * xx + xoffset
y = hh - (city[1] - minY) * yy + yoffset
self.nodes.append((x, y))
node = self.canvas.create_oval(x - r, y - r, x + r, y + r,
fill="#ff0000",
outline="#000000",
tags="node", )
self.nodes2.append(node)
def distance(self, order):
distance = 0.0
for i in range(-1, len(self.citys) - 1):
index1, index2 = order[i], order[i + 1]
city1, city2 = self.citys[index1], self.citys[index2]
distance += math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
return distance
def matchFun(self):
return lambda life: 1.0 / self.distance(life.gene)
def title(self, text):
self.root.title(text)
def line(self, order):
self.canvas.delete("line")
for i in range(-1, len(order) - 1):
p1 = self.nodes[order[i]]
p2 = self.nodes[order[i + 1]]
self.canvas.create_line(p1, p2, fill="#000000", tags="line")
def bindEvents(self):
self.root.bind("n", self.new)
self.root.bind("g", self.start)
self.root.bind("s", self.stop)
def new(self, evt=None):
self.isRunning = False
order = range(len(self.citys))
self.line(order)
self.ga = GA_TSP(CrossRate=0.7,
MutationRage=0.02,
LifeCount=self.lifeCount,
GeneLenght=len(self.citys),
MatchFun=self.matchFun())
def start(self, evt=None):
self.isRunning = True
while self.isRunning:
self.ga.next()
distance = self.distance(self.ga.best.gene)
self.line(self.ga.best.gene)
self.title("TSP-gen: %d" % self.ga.generation)
self.canvas.update()
def stop(self, evt=None):
self.isRunning = False
def mainloop(self):
self.root.mainloop()
def main():
# tsp = TSP()
# tsp.run(10000)
tsp = TSP_WIN(Tkinter.Tk())
tsp.mainloop()
if __name__ == '__main__':
main()
VGG
mode.py文件
import torch.nn as nn
import torch
# official pretrain weights
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth'
}
class VGG(nn.Module):
def __init__(self, features, num_classes=1000, init_weights=False):
'''
:param features: 特征提取
:param num_classes: 定义分类个数,默认为1000
:param init_weights: 是否需要权重初始化
'''
super(VGG, self).__init__()
self.features = features
self.classifier = nn.Sequential(
nn.Linear(512 * 7 * 7, 4096), # 全连接层
nn.ReLU(True), # 激活函数
nn.Dropout(p=0.5), # 如果得到的数据是离群点,我就随机丢掉50%的数据
# pytorch的p和TensorFlow的keep_prob代表的正好相反
nn.Linear(4096, 4096),
nn.ReLU(True),
nn.Dropout(p=0.5),
nn.Linear(4096, num_classes) # 最后层输入的个数是4096,num_classes是最后分层多少类
)
if init_weights:
self._initialize_weights()
def forward(self, x):
'''
前向传播模块
:param x:
:return:
'''
# N x 3 x 224 x 224,卷积层
x = self.features(x)
# N x 512 x 7 x 7, 展平到全连接层
x = torch.flatten(x, start_dim=1) # 利用第一维展平
# N x 512*7*7
x = self.classifier(x)
return x
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d): # 是继承的nn的卷积层
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear): # 继承的nn的全连接层
nn.init.xavier_uniform_(m.weight)
# nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
def make_features(cfg: list):
'''
特征提取模块
:param cfg: 是一个列表,代表选用哪一个模型
:return:
'''
layers = []
in_channels = 3
for v in cfg:
# 判断需要最大 池化层 还是 卷积层
if v == "M":
# 为池化层
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
# 为卷积层
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
layers += [conv2d, nn.ReLU(True)] # Relu为激活函数
in_channels = v
return nn.Sequential(*layers) # 合并提取,将模型聚合到一块
cfgs = {
# 配置文件参数
'vgg11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
# 64 代表卷积核的个数,M代表最大池化层
'vgg13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'vgg16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
'vgg19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}
def vgg(model_name="vgg16", **kwargs):
'''
选择vgg16模型
:param model_name:
:param kwargs:
:return:
'''
assert model_name in cfgs, "Warning: model number {} not in cfgs dict!".format(model_name)
cfg = cfgs[model_name]
model = VGG(make_features(cfg), **kwargs)
return model
全连接层参数

# in_features由输入张量的形状决定,out_features则决定了输出张量的形状
connected_layer = nn.Linear(in_features = 64*64*3, out_features = 1)
初始化权重参数
基本思想是通过网络层时,输入和输出的方差相同,包括前向传播和后向传播。具体看以下博文:
- 为什么需要Xavier 初始化?

简答的说就是:
- 如果初始化值很小,那么随着层数的传递,方差就会趋于0,此时输入值 也变得越来越小,在sigmoid上就是在0附近,接近于线性,失去了非线性
- 如果初始值很大,那么随着层数的传递,方差会迅速增加,此时输入值变得很大,而sigmoid在大输入值写倒数趋近于0,反向传播时会遇到梯度消失的问题
所以,
就是在每一层网络保证输入和输出的方差相同。
https://blog.csdn.net/dss_dssssd/article/details/83959474
最大池化层
1.函数语法格式和作用
作用:
对邻域内特征点取最大
减小卷积层参数误差造成估计均值的偏移的误差,更多的保留纹理信息。
MaxPool2d(kernel_size, stride=None, padding=0,
dilation=1, return_indices=False, ceil_mode=False)

https://blog.csdn.net/weixin_38481963/article/details/109962715 Pytorch的nn.Conv2d()详解
nn.Conv2d()
nn.Conv2d()的使用、形参与隐藏的权重参数
二维卷积应该是最常用的卷积方式了,在Pytorch的nn模块中,封装了nn.Conv2d()类作为二维卷积的实现。使用方法和普通的类一样,先实例化再使用。下面是一个只有一层二维卷积的神经网络,作为nn.Conv2d()方法的使用简介:


https://blog.csdn.net/qq_42079689/article/details/102642610 Pytorch的nn.Conv2d()详解
predict文件中代码
import os
import json
import torch
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
from model import vgg
def main():
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# device = torch.device("cpu")
print("using {} device.".format(device))
data_transform = transforms.Compose(
[transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# load image,添加预测图像的路径
img_path = "data_set/flower_data/val/tulips/14054827092_f359f5fcbd_m.jpg"
assert os.path.exists(img_path), "file: '{}' dose not exist.".format(img_path)
img = Image.open(img_path)
plt.imshow(img) # 函数负责对图像进行处理,并显示其格式,但是不能显示。其后跟着plt.show()才能显示出来。
# [N, C, H, W]
img = data_transform(img)
# expand batch dimension
img = torch.unsqueeze(img, dim=0)
# read class_indict
json_path = './class_indices.json'
assert os.path.exists(json_path), "file: '{}' dose not exist.".format(json_path)
json_file = open(json_path, "r")
class_indict = json.load(json_file)
# create model
model = vgg(model_name="vgg16", num_classes=5).to(device)
# load model weights
weights_path = "./best_model/vgg16Net.pth"
assert os.path.exists(weights_path), "file: '{}' dose not exist.".format(weights_path)
model.load_state_dict(torch.load(weights_path, map_location=device))
model.eval()
with torch.no_grad():
# predict class
output = torch.squeeze(model(img.to(device))).cpu()
predict = torch.softmax(output, dim=0)
predict_cla = torch.argmax(predict).numpy()
# 展示出预测图像的分类结果
print_res = "class: {} prob: {:.3}".format(class_indict[str(predict_cla)],
predict[predict_cla].numpy())
plt.title(print_res)
print(print_res)
plt.show()
if __name__ == '__main__':
main()









https://blog.csdn.net/zfhsfdhdfajhsr/article/details/124141658 torch.nn.softmax介绍
train文件
import os # 打开文件用的
import json
import torch
import torch.nn as nn
from torchvision import transforms, datasets # torch有一些专门的格式,是用来转化格式的
import torch.optim as optim
from tqdm import tqdm # 加载精度
from model import vgg
from PIL import ImageFile # 打开我想要的图片
ImageFile.LOAD_TRUNCATED_IMAGES = True
def main():
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
print("using {} device.".format(device))
# data_transform 图像预处理模块
data_transform = {
# 转变训练集格式
"train": transforms.Compose([transforms.RandomResizedCrop(224), # 随机裁剪一个area然后再resize
transforms.RandomHorizontalFlip(), # 翻转
transforms.ToTensor(), # 转换成Tensor格式
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]), # 需不需要把输入的图像权重初始化一下
# 转变验证集格式
"val": transforms.Compose([transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])}
data_root = os.path.abspath(os.path.join(os.getcwd(), "./..")) # get data root path
# os.getcwd() 获取当前工作目录
image_path = os.path.join(data_root, "Test3_vggnet/data_set", "flower_data") # flower data set path
# "Test3_vggnet/data_set" 为训练集的路径
assert os.path.exists(image_path), "{} path does not exist.".format(image_path)
train_dataset = datasets.ImageFolder(root=os.path.join(image_path, "train"),
transform=data_transform["train"])
train_num = len(train_dataset)
# {'daisy':0, 'dandelion':1, 'roses':2, 'sunflower':3, 'tulips':4}
flower_list = train_dataset.class_to_idx
cla_dict = dict((val, key) for key, val in flower_list.items())
# write dict into json file
json_str = json.dumps(cla_dict, indent=4)
# json.dumps:将json格式转化成字符串 indent是缩进
with open('class_indices.json', 'w') as json_file:
json_file.write(json_str)
batch_size = 32 # 一次抓多少图片放到网络中训练
nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]) # number of workers
print('Using {} dataloader workers every process'.format(nw))
# 加载训练数据
train_loader = torch.utils.data.DataLoader(train_dataset,
batch_size=batch_size, shuffle=True, # shuffle是否需要打乱输入
num_workers=0) # num_workers训练线程数,window只能为0,linux就可以为其他了
validate_dataset = datasets.ImageFolder(root=os.path.join(image_path, "val"),
transform=data_transform["val"])
val_num = len(validate_dataset)
validate_loader = torch.utils.data.DataLoader(validate_dataset,
batch_size=batch_size, shuffle=False,
num_workers=0)
print("using {} images for training, {} images for validation.".format(train_num,
val_num))
# test_data_iter = iter(validate_loader)
# test_image, test_label = test_data_iter.next()
model_name = "vgg16"
# 使用VGG16模型来训练,分类数量为5,
net = vgg(model_name=model_name, num_classes=5, init_weights=True)
net.to(device) # 调用现在的设备去运行
loss_function = nn.CrossEntropyLoss() # 损失函数为交叉熵损失
optimizer = optim.Adam(net.parameters(), lr=0.01)
# lr=0.01是学习率,就是步长小步长大的问题,影响收敛速率,如果设置的大就可能一直震荡
# 最好的情况是,学习率先大一点,大范围跳,然后逐步降低,小范围跳
# # 定义学习率为0.01, 使用Adam优化器
epochs = 10 # 初始化训练集的迭代次数
best_acc = 0.0
save_path = './{}Net.pth'.format(model_name)
train_steps = len(train_loader)
for epoch in range(epochs):
# train
net.train()
running_loss = 0.0
train_bar = tqdm(train_loader)
for step, data in enumerate(train_bar):
images, labels = data
optimizer.zero_grad() # 将梯度初始化为零
outputs = net(images.to(device))
loss = loss_function(outputs, labels.to(device))
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
# 记录下训练和核验证集的损失
train_bar.desc = "train epoch[{}/{}] loss:{:.3f}".format(epoch + 1,
epochs,
loss)
# validate
net.eval()
acc = 0.0 # accumulate accurate number / epoch
with torch.no_grad():
val_bar = tqdm(validate_loader)
for val_data in val_bar:
val_images, val_labels = val_data
outputs = net(val_images.to(device))
predict_y = torch.max(outputs, dim=1)[1]
acc += torch.eq(predict_y, val_labels.to(device)).sum().item()
val_accurate = acc / val_num
# 记录下训练集和验证集的准确度
print('[epoch %d] train_loss: %.3f val_accuracy: %.3f' %
(epoch + 1, running_loss / train_steps, val_accurate))
if val_accurate > best_acc:
best_acc = val_accurate
torch.save(net.state_dict(), save_path)
print('Finished Training')
if __name__ == '__main__':
main()
RNN


"""
View more, visit my tutorial page: https://mofanpy.com/tutorials/
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
Dependencies:
torch: 0.4
matplotlib
torchvision
"""
import torch
from torch import nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
# torch.manual_seed(1) # reproducible
# Hyper Parameters
EPOCH = 1 # train the training data n times, to save time, we just train 1 epoch
BATCH_SIZE = 64
# 表示单次传递给程序用以训练的参数个数。比如我们的训练集有1000个数据。
# 这是如果我们设置batch_size=100,那么程序首先会用数据集中的前100个参数,即第1-100个数据来训练模型。
# 当训练完成后更新权重,再使用第101-200的个数据训练,直至第十次使用完训练集中的1000个数据后停止。
TIME_STEP = 28 # rnn time step / image height
INPUT_SIZE = 28 # rnn input size / image width
LR = 0.01 # learning rate
DOWNLOAD_MNIST = True # set to True if haven't download the data
# Mnist digital dataset
train_data = dsets.MNIST(
root='./mnist/',
train=True, # this is training data
transform=transforms.ToTensor(), # Converts a PIL.Image or numpy.ndarray to
# torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
# ToTensor() 能够把灰度范围从0-255变换到0-1之间,
download=DOWNLOAD_MNIST, # download it if you don't have it
)
# plot one example
print(train_data.train_data.size()) # (60000, 28, 28)
print(train_data.train_labels.size()) # (60000)
plt.imshow(train_data.train_data[0].numpy(), cmap='gray')
plt.title('%i' % train_data.train_labels[0])
plt.show()
# Data Loader for easy mini-batch return in training
train_loader = torch.utils.data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)
# convert test data into Variable, pick 2000 samples to speed up testing
test_data = dsets.MNIST(root='./mnist/', train=False, transform=transforms.ToTensor())
test_x = test_data.test_data.type(torch.FloatTensor)[:2000]/255. # shape (2000, 28, 28) value in range(0,1)
test_y = test_data.test_labels.numpy()[:2000] # covert to numpy array
class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.rnn = nn.LSTM( # if use nn.RNN(), it hardly learns
input_size=INPUT_SIZE,
hidden_size=64, # rnn hidden unit
num_layers=1, # number of rnn layer
batch_first=True, # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
)
self.out = nn.Linear(64, 10)
def forward(self, x):
# x shape (batch, time_step, input_size)
# r_out shape (batch, time_step, output_size)
# h_n shape (n_layers, batch, hidden_size)
# h_c shape (n_layers, batch, hidden_size)
r_out, (h_n, h_c) = self.rnn(x, None) # None represents zero initial hidden state
# choose r_out at the last time step
out = self.out(r_out[:, -1, :])
return out
rnn = RNN()
print(rnn)
optimizer = torch.optim.Adam(rnn.parameters(), lr=LR) # optimize all cnn parameters
loss_func = nn.CrossEntropyLoss() # the target label is not one-hotted
# training and testing
for epoch in range(EPOCH):
for step, (b_x, b_y) in enumerate(train_loader): # gives batch data
b_x = b_x.view(-1, 28, 28) # reshape x to (batch, time_step, input_size)
output = rnn(b_x) # rnn output
loss = loss_func(output, b_y) # cross entropy loss
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients
if step % 50 == 0:
test_output = rnn(test_x) # (samples, time_step, input_size)
pred_y = torch.max(test_output, 1)[1].data.numpy()
accuracy = float((pred_y == test_y).astype(int).sum()) / float(test_y.size)
print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)
# print 10 predictions from test data
test_output = rnn(test_x[:10].view(-1, 28, 28))
pred_y = torch.max(test_output, 1)[1].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:10], 'real number')

