Automatic Level Generation from Array - actionscript-3

So, I am trying to make the stages for the level in my game automatically generated.
I made an array (note, the amount of "tiles" on the screen is 16x16):
var background:Array=new Array(
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
)
And as you can probably tell, each 1 or 0 corresponds to if the tile is one thing or another (there or not there in this scenario).
I am pretty bad at the next part that I did.
I decided to make this using http://www.flashgametuts.com/tutorials/as3/how-to-create-a-platform-game-in-as3-part-2/'s method (kinda).
var bkgblocks:Sprite=new Sprite();
var bkgblocksw:Number=stage.stageWidth/16
var bkgblocksh:Number=stage.stageHeight/16
//the blocks are 45 pixels wide and tall
var row:int=0;
for(var i:int=0; i<background.length;i++){
if((i+1)/16==int((i+1)/16)){
//if i is divisible by 16
row++
}
if(background[i]==1){
bkgblocks.graphics.beginFill(0x000000)
bkgblocks.graphics.drawRect(I have no idea what to do here ,row*stage.stageHeight/16,bkgblocksw,bkgblocksh);
bkgblocks.graphics.endFill()
addChild(bkgblocks)
}
}
As you can see, I have no idea how or where to place the blocks!
I have where to place their y coordinate, but the x is way too confusing.
I thought I could do something like this
i*(45/(row+1))
but that messed up completely. This is more of a math question, I'm sorry, but if anybody can (or has) figure this out, I would appreciate it.

