tensorflow训练打游戏ai

python3,所需模块请自行补齐

# coding=utf8

import pygame
import random
from pygame.locals import *
import numpy as np
from collections import deque
import tensorflow as tf  # http://blog.topspeedsnail.com/archives/10116
import cv2               # http://blog.topspeedsnail.com/archives/4755

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

SCREEN_SIZE = [320, 400]
BAR_SIZE = [50, 5]
BALL_SIZE = [15, 15]

# 神经网络的输出
MOVE_STAY = [1, 0, 0]
MOVE_LEFT = [0, 1, 0]
MOVE_RIGHT = [0, 0, 1]


class Game(object):
    def __init__(self):
        pygame.init()
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(SCREEN_SIZE)
        pygame.display.set_caption('Simple Game')

        self.ball_pos_x = SCREEN_SIZE[0] // 2 - BALL_SIZE[0] / 2
        self.ball_pos_y = SCREEN_SIZE[1] // 2 - BALL_SIZE[1] / 2

        self.ball_dir_x = -1  # -1 = left 1 = right
        self.ball_dir_y = -1  # -1 = up   1 = down
        self.ball_pos = pygame.Rect(
            self.ball_pos_x, self.ball_pos_y, BALL_SIZE[0], BALL_SIZE[1])

        self.bar_pos_x = SCREEN_SIZE[0] // 2 - BAR_SIZE[0] // 2
        self.bar_pos = pygame.Rect(
            self.bar_pos_x, SCREEN_SIZE[1] - BAR_SIZE[1], BAR_SIZE[0], BAR_SIZE[1])

    # action是MOVE_STAY、MOVE_LEFT、MOVE_RIGHT
    # ai控制棒子左右移动;返回游戏界面像素数和对应的奖励。(像素->奖励->强化棒子往奖励高的方向移动)
    def step(self, action):

        if action == MOVE_LEFT:
            self.bar_pos_x = self.bar_pos_x - 2
        elif action == MOVE_RIGHT:
            self.bar_pos_x = self.bar_pos_x + 2
        else:
            pass
        if self.bar_pos_x < 0:
            self.bar_pos_x = 0
        if self.bar_pos_x > SCREEN_SIZE[0] - BAR_SIZE[0]:
            self.bar_pos_x = SCREEN_SIZE[0] - BAR_SIZE[0]

        self.screen.fill(BLACK)
        self.bar_pos.left = self.bar_pos_x
        pygame.draw.rect(self.screen, WHITE, self.bar_pos)

        self.ball_pos.left += self.ball_dir_x * 2
        self.ball_pos.bottom += self.ball_dir_y * 3
        pygame.draw.rect(self.screen, WHITE, self.ball_pos)

        if self.ball_pos.top <= 0 or self.ball_pos.bottom >= (SCREEN_SIZE[1] - BAR_SIZE[1] + 1):
            self.ball_dir_y = self.ball_dir_y * -1
        if self.ball_pos.left <= 0 or self.ball_pos.right >= (SCREEN_SIZE[0]):
            self.ball_dir_x = self.ball_dir_x * -1

        reward = 0
        if self.bar_pos.top <= self.ball_pos.bottom and (self.bar_pos.left < self.ball_pos.right and self.bar_pos.right > self.ball_pos.left):
            reward = 1    # 击中奖励
        elif self.bar_pos.top <= self.ball_pos.bottom and (self.bar_pos.left > self.ball_pos.right or self.bar_pos.right < self.ball_pos.left):
            reward = -1   # 没击中惩罚

        # 获得游戏界面像素
        screen_image = pygame.surfarray.array3d(pygame.display.get_surface())
        pygame.display.update()
        # 返回游戏界面像素和对应的奖励
        return reward, screen_image


# learning_rate
LEARNING_RATE = 0.99
# 更新梯度
INITIAL_EPSILON = 1.0
FINAL_EPSILON = 0.05
# 测试观测次数
EXPLORE = 500000
OBSERVE = 50000
# 存储过往经验大小
REPLAY_MEMORY = 500000

BATCH = 100

# 输出层神经元数。代表3种操作-MOVE_STAY:[1, 0, 0]  MOVE_LEFT:[0, 1, 0]  MOVE_RIGHT:[0, 0, 1]
output = 3
input_image = tf.placeholder("float", [None, 80, 100, 4])  # 游戏像素
action = tf.placeholder("float", [None, output])     # 操作

# 定义CNN-卷积神经网络 参考:http://blog.topspeedsnail.com/archives/10451


