人工智能实验报告1

昆明理工大学信息工程与自动化学院学生实验报告

20## 2013 学年  1  学期

课程名称:人工智能        开课实验室:信自楼445     20## 年12月 26日

一、上机目的及内容

1.上机内容:

  用于预测房价的线性回归(一元或二元的例子)

2.上机目的

(1)掌握线性回归的实质

(2)能够用MATLAB实现线性回归

二、实验原理及基本技术路线图(方框原理图或程序流程图)

(1)建立两个数据包:ex2x.da和ex2y.dat,分别存放住房面积和价格

(2)下载数据,分别付给x和y

(3)定义最大迭代次数,以及学习率,通过梯度下降法,进行迭代

     grad = (1/m).* x' * ((x * theta) - y)

     theta = theta - alpha .* grad

(4)如果没有得到预期目的,返回(3)

(5)如果得到回归曲线则停止,输出图形,否则返回(3)

三、所用仪器、材料(设备名称、型号、规格等或使用软件),

1台PC及MATLAB软件

、实验方法、步骤(或:程序代码或操作过程)

% Exercise 2 Linear Regression

% for house

%

% x refers to a house's area

% y is a house's price

%

clear all; close all; clc    %清空所有记录和关闭之前打开的所有窗口

x = load('ex2x.dat');      %从ex2x.da这个数据包中下载数据到x

y = load('ex2y.dat');      %从ex2y.dat这个数据包中下载数据在y

m = length(y);           % number of training examples

                       %定义训练的样本(y)的长度或大小

% Plot the training data(开始训练函数)

figure;                  % open a new figure window(打开一个新的窗口)

plot(x, y, 'o');            %定义输出样本用O表示

ylabel(' price of x*100万 元')         %定义y轴的值为住房的房价

xlabel(' area of x*60 square meter ')  %定义x轴的值为住房的面积,单位为平方米

% Gradient descent

x = [ones(m, 1) x]          % Add a column of ones to x(添加到 x 的那些列:就是将m设为1的那些列)

theta = zeros(size(x(1,:)))'% initialize fitting parameters(对theta进行初始化)

                            %将x中第一行和所有列初始化

MAX_ITR = 5000;            %训练或者是迭代的最大次数为5000次

alpha = 0.07;                %定义学习率为0.07

for num_iterations = 1:MAX_ITR  %梯度下降发开始,对回归函数开始迭代,从1到1500

    % This is a vectorized version of the

    % gradient descent update formula

    % It's also fine to use the summation formula from the videos

    % Here is the gradient

    grad = (1/m).* x' * ((x * theta) - y); %梯度下降发函数实现语句

    % Here is the actual update

    theta = theta - alpha .* grad;  %计算theta的值

    % Sequential update: The wrong way to do gradient descent

    % grad1 = (1/m).* x(:,1)' * ((x * theta) - y);

    % theta(1) = theta(1) + alpha*grad1;

    % grad2 = (1/m).* x(:,2)' * ((x * theta) - y);

    % theta(2) = theta(2) + alpha*grad2;

end

% print theta to screen

theta

% Plot the linear fit

hold on; % keep previous plot visible

plot(x(:,2), x*theta, '-')                  %寻找一个最低点,并将其输出来

legend('Training data', 'Linear regression')%对数据进行训练

hold off % don't overlay any more plots on this figure

% Closed form solution for reference

% You will learn about this method in future videos

exact_theta = (x' * x)\x' * y               %确定theta值

% Predict values for area 120 and 150

predict1 = [80, 120] *theta  %预测距离工作地80万,120平米的住房是否符合训练样本的规律

predict2 = [110, 150] * theta  %预测距离工作地110万,150平米的住房是否符合训练样本的规律

% Calculate J matrix

% Grid over which we will calculate J

theta0_vals = linspace(-3, 3, 100);       %theta0的值为-3到3,并分割为100等分,并将其用等高线输出

theta1_vals = linspace(-1, 1, 100);       %theta1的值为-1到1,并分割为100等分

% initialize J_vals to a matrix of 0's

J_vals = zeros(length(theta0_vals), length(theta1_vals))

for i = 1:length(theta0_vals)             %开始迭代,i从1到1500

         for j = 1:length(theta1_vals)       %开始迭代,j从1到1500

         t = [theta0_vals(i); theta1_vals(j)];   

         J_vals(i,j) = (0.5/m) .* (x * t - y)' * (x * t - y);

    end

end

% Because of the way house in the surf command, we need to

% transpose J_vals before calling surf, or else the axes will be flipped

J_vals = J_vals';                       %将J_vals'矩阵付给J_vals

% Surface plot

figure;

surf(theta0_vals, theta1_vals, J_vals)   %利用surf函数求theta0_vals、theta1_vals、 J_vals的值

xlabel('\theta_0'); ylabel('\theta_1'); %x轴表示theta_0,y轴表示theta_1

% Contour plot

figure;

% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100

contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 2, 15))%输出梯度下降中的最低点,用等高线表示