I usually prefer packing a grid into an array of arrays to make it more human-readable e. g.
var grid:Array = [
[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[1, 0, 0, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 1, 0, 0]
];
Where the first (outer) array contains rows of cells, each row represented by an array
So you can access a cell by calling grid[y][x] and find the 'real' coordinates by multiplying x and y by const CELL_SIZE

It seems you are tangled with 1D-2D coordinate transformation.
Let's width of your screen (2D coordinates) is Wdt. So element with (x,y) coordinates will be at y * Wdt + x index of 1D array.
A[y * Wdt + x] corresponds to Screen[y][x]
And back tranform:
x = index %% Wdt //integer modulus
y = index \ Wdt //integer division
Screen[index \ Wdt] [index %% Wdt] = A[index]

Related

Transparency in plotted surfaces

I'm using Octave 7.2.0-1 on linux.
When plotting surfaces which overlap (both with facealpha<1) Octave only shows the axes as a "see-through", not the surface which is "behind":
[ xs, ys, zs ] = sphere( 20 );
surf( xs, ys, zs, 'facealpha', 0.5, 'edgealpha', 0.5, 'facecolor', 'r' );
hold on
surf( xs+1, ys+1, zs , 'facealpha',0.5, 'edgealpha', 0.5, 'facecolor', 'g');
Is this a bug?

what do the lines ```predictions[a > 0.5] = 1``` and ```acc = np.mean(predictions == y)``` mean?

I am new to python programming. I am working on deep learning algorithms . I have never seen these type of lines in c or c++ programs.
what do the lines predictions[a > 0.5] = 1 and acc = np.mean(predictions == y) mean?
def predict(x, w, b):
a = sigmoid( w.T # x + b)
predictions = np.zeros_like(a)
predictions[a > 0.5] = 1
return predictions
def test_model(x, y, w, b):
predictions = predict(x, w, b)
acc = np.mean(predictions == y)
acc = np.asscalar(acc)
return acc
def main():
x, y = load_train_data()
x = flatten(x)
x = x/255. # normalize the data to [0, 1]
print(f'train accuracy: {test_model(x, y, w, b) * 100:.2f}%')
x, y = load_test_data()
x = flatten(x)
x = x/255. # normalize the data to [0, 1]
print(f'test accuracy: {test_model(x, y, w, b) * 100:.2f}%')
Thank You
Generally speaking, without knowing more, it is impossible to say, because [] is just invoking a method, which can be defined on any class:
class Indexable:
def __getitem__(self, index):
if index:
return "Truly indexed!"
else:
return "Falsely indexed!"
predictions = Indexable()
a = 0.7
predictions[a > 0.5]
# => 'Truly indexed!'
The same is true of the operator >.
However, from context, it is likely that both predictions and a are numpy arrays of same size, and a contains numbers.
a > .5 will produce another array of the same size as a with False where the element is .5 or smaller, and True where it is larger than .5.
predictions[b] where b is a boolean array of the same size will produce an array that only contains the elements where b is True:
predictions = np.array([1, 2, 3, 4, 5])
b = [True, False, False, False, True]
predictions[b]
# => array([1, 5])
The indexed assignments are similar, setting a value only where the corresponding element in the index array is True:
predictions[b] = 17
predictions
# => array([17, 2, 3, 4, 17])
So the line you are wondering about is setting all the predictions where the corresponding a is over 0.5 to 1.
As for the other line you're wondering about, the logic of == is similar to that of > above: predictions == y will give a boolean array telling where predictions and y coincide.
This array is then passed to np.mean, which calculates an arithmetic average of its argument. How do you get an average of [True, False, False, False, True] though? By coercing them to floats! float(True) is 1.0; float(False) is 0.0. The average of a boolean list thus basically tells you the fraction of elements that are true: np.mean([True, False, False, True]) is the same as np.mean([1.0, 0.0, 0.0, 0.0, 1.0]), giving the result of 0.4 (or 40% of elements being True).
So your line calculates which proportion of predictions is same as y (in other words, accuracy of the prediction, assuming y is the gold data).

Creating a 2 line graph on left axis and a bar graph on right axis Octave

I'm having difficulty creating a 2 y axis graph in Octave. Currently I can make the 2 line graph. However, I haven't been able to find a function that will help me with my problem. I have tried using the plotyy function but I am not sure if you can use this function with two left side axis line graphs and one right side graph. Here is code I have written so far in my attempt.
labels = ["Data 1"; "Data 2"; "Data 3"; "Data 4"; "Data 5"]
y1 = [137, 15, 2, 3, 37]
y2 = [43, 1, 67, 97, 41]
x = [1, 2, 3, 4, 5]
y3 = [0, .2, .3, .104, .09]
z1 = plot(x, y1, y2)
plot(x, y1, y2)
hold on
plot(x, y2)
xlabel("Version")
yyaxis left
ylabel("Y axis")
set(gca,'XTickLabel',labels)
yyaxis right
z = bar(x,y3)
z
yyaxis right
ylabel("Data")
While plotyy is the command to plot two normal plots using distinct left and right yaxes, I don't think you can do what you were trying to do with it. (i.e. mix two plots with a bar chart). However, what plotyy does is literally a simple case of overlaying two axes at the same position and making one 'see-through'. So you can use the same approach in general.
Here's your example above re-worked to achieve this (plus some extra bling):
x = [1, 2, 3, 4, 5]; labels = ["Data 1"; "Data 2"; "Data 3"; "Data 4"; "Data 5"];
y1 = [137, 15, 2, 3, 37]; y2 = [43, 1, 67, 97, 41]; y3 = [0, .2, .3, .104, .09];
ax_left = axes('position', [0.15, 0.12, 0.7, 0.82]); % manually positioned
plot (x, y1, 'r-', 'linewidth', 3); hold on
plot (x, y2, 'g:', 'linewidth', 3); hold off
set (ax_left, ...
'fontsize', 16, 'fontweight', 'bold', 'labelfontsizemultiplier', 1.2, ...
'color', 'none', ... % makes 'background' see-through
'box', 'off', ... % prevents left axis ticks in the right axis
'xlim', [0, 6], 'ylim', [0, 150], 'xtick', x, 'xticklabel', labels);
xlabel('Version'); ylabel('Left Y-Axis');
ax_right = axes('position', [0.15, 0.12, 0.7, 0.82]); % same position as above
bar (x, y3, 0.5, 'facecolor', [0, 0.5, 1]); % nice narrow light blue columns
set (ax_right, ...
'fontsize', 16, 'fontweight', 'bold', 'labelfontsizemultiplier', 1.2, ...
'yaxislocation', 'right', ...
'ycolor', [0, 0.5, 1], ... % same nice light blue color as bar chart
'box', 'off', 'xlim', [0, 6], 'ylim', [0, 0.35], 'xtick', []);
ylabel('Data');
% ensure axes are stacked in the order you want them to appear (bottom to top)
axes(ax_right);
axes(ax_left);

Compare two linear regression models in MATLAB

I want to compare the performance of two models using the F statistic. Here is a reproducible example and the expected results:
load carbig
tbl = table(Acceleration,Cylinders,Horsepower,MPG);
% Testing separetly both models
mdl1 = fitlm(tbl,'MPG~1+Acceleration+Cylinders+Horsepower');
mdl2 = fitlm(tbl,'MPG~1+Acceleration');
% Comparing both models using the F-test and p-value
numerator = (mdl2.SSE-mdl1.SSE)/(mdl1.NumCoefficients-mdl2.NumCoefficients);
denominator = mdl1.SSE/mdl1.DFE;
F = numerator/denominator;
p = 1-fcdf(F,mdl1.NumCoefficients-mdl2.NumCoefficients,mdl1.DFE);
We end up with F = 298.75 and p = 0, indicating mdl1 is significantly better than mdl2, as assessed by the F statistic.
Is there anyway to obtain the F and p values without performing twice fitlm and doing all the computation?
I tried to run a coefTest, as suggested by #Glen_b, however the function is poorly documented and the results are not the ones I'm expecting.
[p,F] = coefTest(mdl1); % p = 0, F = 262.508 (this F test mdl1 vs constant mdl)
[p,F] = coefTest(mdl1,[0,0,1,1]); % p = 0, F = 57.662 (not sure what this is testing)
[p,F] = coefTest(mdl1,[1,1,0,0]); % p = 0, F = 486.810 (idem)
I believe I should carry the test with a different null hypothesis (C) using the function [p,F] = coeffTest(mdl1,H,C). But I don't really know how to do it and there's no example.
This answer is in regards to comparing two linear regression models where one model is a restricted version of the other.
Short answer:
To do an F-test on the restriction that the 3rd and 4th elements of your estimated, coefficient vector b are zero:
[p, F] = coefTest(mdl1, [0, 0, 1, 0; 0, 0, 0, 1]);
Further explanation:
Let b be our estimated vector. Linear restrictions on b are typically written in a matrix form: R*b = r. The restriction that 3rd and 4th element of b are zero would be written:
[0, 0, 1, 0 * b = [0
0, 0, 0, 1] 0];
The matrix [0, 0, 1, 0; 0, 0, 0, 1] is what coefTest calls the H matrix in the docs.
P = coefTest(M,H), with H a numeric matrix having one column for each
coefficient, performs an F test that H*B=0, where B represents the
coefficient vector.
Long version
Sometimes with this econometric routines, it's nice just to write it out yourself so you know what's really going on.
Remove rows with NaN because they just add unrelated complexity:
tbl_dirty = table(Acceleration,Cylinders,Horsepower,MPG);
tbl = tbl_dirty(~any(ismissing(tbl_dirty),2),:);
Do the estimation etc...
n = height(tbl); % number of observations
y = tbl.MPG;
X = [ones(n, 1), tbl.Acceleration, tbl.Cylinders, tbl.Horsepower];
k = size(X,2); % number of variables (including constant)
b = X \ y; % estimate b with least squares
u = y - X * b; % calculates residuals
s2 = u' * u / (n - k); % estimate variance of error term (assuming homoskedasticity, independent observations)
BCOV = inv(X'*X) * s2; % get covariance matrix of b assuming homoskedasticity of error term etc...
bse = diag(BCOV).^.5; % standard errors
R = [0, 0, 1, 0;
0, 0, 0, 1];
r = [0; 0]; % Testing restriction: R * b = r
num_restrictions = size(R, 1);
F = (R*b - r)'*inv(R * BCOV * R')*(R*b - r) / num_restrictions; % F-stat (see Hiyashi for reference)
Fp = 1 - fcdf(F, num_restrictions, n - k); % F p-val
For reference, can look at p. 65 of Hiyashi's book Econometrics.
No, there is not.
Fitlm fits an arbitrary model. In your case a regression model with an intercept and either one or three regressors. It might seem that the model with three regressors can use information from the model with one regressor, but this is only true if there are some restrictions on the model and even then this overlapping information is limited.
Fitlm is a very general framework which can be used for arbitrary models. Doing multiple regressions at the same time with sharing of information can thus get quite complex and is not implemented.
It is possible to implement this yourself for these two specific models. Usually such a linear regression is solved using the covariance matrix:
Beta = (X' X) ^-1 X' y
were X is the data with the variables as columns and y is the target variable. In this case you could reuse part of the covariance matrix for which you only need the columns from the smaller regression: the variation in Acceleration. Since adding 2 new variables adds 8 values yo the covariance matrix you only save 1/9 of the time. Furthermore, the heaviest part is the inversion. Thus the time improvement is very very little.
In short, just do two separate regressions

Python: about [:] and its behavior in a function

def call(nums):
nums[:] = [x for x in nums if x != 4]
numbers = [4, 5]
print(numbers)
call(numbers)
print(numbers)
The output for the above code is:
[4, 5]
[5]
But if you remove the "[:]", the output becomes the following:
[4, 5]
[4, 5]
I know that [:] makes a copy of the full list, but why the function argument is modified in one case and not in the other?
As you suspected the issue is hiding in the slicer in line:
nums[:] = [x for x in nums if x != 4]
Python is "pass by value" which means that you're not passing the pointer numbers into the function, but a copy of it. So re-assigning a value to a copy of the reference will not change the original reference.
But, when you use the slicer, you're accessing the object behind the reference and changing it directly which is why you see the side effect after you exit the function - when using the "slice".
As Python passes objects by reference, when you execute your function with nums[:] = ... line, you change actual list that you've passed from outside, numbers. When you change line to nums = ..., you just overwrite local variable called nums, without affecting numbers array.
In Python, you can not only slice collections to read them, but you can assign to slices, replacing sliced content.
For example:
>>> a = [0, 1, 2, 3, 4, 5]
>>> a[1:4]
[1, 2, 3]
If you assign to slice, it will replace part of original array:
>>> a[1:4] = ['z']
>>> a
[0, 'z', 4, 5]
But when assigning to slices, array remains the same:
>>> a = [0, 1, 2, 3, 4, 5]
>>> b = a
>>> a[:] = ['z']
>>> a
['z']
>>> b
['z']
As you can see, a and b change at the same time, because when assigning to slice, you don't change object's identity, you only change its contents.
>>> a = [0, 1, 2, 3, 4, 5]
>>> b = a
>>> a = ['z']
>>> a
['z']
>>> b
[0, 1, 2, 3, 4, 5]
This is not the case when you just assign to variable, dropping older array out of scope.
def call(nums):
nums = [x for x in nums if x != 4]
Would only change the value of the name nums function parameter which would accomplish nothing.
def call(nums):
nums[:] = [x for x in nums if x != 4]
Changes the actual value of the list passed in as an argument.