def convolutional_neural_network(input_image):
    weights = {'w_conv1': tf.Variable(tf.zeros([8, 8, 4, 32])),
               'w_conv2': tf.Variable(tf.zeros([4, 4, 32, 64])),
               'w_conv3': tf.Variable(tf.zeros([3, 3, 64, 64])),
               'w_fc4': tf.Variable(tf.zeros([3456, 784])),
               'w_out': tf.Variable(tf.zeros([784, output]))}

    biases = {'b_conv1': tf.Variable(tf.zeros([32])),
              'b_conv2': tf.Variable(tf.zeros([64])),
              'b_conv3': tf.Variable(tf.zeros([64])),
              'b_fc4': tf.Variable(tf.zeros([784])),
              'b_out': tf.Variable(tf.zeros([output]))}

    conv1 = tf.nn.relu(tf.nn.conv2d(input_image, weights['w_conv1'], strides=[
                       1, 4, 4, 1], padding="VALID") + biases['b_conv1'])
    conv2 = tf.nn.relu(tf.nn.conv2d(conv1, weights['w_conv2'], strides=[
                       1, 2, 2, 1], padding="VALID") + biases['b_conv2'])
    conv3 = tf.nn.relu(tf.nn.conv2d(conv2, weights['w_conv3'], strides=[
                       1, 1, 1, 1], padding="VALID") + biases['b_conv3'])
    conv3_flat = tf.reshape(conv3, [-1, 3456])
    fc4 = tf.nn.relu(tf.matmul(conv3_flat, weights['w_fc4']) + biases['b_fc4'])

    output_layer = tf.matmul(fc4, weights['w_out']) + biases['b_out']
    return output_layer

# 深度强化学习入门: https://www.nervanasys.com/demystifying-deep-reinforcement-learning/
# 训练神经网络


def train_neural_network(input_image):
    predict_action = convolutional_neural_network(input_image)

    argmax = tf.placeholder("float", [None, output])
    gt = tf.placeholder("float", [None])

    action = tf.reduce_sum(tf.multiply(predict_action, argmax), reduction_indices=1)
    cost = tf.reduce_mean(tf.square(action - gt))
    optimizer = tf.train.AdamOptimizer(1e-6).minimize(cost)

    game = Game()
    D = deque()

    _, image = game.step(MOVE_STAY)
    # 转换为灰度值
    image = cv2.cvtColor(cv2.resize(image, (100, 80)), cv2.COLOR_BGR2GRAY)
    # 转换为二值
    ret, image = cv2.threshold(image, 1, 255, cv2.THRESH_BINARY)
    input_image_data = np.stack((image, image, image, image), axis=2)

    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())

        saver = tf.train.Saver()

        n = 0
        epsilon = INITIAL_EPSILON
        while True:
            action_t = predict_action.eval(
                feed_dict={input_image: [input_image_data]})[0]

            argmax_t = np.zeros([output], dtype=np.int)
            if(random.random() <= INITIAL_EPSILON):
                maxIndex = random.randrange(output)
            else:
                maxIndex = np.argmax(action_t)
            argmax_t[maxIndex] = 1
            if epsilon > FINAL_EPSILON:
                epsilon -= (INITIAL_EPSILON - FINAL_EPSILON) / EXPLORE

            # for event in pygame.event.get():  macOS需要事件循环,否则白屏
            #	if event.type == QUIT:
            #		pygame.quit()
            #		sys.exit()
            reward, image = game.step(list(argmax_t))

            image = cv2.cvtColor(cv2.resize(
                image, (100, 80)), cv2.COLOR_BGR2GRAY)
            ret, image = cv2.threshold(image, 1, 255, cv2.THRESH_BINARY)
            image = np.reshape(image, (80, 100, 1))
            input_image_data1 = np.append(
                image, input_image_data[:, :, 0:3], axis=2)

            D.append((input_image_data, argmax_t, reward, input_image_data1))

            if len(D) > REPLAY_MEMORY:
                D.popleft()

            if n > OBSERVE:
                minibatch = random.sample(D, BATCH)
                input_image_data_batch = [d[0] for d in minibatch]
                argmax_batch = [d[1] for d in minibatch]
                reward_batch = [d[2] for d in minibatch]
                input_image_data1_batch = [d[3] for d in minibatch]

                gt_batch = []

                out_batch = predict_action.eval(
                    feed_dict={input_image: input_image_data1_batch})

                for i in range(0, len(minibatch)):
                    gt_batch.append(
                        reward_batch[i] + LEARNING_RATE * np.max(out_batch[i]))

                optimizer.run(feed_dict={
                              gt: gt_batch, argmax: argmax_batch, input_image: input_image_data_batch})

            input_image_data = input_image_data1
            n = n + 1

            if n % 10000 == 0:
                saver.save(sess, 'game.cpk', global_step=n)  # 保存模型

            print(n, "epsilon:", epsilon, " ", "action:",
                  maxIndex, " ", "reward:", reward)