xlabel('\theta_0'); ylabel('\theta_1');                       %x轴表示theta_0,y轴表示theta_1

五、运行截图

图1

图2

图3

六、实验总结

通过实现掌握和了解了线性回归的基本特性,通过实验编程实现了住房价格和面积之间关系的线性分析。在实验中遇到了很多的问题:一开始的时候对软件不是很熟悉,不知道如何将数据写到数据包中,后来在老师的帮助下,解决了这个问题。数据写到数据包有两种方式:一是在matlab软件中手工输入或随机生成数据,然后用命令程序写到数据包(保存为数据包的形式);而是利用存储技术,也就是利用数据库语言生成数据包;其次遇到的问题是,迭代中出现了了问题,后来发现自己没有初始化学习率;最后的问题是,画不出图像,经过老师的帮助和自己的努力,最后实现了。总之,在这次实验中不但对MATLAB有了进一步的了解和认识,同时也获得了很多宝贵的经验和知识。

 

第二篇:AI实验报告1

实验一:追逐与拦截

一、实验目的

掌握游戏中追逐与拦截的人工智能算法

二、实验仪器

Visual C++6.0

三、实验原理及过程

四、实验结果

红色的箭头追着蓝色的箭头跑。

五、实验心得(需包括有何不足如何改进)

认识了AI的特点,用Visual C++6.0编写程序时的环境及生成效果。不足就是红色的箭头回跑到的屏幕的外面去。

六、主要代码

#include "main.h"

#include "time.h"

//---------------------------------------------------------------------------

/*

Book: AI for Game Developers

Authors: David M. Bourg & Glenn Seemann

Example: Chasing and evading in continuous environments, Chapter 2

*/

//---------------------------------------------------------------------------

// Global Variables:

int FrameCounter = 0;

RigidBody2D Craft1, Craft2;

Vector Target;

#define _TIMESTEP 0.001

#define _TOL 1e-10

#define _FWDTIME 10

#define _THRUSTFACTOR 3

#define _CHASESETUP true

bool Initialize(void)

{

Craft1.fMass = 10;

Craft1.fInertia = 10;

Craft1.fInertiaInverse = 1/10;

Craft1.vPosition.x = _WINWIDTH-60;

Craft1.vPosition.y = _WINHEIGHT*0.8;

Craft1.fWidth = 10;

Craft1.fLength = 20;

Craft1.fHeight = 5;

Craft1.fOrientation = 135;

Craft1.CD.y = -0.12*Craft1.fLength; Craft1.CD.x = 0.0f; // coordinates of the body center of drag

Craft1.CT.y = -0.50*Craft1.fLength; Craft1.CT.x = 0.0f; // coordinates of the propeller thrust vector

Craft1.CPT.y = 0.5*Craft1.fLength; Craft1.CPT.x = -0.5*Craft1.fWidth; // coordinates of the port bow thruster

Craft1.CST.y = 0.5*Craft1.fLength; Craft1.CST.x = 0.5*Craft1.fWidth; // coordinates of the starboard bow thruster

Craft1.ProjectedArea = (Craft1.fLength + Craft1.fWidth) * Craft1.fHeight;

Craft1.ThrustForce = _THRUSTFORCE*1;

Craft2.fMass = 10;

Craft2.fInertia = 10;

Craft2.fInertiaInverse = 1/10;

if(_CHASESETUP)

{

Craft2.vPosition.x = 40;

Craft2.vPosition.y = _WINHEIGHT*0.8;

} else {

Craft2.vPosition.x = Craft1.vPosition.x - Craft1.fLength*8;

Craft2.vPosition.y = Craft1.vPosition.y - Craft1.fLength*4;

}

Craft2.fWidth = 10;

Craft2.fLength = 20;

Craft2.fHeight = 5;

if(_CHASESETUP)

Craft2.fOrientation = -135;

else

Craft2.fOrientation = 135;

Craft2.CD.y = -0.12*Craft2.fLength; Craft2.CD.x = 0.0f; // coordinates of the body center of drag

Craft2.CT.y = -0.50*Craft2.fLength; Craft2.CT.x = 0.0f; // coordinates of the propeller thrust vector

Craft2.CPT.y = 0.5*Craft2.fLength; Craft2.CPT.x = 0.5*Craft2.fWidth; // coordinates of the port

bow thruster

Craft2.CST.y = 0.5*Craft2.fLength; Craft2.CST.x = -0.5*Craft2.fWidth; starboard bow thruster

Craft2.ProjectedArea = (Craft2.fLength + Craft2.fWidth) * Craft2.fHeight; Craft2.ThrustForce = _THRUSTFORCE*_THRUSTFACTOR;

return true;

}

