Holt winters Alpha - holtwinters

I am trying to get the HoltWinters Alpha function added.
I have a Table called Sales1 and the code should refer to this table.
Is there anyone who can correct or amend my code below ,so i get the Holtwinters Alpha instead of the Chronbachs Alpha?
Holt winters calc (need this probably amended)
library(forecast)
library(Metrics
)
read_file(sales1)
x <- sales
x = c(Sales1)
mSES = HoltWinters(x, alpha = 0.5, beta = FALSE, gamma = FALSE)
mHW = HoltWinters(x, alpha = 0.5, beta = FALSE, gamma = FALSE)
mSES$SSE
mHW$SSE
HoltWinters(x, alpha = NULL, beta = NULL, gamma = NULL,
seasonal = c("additive", "multiplicative"),
start.periods = 2, l.start = NULL, b.start = NULL,
s.start = NULL,
optim.start = c(alpha = 0.3, beta = 0.1, gamma = 0.1),
optim.control = list())
chronbachs alpha calc
read_file(sales1)
library(tidyverse)
library(psy)
Number of rows before to take into account
rolling = 2
sales1 <- sales::sales( ~date, ~sales,)
#Lag
sales1 = sales1 %>% mutate(lagsales = lag(sales))
#Rolling Chronbachs Alpha.:( I need the Holtwinter Alpha here )
sales1$alpha = c( rep(NA, rolling),
map_dbl((rolling + 1):nrow(sales1), function(x){
cronbach(sales1 %>% select(sales, lagsales) %>% slice((x-rolling):x))$alpha
})
)
sales1
tibbet from Sales1 table:
df <- tibble::tribble(
~seq, ~date, ~sales,
1, "3/01/2017", 40,
2, "4/01/2017", 2,
3, "5/01/2017", 2,
4, "6/01/2017", 2,
5, "7/01/2017", 30,
6, "8/01/2017", 2,
7, "1/02/2017", 9,
8, "2/02/2017", 5,
9, "3/02/2017", 65,
10, "4/02/2017", 3,
11, "5/02/2017", 65

Related

Polygon set_width and set_height not work

There is right part inverse proportional function (1/x) in the scene, in the begining I draw a rectangle(using polygon), the left down corner is (0, 0, 0), thei right up corner is on the function with x=3.
I override update_mobjects, and update the postion of the right upper corner of rectangle with some point on the function, but not work, the width increase instead of decrease, please help, thanks!
my code is as below:
class Chess(GraphScene):
CONFIG = {
"x_min": -5,
"x_max": 5,
"y_min": -5,
"y_max": 6,
"y_axis_height": 10,
"graph_origin": ORIGIN,
"x_labeled_nums": range(-5, 5, 1),
"y_labeled_nums": range(-5, 6, 1)
}
def construct(self):
self.setup_axes(animate=True)
if1r = self.get_graph(lambda x: 1 / x, color=YELLOW_D, x_min=1 / self.y_max, x_max=self.x_max)
self.play(FadeIn(if1r))
spt1 = self.input_to_graph_point(3, if1r)
sg = Polygon(np.array([0, 0, 0]), np.array([spt1[0], 0, 0]), spt1, np.array([0, spt1[1], 0]), fill_color=RED_D,
fill_opacity=1.0)
self.add(sg)
self.sg = sg
self.sva1 = 3
self.if1r = if1r
self.moving3()
def moving3(self):
self.always_update_mobjects = True
self.wait(10)
def update_mobjects(self, dt):
if (hasattr(self, "sva1") and self.sva1 > 1):
self.sva1 = self.sva1 - 0.01
spt2 = self.input_to_graph_point(self.sva1, self.if1r)
self.sg.set
self.sg.set_width(spt2[0], stretch=False, about_point=self.sg.get_corner(DOWN + LEFT))
self.sg.set_height(spt2[1], stretch=False, about_point=self.sg.get_corner(DOWN+LEFT))
Yes it works, but you forgot to change stretch=True in the last two lines.
In addition, the line self.sg.set left over.
If you allow me the comment, I think you have better control in this way:
More examples here
class NewChess(GraphScene):
CONFIG = {
"x_min": -5,
"x_max": 5,
"y_min": -5,
"y_max": 6,
"y_axis_height": 10,
"graph_origin": ORIGIN,
"x_labeled_nums": range(-5, 5, 1),
"y_labeled_nums": range(-5, 6, 1),
"x_start":3,
"x_end":1
}
def get_rectangle_from_point(self,point):
return Polygon(
[0, 0, 0], #(0,0)
[point[0], 0, 0], #(x,0)
point, #(x,y)
[0, point[1], 0], #(0,y)
fill_color=RED_D,
fill_opacity=1.0
)
def construct(self):
self.setup_axes()
x_coord_tracker=ValueTracker(self.x_start)
if1r = self.get_graph(lambda x: 1 / x, color=YELLOW_D, x_min=1 / self.y_max, x_max=self.x_max)
spt1 = self.input_to_graph_point(x_coord_tracker.get_value(), if1r)
sg = self.get_rectangle_from_point(spt1)
self.play(FadeIn(if1r))
self.play(FadeIn(sg))
def update_rectangle(rectangle):
new_coord=self.input_to_graph_point(x_coord_tracker.get_value(), if1r)
rectangle.become(self.get_rectangle_from_point(new_coord))
return rectangle
sg.add_updater(update_rectangle)
self.add(sg) # Add object again
self.play(
x_coord_tracker.set_value,self.x_end,
rate_func=linear,
run_time=2
)
self.wait()

I'm not getting summary from statsmodels.formula.api

Getting an error while running regressor_OLS.summary().
Error: name 'regressor_OLS' is not defined
import statsmodels.formula.api as sm
x = np.append(arr = np.ones((50, 1)).astype(int),values = x, axis = 1)
x_opt = x[:, [0, 1, 2, 3, 4, 5]]
regressor_OLS = sm.OLS(endog = y, exog = x_opt).fit()
regressor_OLS.summary()

TensorFlow (Neural Network) FC output size

Not sure whether my question is TF specific or just NNs in general but i have created a CNN using tensorflow. and im having trouble understanding why the size of the output on my fully connected layer is what it is.
X = tf.placeholder(tf.float32, [None, 32, 32, 3])
y = tf.placeholder(tf.int64, [None])
is_training = tf.placeholder(tf.bool)
# define model
def complex_model(X,y,is_training):
# conv layer
wconv_1 = tf.get_variable('wconv_1', [7 ,7 ,3, 32])
bconv_1 = tf.get_variable('bconv_1', [32])
# affine layer 1
w1 = tf.get_variable('w1', [26*26*32//4, 1024]) #LINE 13
b1 = tf.get_variable('b1', [1024])
# batchnorm params
bn_gamma = tf.get_variable('bn_gamma', shape=[32]) #scale
bn_beta = tf.get_variable('bn_beta', shape=[32] ) #shift
# affine layer 2
w2 = tf.get_variable('w2', [1024, 10])
b2 = tf.get_variable('b2', [10])
c1_out = tf.nn.conv2d(X, wconv_1, strides=[1, 1, 1, 1], padding="VALID") + bconv_1
activ_1 = tf.nn.relu(c1_out)
mean, var = tf.nn.moments(activ_1, axes=[0,1,2], keep_dims=False)
bn = tf.nn.batch_normalization(act_1, mean, var, bn_gamma, bn_beta, 1e-6)
mp = tf.nn.max_pool(bn, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
affine_in_flat = tf.reshape(mp, [-1, 26*26*32//4])
affine_1 = tf.matmul(affine_in_flat, w1) + b1
activ_2 = tf.nn.relu(affine_1)
affine_2 = tf.matmul(activ_2, w2) + b2
return affine_2
#print(affine_2.shape)
In line 13 where i set the value of w1 i would have expected to just put:
w1 = tf.get_variable('w1', [26*26*32, 1024])
however if i run the code with the line shown above and with
affine_in_flat = tf.reshape(mp, [-1, 26*26*32])
my output size is 16,10 instead of 64,10 which is what i would expect given the initialisations below:
x = np.random.randn(64, 32, 32,3)
with tf.Session() as sess:
with tf.device("/cpu:0"): #"/cpu:0" or "/gpu:0"
tf.global_variables_initializer().run()
#print("train", x.size, is_training, y_out)
ans = sess.run(y_out,feed_dict={X:x,is_training:True})
%timeit sess.run(y_out,feed_dict={X:x,is_training:True})
print(ans.shape)
print(np.array_equal(ans.shape, np.array([64, 10])))
can anybody tell me why i need to divide the size of w1[0] by 4?
Adding print statements for bn and mp I get:
bn: <tf.Tensor 'batchnorm/add_1:0' shape=(?, 26, 26, 32) dtype=float32>
mp: <tf.Tensor 'MaxPool:0' shape=(?, 13, 13, 32) dtype=float32>
Which would seem to be due to the strides=[1, 2, 2, 1] on the max pooling (but to maintain 26, 26 you'd also need padding='SAME').

Why is my convolution autoencoder not getting trained properly?

Why is my convolutional autoencoder not converging properly? I have a very simple layer stack.
Encoder: Conv/ReLU(Kernel size: 7x7, stride = 1, padding = 0) => maxPool(kernel size=2x2, stride = 2) => Conv/ReLU(Kernel size: 5x5, stride = 1, padding = 0) => MaxPool(kernel size=2x2, stride = 2)
Decoder: Nearest Neighbour Upsampling => Deconv/ReLU => Nearest Neighbour Upsampling => Deconv/ReLU
Training Images are of size 30x30x1.
I tried to train it with 1000 images over 1000 epoch, but the error (MSE) is still 120.
BATCH_SIZE = 100
IMAGE_SIZE = 30
NUM_CHANNELS = 1
num_images = 1000
def init_weights(shape):
return tf.Variable(tf.random_normal(shape, stddev=0.01))
def encoder(X, w, w2, wd, wd2):
l1a = tf.nn.relu(tf.nn.conv2d(X, w,strides=[1, 1, 1, 1], padding='VALID'))
l1 = tf.nn.max_pool(l1a, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
l2a = tf.nn.relu(tf.nn.conv2d(l1, w2,strides=[1, 1, 1, 1], padding='VALID'))
l2 = tf.nn.max_pool(l2a, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
l1da = tf.image.resize_images(l2, 8, 8, 1, align_corners=False)
output_shapel1d = tf.convert_to_tensor([BATCH_SIZE, 12, 12, 32], dtype=tf.int32);
l1d = tf.nn.relu(tf.nn.conv2d_transpose(l1da, wd, output_shapel1d, strides=[1, 1, 1, 1], padding='VALID'))
l2da = tf.image.resize_images(l1d, 24, 24, 1, align_corners=False)
output_shapel2d = tf.convert_to_tensor([BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS], dtype=tf.int32);
l2d = tf.nn.relu(tf.nn.conv2d_transpose(l2da, wd2, output_shapel2d, strides=[1, 1, 1, 1], padding='VALID'))
return l2d
complete_image = extract_data(0, 1000)
trX = complete_image[0:900]
trY = trX
teX = complete_image[900:1000]
teY = teX
X = tf.placeholder("float", [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS])
Y = tf.placeholder("float", [BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS])
w = init_weights([7, 7, 1, 32])
w2 = init_weights([5, 5, 32, 64])
wd = init_weights([5, 5, 32, 64])
wd2 = init_weights([7, 7, 1, 32])
py_x = encoder(X, w, w2, wd, wd2)
cost = tf.reduce_mean(tf.squared_difference(py_x, Y, name = None))
train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
predict_op = py_x;
global_step = tf.Variable(0, name='global_step', trainable=False)
saver = tf.train.Saver()
with tf.Session() as sess:
tf.initialize_all_variables().run()
start = global_step.eval() # get last global_step
print "Start from:", start
if FLAGS.output == "train":
for i in range(start, 500):
training_batch = zip(range(0, num_images - BATCH_SIZE, batch_size),
range(batch_size, num_images - BATCH_SIZE, batch_size))
for start, end in training_batch:
sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})
total_epoch_cost += sess.run(cost, feed_dict={X: trX[start:end], Y: trY[start:end]})
avg_epoch_cost = total_epoch_cost/BATCH_SIZE
print "cost during epoch " + `i` + "is ", avg_epoch_cost
I have added the complete code in this gist with slight modifications. I am training this with around 10,000 images, and the error after 488 epochs is 74.8.

Modelica: Wrong number of subscripts in data[j].MM (1 subscripts for 0 dimensions)

I'm try to create new media based on MixtureGasNasa and used it in test examples NonCircularPipes (copy standard MSL example to new file).
When I try to check model I get new errors:
[9] 17:54:03 Translation Error
[Modelica.Media.IdealGases.Common: 1305:5-1305:67]: Wrong number of subscripts in data[j].MM (1 subscripts for 0 dimensions).
[10] 17:54:03 Translation Error
[Modelica.Media.IdealGases.Common: 1305:5-1305:67]: Variable data[j].MM not found in scope Modelica.Fluid.Sources.Boundary_pT$boundary.Medium.molarMass.$foriter loop scope$.
[11] 17:54:03 Translation Error
Error occurred while flattening model Example_NonCircularPipes
For describe situation in details include here code of models.
package ACIDGas_1 "Определение проектной смеси для установки по очистке серы"
import Modelica.Fluid;
function phase_stat "функция расчета диаграммы состояний для бинарных газов/жидкостей относительно серы"
end phase_stat;
import Modelica.Media.IdealGases.Common.MixtureGasNasa;
extends MixtureGasNasa(mediumName = "ACIDGas", data = {Common.SingleGasesData.H2S, Common.SingleGasesData.SO2, Common.SingleGasesData.H2O, Common.SingleGasesData.O2, Common.SingleGasesData.N2, Common.SingleGasesData.H2, Common.SingleGasesData.CO, Common.SingleGasesData.CO2, Common.SingleGasesData.COS, Common.SingleGasesData.CS2, Common.SingleGasesData.CH4, Common.SingleGasesData.C2H6, Common.SingleGasesData.C3H8, Common.SingleGasesData.C4H10_isobutane, Common.SingleGasesData.C4H10_n_butane, Common.SingleGasesData.C5H12_i_pentane, Common.SingleGasesData.NC3H12, Common.SingleGasesData.NH3, Common.SingleGasesData.S, Common.SingleGasesData.S2, Common.SingleGasesData.S3, Common.SingleGasesData.S4, Common.SingleGasesData.S5, Common.SingleGasesData.S6, Common.SingleGasesData.S7, Common.SingleGasesData.S8}, fluidConstants = {Common.FluidData.H2S, Common.FluidData.SO2, Common.FluidData.H2O, Common.FluidData.O2, Common.FluidData.N2, Common.FluidData.H2, Common.FluidData.CO, Common.FluidData.CO2, Common.FluidData.COS, Common.FluidData.CS2, Common.FluidData.CH4, Common.FluidData.C2H6, Common.FluidData.C3H8, Common.FluidData.C4H10_isobutane, Common.FluidData.C4H10_n_butane, Common.FluidData.C5H12_i_pentane, Common.FluidData.NC3H12, Common.FluidData.NH3, Common.FluidData.S, Common.FluidData.S2, Common.FluidData.S3, Common.FluidData.S4, Common.FluidData.S5, Common.FluidData.S6, Common.FluidData.S7, Common.FluidData.S8}, substanceNames = {"H2S", "SO2,", "H2O", "O2", "N2", "H2", "CO", "CO2", "COS", "CS2", "CH4", "C2H6", "C3H8", "C4H10_isobutane", "C4H10_n_butane", "C5H12_i_pentane", "NH3", "S", "S2", "S3", "S4", "S5", "S6", "S7", "S8"}, reference_X = {0.0, 0.0, 0.0, 0.232, 0.768, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0});
annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {2, 2})), Diagram(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {2, 2})));
end ACIDGas_1;
model Example_NonCircularPipes
import Modelica.Media;
import Modelica.Fluid;
replaceable package Medium = ACIDGas_1 "Medium in the component";
extends Modelica.Icons.Example;
constant Real odim = 0.015;
constant Real idim = 0.005;
inner Modelica.Fluid.System system(energyDynamics = Modelica.Fluid.Types.Dynamics.FixedInitial) annotation(Placement(visible = true, transformation(origin = {-80, 80}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
Modelica.Fluid.Sources.Boundary_pT boundary(redeclare package Medium = Medium, nPorts = 2, p = 10.0e5, T = 293.15) annotation(Placement(visible = true, transformation(origin = {-80, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
Modelica.Fluid.Sources.MassFlowSource_T massflowsink1(redeclare package Medium = Medium, nPorts = 1, m_flow = -0.1, T = 293.15) annotation(Placement(visible = true, transformation(origin = {40, 40}, extent = {{10, -10}, {-10, 10}}, rotation = 0)));
Modelica.Fluid.Sources.MassFlowSource_T massflowsink2(redeclare package Medium = Medium, nPorts = 1, m_flow = -0.1, T = 293.15) annotation(Placement(visible = true, transformation(origin = {40, -40}, extent = {{10, -10}, {-10, 10}}, rotation = 0)));
Modelica.Fluid.Pipes.DynamicPipe circular_pipe(redeclare package Medium = Medium, length = 100, diameter = 0.01, T_start = 293.15, p_a_start = 10.0e5, p_b_start = 10.0e5) annotation(Placement(visible = true, transformation(origin = {-20, 40}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
Modelica.Fluid.Pipes.DynamicPipe annulus_pipe(redeclare package Medium = Medium, length = 100, crossArea = Modelica.Constants.pi * (odim ^ 2 - idim ^ 2) / 4, perimeter = Modelica.Constants.pi * (odim + idim), isCircular = false, diameter = 0, p_a_start = 1000000, p_b_start = 1000000, T_start = 293.15) annotation(Placement(visible = true, transformation(origin = {-20, -40}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
equation
connect(boundary.ports[1], circular_pipe.port_a) annotation(Line(points = {{-70, 2}, {-60, 2}, {-60, 40}, {-30, 40}}, color = {0, 127, 255}));
connect(boundary.ports[2], annulus_pipe.port_a) annotation(Line(points = {{-70, -2}, {-60, -2}, {-60, -40}, {-30, -40}}, color = {0, 127, 255}));
connect(circular_pipe.port_b, massflowsink1.ports[1]) annotation(Line(points = {{-10, 40}, {30, 40}}, color = {0, 127, 255}));
connect(annulus_pipe.port_b, massflowsink2.ports[1]) annotation(Line(points = {{-10, -40}, {30, -40}}, color = {0, 127, 255}));
annotation(experiment(StopTime = 1), Library = Seneca, Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {2, 2})), Diagram(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {2, 2})));
end Example_NonCircularPipes;
What I do wrong?

Resources