train_neural_network(input_image)


  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: TensorFlow是谷歌开源的人工智能框架,它可以辅助开发者利用人工智能算法来训练模型。TensorFlow训练模型过程可以分为以下几个步骤: 1. 数据准备:训练模型需要大量的数据集,开发者需要准备好相关的数据。在数据准备过程中,需要对数据进行清洗和转化,确保数据的质量和格式的合理性。 2. 设计模型:在训练模型的过程中,开发者需要根据需求和数据集选择合适的模型类型。目前,TensorFlow支持很多种模型类型和算法,开发者可以选择常用的卷积神经网络、循环神经网络、深度学习等算法。 3. 定义损失函数:损失函数为机器学习模型优化的指标,开发者需要根据模型类型和需求,选择合适的损失函数。 4. 选择优化算法:TensorFlow支持很多种优化算法,包括传统的梯度下降、动量优化、Adam优化等,这些算法可以通过传递参数来调整优化效果。 5. 训练模型:将准备好的数据按照一定的规则依次输入模型中进行训练,通过迭代优化损失函数来得到最优的模型。 6. 模型验证和调整:训练完成后,需要对模型进行验证和调整,确保其具有较高的性能和泛化能力。 总的来说,TensorFlow训练模型过程比较复杂,需要开发者结合自己的需求和实际情况来进行。不过,随着人工智能技术的不断发展和TensorFlow的不断完善,这个过程变得越来越容易,未来TensorFlow训练模型将会得到更广泛的应用。 ### 回答2: TensorFlow是一个用途广泛的开源机器学习工具箱,可用于各种深度学习应用。使用TensorFlow训练模型的步骤需要至少以下几个步骤: 1. 数据准备:TensorFlow通常需要将数据准备为可输送的形式。这通常需要对图像,文本等进行处理,如对图像进行裁剪,缩放,变形等操作。 2. 构建计算图:TensorFlow的中心思想是计算图,它提供了一个用于定义模型的抽象方式。模型通常是由神经网络组成的,使得它可以看成是一个有向图,其中节点是操作,边是数据流。TensorFlow还提供了许多便捷工具,如变量(Variables),常量(Constants)等来构建计算图。 3. 定义目标函数:训练模型的目标是最小化某个目标函数,例如均方误差。在TensorFlow中,目标函数通常定义为一个操作(operation),用于计算误差或损失值。 4. 训练模型:在TensorFlow中,训练模型通常涉及一个迭代过程,其中模型的参数通过反向传播优化方法进行更新,例如随机梯度下降。 5. 评估模型:训练模型后,应对其进行评估以确定其性能如何。可以使用交叉验证等方法进行评估并调整模型参数。 熟练运用TensorFlow进行模型训练需要深入理解其概念和原理,同时需要具备一定编程能力和数学基础。可以通过参加TensorFlow官方提供的教程和示例程序,或者参加培训班等方式进行学习。 ### 回答3: TensorFlow是一个基于数据流图的开源软件库,让用户能够更容易地构建、训练和部署神经网络。在TensorFlow中,用户可以通过定义计算图、使用张量并运行会话来完成模型的训练。 1. 定义计算图 在TensorFlow中,用户需要定义一个计算图来表达模型。计算图是一种由节点和边组成的有向无环图(DAG),其中每个节点表示一个操作,边表示张量(多维数组)在操作之间流动的路径。TensorFlow的核心概念是张量,用户可以用它来表示模型的输入、输出和中间状态。例如,用户可以通过以下代码创建一个计算图: ```python import tensorflow as tf # 创建两个张量 a = tf.constant(2) b = tf.constant(3) # 执行一个加法操作 c = tf.add(a, b) # 创建一个会话,运行计算图 with tf.Session() as sess: print(sess.run(c)) ``` 2. 定义模型 在计算图中定义了操作,接下来需要定义模型。用户可以使用TensorFlow提供的各种操作(例如卷积层、池化层、全连接层等)来构建模型。例如,以下代码定义了一个简单的线性回归模型: ```python import tensorflow as tf # 定义输入和输出张量 x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) # 定义模型参数 w = tf.Variable(0.0) b = tf.Variable(0.0) # 定义模型 y_pred = w * x + b # 定义损失函数(平方误差) loss = tf.square(y_pred - y) # 定义优化器 optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01) # 最小化损失函数 train_op = optimizer.minimize(loss) ``` 3. 训练模型 有了模型和计算图,接下来是训练模型。在TensorFlow训练模型的一般流程如下: - 准备训练数据和标签 - 开始一个会话 - 初始化模型参数 - 循环训练若干轮,每轮训练时执行以下操作: - 提供训练数据和标签 - 运行训练操作 - 计算损失函数值 - 打印损失函数值和模型参数 - 关闭会话 例如,以下代码展示了如何使用梯度下降算法训练上述线性回归模型: ```python import numpy as np import tensorflow as tf # 准备数据和标签 x_train = np.array([1, 2, 3, 4]) y_train = np.array([2, 4, 6, 8]) # 开始一个会话 with tf.Session() as sess: # 初始化模型参数 sess.run(tf.global_variables_initializer()) # 循环训练若干轮 for i in range(100): # 提供训练数据和标签 feed_dict = {x: x_train, y: y_train} # 运行训练操作和损失函数计算 _, loss_val, w_val, b_val = sess.run([train_op, loss, w, b], feed_dict=feed_dict) # 打印损失函数值和模型参数 print("iter: %d, loss: %f, w: %f, b: %f" % (i, loss_val, w_val, b_val)) ``` 以上就是TensorFlow训练模型的基本流程,当然实际上要训练一个复杂的神经网络模型可能需要更多的工作量和技巧。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值