void UpdateSimulation(void)

{

double dt = _TIMESTEP;

RECT r;

Craft1.SetThrusters(false, false);

if (IsKeyDown(VK_UP))

Craft1.ModulateThrust(true);

if (IsKeyDown(VK_DOWN))

Craft1.ModulateThrust(false);

if (IsKeyDown(VK_RIGHT))

Craft1.SetThrusters(true, false);

if (IsKeyDown(VK_LEFT))

Craft1.SetThrusters(false, true);

// Do craft 2 AI

Craft2.Fa.x = 0;

Craft2.Fa.y = 0;

Craft2.Pa.x = 0;

Craft2.Pa.y = 0;

if(BasicChase)

{

DoCraft2Chase();

DoCraft2ModulateThrust();

}

if(BasicEvade)

DoCraft2Evade();

if(InterceptChase)

{ // coordinates of the

//DoCraft2Intercept(); //DoCraft2ModulateThrust(); DoCraft2InterceptAlt(); } if(PotentialChase) DoAttractCraft2(); // update the simulation Craft1.UpdateBodyEuler(dt); Craft2.UpdateBodyEuler(dt); if(FrameCounter >= _RENDER_FRAME_COUNT) { // update the display if(!ShowTrails) ClearBackBuffer(); DrawCraft(Craft1, RGB(0,0,255)); DrawCraft(Craft2, RGB(255,0,0)); RECT r; r.left = (int) (Target.x-3); r.top = (int) (Target.y-3); r.right = (int) (Target.x+3); r.bottom = (int) (Target.y+3); DrawEllipse(&r, 1, RGB(0,255,0)); CopyBackBufferToWindow(); FrameCounter = 0; } else FrameCounter++; if(Craft1.vPosition.x > _WINWIDTH) Craft1.vPosition.x = 0; if(Craft1.vPosition.x < 0) Craft1.vPosition.x = _WINWIDTH; if(Craft1.vPosition.y > _WINHEIGHT) Craft1.vPosition.y = 0; if(Craft1.vPosition.y < 0) Craft1.vPosition.y = _WINHEIGHT; if(Craft2.vPosition.x > _WINWIDTH) Craft2.vPosition.x = 0; if(Craft2.vPosition.x < 0) Craft2.vPosition.x = _WINWIDTH;

if(Craft2.vPosition.y > _WINHEIGHT) Craft2.vPosition.y = 0; if(Craft2.vPosition.y < 0) Craft2.vPosition.y = _WINHEIGHT;

}

void DrawCraft(RigidBody2D craft, COLORREF clr) {

Vector vList[5];

double wd, lg;

int i;

Vector v1;

wd = craft.fWidth;

lg = craft.fLength;

vList[0].y = lg/2; vList[0].x = wd/2;

vList[1].y = -lg/2; vList[1].x = wd/2;

vList[2].y = -lg/2; vList[2].x = -wd/2;

vList[3].y = lg/2; vList[3].x = -wd/2;

vList[4].y = lg/2*1.5; vList[4].x = 0;

for(i=0; i<5; i++)

{

v1 = VRotate2D(craft.fOrientation, vList[i]);

vList[i] = v1 + craft.vPosition;

}

DrawLine(vList[0].x, vList[0].y, vList[1].x, vList[1].y, 2, clr); DrawLine(vList[1].x, vList[1].y, vList[2].x, vList[2].y, 2, clr); DrawLine(vList[2].x, vList[2].y, vList[3].x, vList[3].y, 2, clr); DrawLine(vList[3].x, vList[3].y, vList[4].x, vList[4].y, 2, clr); DrawLine(vList[4].x, vList[4].y, vList[0].x, vList[0].y, 2, clr);

if(ShowVectors)

{

Vector v, u;

double f = 5;

// Show velocity vectors in green

DrawLine(craft.vPosition.x, craft.vPosition.y, craft.vPosition.y+craft.vVelocity.y, 3, RGB(0,255,0));

// Show force vectors in black

// thrust vector

v.x = 0;

v.y = craft.ThrustForce*f;

v = VRotate2D(craft.fOrientation, v); craft.vPosition.x+craft.vVelocity.x,

u.x = craft.CT.x;

u.y = craft.CT.y;

u = VRotate2D(craft.fOrientation, u);

DrawLine(craft.vPosition.x+u.x, craft.vPosition.y+u.y, craft.vPosition.x + u.x + v.x, craft.vPosition.y + u.y + v.y, 1, RGB(0,0,0));

// port steering force

v.x = craft.PThrust.x*f;

v.y = craft.PThrust.y*f;

v = VRotate2D(craft.fOrientation, v);

u.x = craft.CPT.x;

u.y = craft.CPT.y;

u = VRotate2D(craft.fOrientation, u);

DrawLine(craft.vPosition.x+u.x, craft.vPosition.y+u.y, craft.vPosition.x + u.x + v.x, craft.vPosition.y + u.y + v.y, 1, RGB(0,0,0));

// stbd steering force

v.x = craft.SThrust.x*f;

v.y = craft.SThrust.y*f;

v = VRotate2D(craft.fOrientation, v);

u.x = craft.CST.x;

u.y = craft.CST.y;

u = VRotate2D(craft.fOrientation, u);

DrawLine(craft.vPosition.x+u.x, craft.vPosition.y+u.y, craft.vPosition.x + u.x + v.x, craft.vPosition.y + u.y + v.y, 1, RGB(0,0,0));

// applied force

v.x = craft.Fa.x*f;

v.y = craft.Fa.y*f;

v = VRotate2D(craft.fOrientation, v);

u.x = craft.Pa.x;

u.y = craft.Pa.y;

u = VRotate2D(craft.fOrientation, u);

DrawLine(craft.vPosition.x+u.x, craft.vPosition.y+u.y, craft.vPosition.x + u.x + v.x, craft.vPosition.y + u.y + v.y, 1, RGB(0,0,0));

}

}

void DoCraft2Chase(void)

{

Vector u, v;

bool p = false;

bool s = false;

u = VRotate2D(-Craft2.fOrientation, (Craft1.vPosition - Craft2.vPosition)); u.Normalize();

Target = Craft1.vPosition;

if(u.x < -_TOL)

p = true;

else if(u.x > _TOL)

s = true;

Craft2.SetThrusters(p,s);

}

void DoCraft2Evade(void)

{

Vector u, v;

bool p = false;

bool s = false;

u = VRotate2D(-Craft2.fOrientation, (Craft1.vPosition - Craft2.vPosition)); u.Normalize();

if(u.x > 0)

p = true;

else if(u.x < 0)

s = true;

Craft2.SetThrusters(p,s);

Target = Craft2.vPosition;

}

void DoCraft2Intercept(void)

{

Vector u1, u2, u;

Vector s1, s2;

Vector Vr;

double t1, t2;

Vector s1unit, s2unit;

bool p = false;

bool s = false;

Vr = Craft1.vVelocity - Craft2.vVelocity;

s2 = GetVelocityIntersection() - Craft2.vPosition;

s2unit = s2;

s2unit.Normalize();

u2 = VRotate2D(-Craft2.fOrientation, s2); t2 = s2.Magnitude()/(Vr * s2unit);

s1 = Craft1.vPosition - Craft2.vPosition; s1unit = s1;

s1unit.Normalize();

u1 = VRotate2D(-Craft2.fOrientation, s1); t1 = s1.Magnitude()/(Vr * s1unit);

if(t1 < 0.0)

{

u = u2;

Target = s2 + Craft2.vPosition; } else if(t2 < 0.0) {

u = u1;

Target = s1 + Craft2.vPosition; } else if(t2 < t1)

{

u = u2;

Target = s2 + Craft2.vPosition; } else {

u = u1;

Target = s1 + Craft2.vPosition; }

u.Normalize();

if(u.x < -_TOL)

p = true;

else if(u.x > _TOL)

s = true;

Craft2.SetThrusters(p,s);

}

void DoCraft2InterceptAlt(void)

{

Vector u;

Vector s1, s2, s12;

bool p = false;

bool s = false;

double tClose;

Vector Vr12;

double vr;

// turn around if we get ahead of the prey...

s12 = Craft1.vPosition - Craft2.vPosition;

u = VRotate2D(-Craft2.fOrientation, s12);

if(u.y < -_TOL)

{

//if(GetRandomNumber(0, 10, true) < 5)

p = true;

//else

// s = true;

Craft2.SetThrusters(p,s);

Target = Craft2.vPosition;

return;

}

Vr12 = Craft1.vVelocity-Craft2.vVelocity; // closing velocity s12 = Craft1.vPosition - Craft2.vPosition; // range to close tClose = s12.Magnitude() / Vr12.Magnitude(); // time to close

s1 = Craft1.vPosition + (Craft1.vVelocity * tClose); Target = s1;

s2 = s1 - Craft2.vPosition;

u = VRotate2D(-Craft2.fOrientation, s2);

u.Normalize();

if(u.x < -_TOL)

p = true;

else if(u.x > _TOL)

s = true;

Craft2.SetThrusters(p,s);

}

void DoAttractCraft2(void)

{

// Apply Lenard-Jones potential force to Craft2

Vector r = Craft2.vPosition - Craft1.vPosition; Vector u = r;

u.Normalize();

double U, A, B, n, m, d;

A = 2000;

B = 4000;

n = 2;

m = 3;

d = r.Magnitude()/Craft2.fLength;

U = -A/pow(d, n) + B/pow(d, m);

Craft2.Fa = VRotate2D( -Craft2.fOrientation, U * u);

Craft2.Pa.x = 0;

Craft2.Pa.y = Craft2.fLength / 2;

Target = Craft1.vPosition;

}

Vector GetVelocityIntersection(void)

{

double s, t, num, denom;

Vector a,b,c,d;

a = Craft1.vPosition;

b = a+Craft1.vVelocity;

c = Craft2.vPosition;

d = c+Craft2.vVelocity;

denom = a.x * (d.y-c.y) +

b.x * (c.y-d.y) +

d.x * (b.y-a.y) +

c.x * (a.y-b.y);

if(denom == 0)

return Vector(a.x, a.y, 0);

num = a.x * (d.y-c.y) +

c.x * (a.y-d.y) +

d.x * (c.y-a.y);

s = num/denom;

num = -( a.x * (c.y-b.y) +

b.x * (a.y-c.y) +

c.x * (b.y-a.y) );

t = num/denom;

if( (s >= 0) && (t >= 0) )

return Vector(a.x+s*(b.x-a.x), a.y+s*(b.y-a.y),0); else

return Vector(a.x, a.y, 0);

}

int GetRandomNumber(int min, int max, bool seed)

{

int number;

if(seed)

srand( (unsigned)time( NULL ) );

number = (((abs(rand())%(max-min+1))+min));

if(number>max)

number = max;

if(number<min)

number = min;

return number;

}

void DoCraft2ModulateThrust(void)

{

Vector r = Craft1.vPosition - Craft2.vPosition;

double dmax = Craft2.fLength * 10;

if((Craft2.PThrust.Magnitude() > 0) || (Craft2.SThrust.Magnitude() > 0)) // turning {

if(r.Magnitude() > dmax)

Craft2.ThrustForce = _MAXTHRUST;

else

Craft2.ThrustForce = r.Magnitude() / dmax * _MAXTHRUST; } else {

// todo: check how close we are to target and adjust speed to stay with it Craft2.ThrustForce = _MAXTHRUST;

}

}

相关推荐