python package install error and little code bugs

When you install packages using setup.py, the error:

(py37) C:\Users\weda\Phd\python packages\visibility_graph-0.4>python setup.py install
Traceback (most recent call last):
File “setup.py”, line 11, in <module>
long_description=readme(),
File “setup.py”, line 5, in readme
return f.read()
File “C:\Users\weda\AppData\Local\Continuum\anaconda3\envs\py37\lib\encodings\cp1252.py”, line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: ‘charmap’ codec can’t decode byte 0x9d in position 1725: character maps to <undefined>

the solution: stackoverflow

 

KL distance

信息熵-知乎信息熵公式的由来

information entropy: why exist? — information amount信息量 is used to evaluate the amount of information when an event happens. And entropy is the expectation of information amount in a distribution.

信息量度量的是一个具体事件发生了所带来的信息,而熵则是在结果出来之前对可能产生的信息量的期望——考虑该随机变量的所有可能取值,即所有可能发生事件所带来的信息量的期望。即

[公式]

information entropy: 可以是任意底数。

KL distance: Kullback-Leibler divergence/ relative entropy.它衡量的是相同事件空间里的两个概率分布的差异情况

D(P||Q)表示KL距离,计算公式如下:

 


The phenomenon of electricity consumption:

one challenge:  electricity consumption patterns vary on a daily basis even for the same customer.  ———————> explore the dynamic characteristics, such as switching and maintaining of the consumption states and the corresponding probabilities.

However, few papers consider the dynamics as a factor for clustering.

the clustering of customers ignoring the dynamics patterns changing in the same customers.

Clustering of Electricity Consumption BehaviorDynamics Toward Big Data Applications – wang yi

Method:

  1. data normalization
  2. SAX to reduce data amount.
  3. Markov model to formulate the electricity consumption behavior dynamics.  VS the shape of daily load profiles.  ————-不是很明白
  4. KL distance calculation
  5. CFSFDP + K-means clustering

聚类算法Clustering by fast search and find of density peaks

发表在Science上的新聚类算法

新的聚类中心选取算法: 可以作为其他聚类算法的预处理步骤。

DBSCAN

SOM (self-organizing maps); 中文版; another explanation;

tools

huel; paper with code;

sklearn-cluster


LIttle programming

  • data[“c1”] – Series; data[“c1”].values – narray;

  • the difference between np.array(i) and np.array(i).reshape(1,-1)

np.array(each)
array([0., 0., 1., 0., 0., 0., 1., 1., 1., 0., 0., 0., 1., 0., 0., 1., 0.,
1., 0., 0., 1., 0., 1., 0.])
a = np.array(each)
a.shape
(24,) #表示竖列
b = np.array(each).reshape(1,-1)
b.shape
(1, 24) #表示横列
a
array([0., 0., 1., 0., 0., 0., 1., 1., 1., 0., 0., 0., 1., 0., 0., 1., 0.,
1., 0., 0., 1., 0., 1., 0.])
b
array([[0., 0., 1., 0., 0., 0., 1., 1., 1., 0., 0., 0., 1., 0., 0., 1.,
0., 1., 0., 0., 1., 0., 1., 0.]])

using tensorflow

tf.graph constructs a graph to execute computation.  Node: tf.Operation; edge: tf.Tensor.

tf.name_scope : add a prefix to all operations created in this scope.

tf.constant(42.0): create a tf.Operation hat produces the value 42.0, and returns a tf.Tensor that prepresents the value of the constant.

tf.matmul(x,y): multiplies x and y, and returns a tensor that represents the result of the multiplication.


Conv1D(input, filters, kernel_size, activation)

Questions: The input shape should be (batch_size, length, channel). However, for a time series sequence, what does this channel mean? In image field, the channel means RGB, or grey image.

Answer: in one time series sequence, the channel is 1. Channel means the amount of attributes(time series) you have, like price, power consumption, outside temperature and so on. From Multi-Channel Convolutions explained with… MS Excel!


MNIST example

image.shape(60000, 28, 28). length = 60000;

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10, activation='softmax')
])

The first layer in this network, tf.keras.layers.Flatten, transforms the format of the images from a two-dimensional array (of 28 by 28 pixels) to a one-dimensional array (of 28 * 28 = 784 pixels). This layer has no parameters to learn; it only reformats the data.

After the pixels are flattened, the network consists of a sequence of two tf.keras.layers.Dense layers. These are densely connected, or fully connected, neural layers. The first Dense layer has 128 nodes (or neurons). The second (and last) layer is a 10-node softmax layer that returns an array of 10 probability scores that sum to 1. Each node contains a score that indicates the probability that the current image belongs to one of the 10 classes.

The difference between dense layers and sparse layers. Dense layers are fully connected, Sparse layers aren’t, like drop out operation.


Program Bug:

feed = {inputs_: x, labels_: y, keep_prob_: 0.5, learning_rate_: 
        learning_rate}

# Loss
loss, _, acc = sess.run([cost, optimizer, accuracy], feed_dict=feed)

TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, numpy ndarrays, or TensorHandles. For reference, the tensor object was Tensor(“Reshape_1:0”, shape=(100, 24, 1), dtype=float32) which was passed to the feed with key Tensor(“inputs:0”, shape=(?, 24, 1), dtype=float32).

How to solve this:

with tf.compat.v1.Session() as sess:
  sess.run(...)

the result of sess.run() is numpy ndarray rather than tensor. In this way, you can turn a tensor into a ndarray, but this isn’t a good way. You have to open multiple session and then close it.


What is a tensor:  Tensors

TensorFlow, as the name indicates, is a framework to define and run computations involving tensors. A tensor is a generalization of vectors and matrices to potentially higher dimensions. Internally, TensorFlow represents tensors as n-dimensional arrays of base datatypes.

tf.Tensorobject represents a partially defined computation that will eventually produce a value. TensorFlow programs work by first building a graph of tf.Tensor objects, detailing how each tensor is computed based on the other available tensors and then by running parts of this graph to achieve the desired results.

The difference between scalar and vector: 标量Scalar),又称纯量,是只有大小,没有方向,可用实数表示的一个量,实际上标量就是实数,标量这个称法只是为了区别与向量的差别。

The rank of a tf.Tensor object is its number of dimensions.

Rank Math entity
0 Scalar (magnitude大小 only)
1 Vector (magnitude and direction)
2 Matrix (table of numbers)
3 3-Tensor (cube of numbers)
n n-Tensor (you get the idea)

disscusion about tensor and ndarrays


the difference between validation set and test set. 

In machine learning, there are three sets: train set, validation set and test set. The train set is used for training the network/model (weights). The validation set is part of training process and it is used for parameter selection and avoiding overfitting (fine-tune the model). The test set is only use for performance evaluation about your model.  discussion about this question


TensorFlow session.

A tensorflow session is used to compute a graph. It has three parameters: (target, graph, config). If no graph arguments is specified, the default graph will be lauched. One session can only run one graph, but one graph can be used in multiple sessions.

# Launch the graph in a session.
sess = tf.compat.v1.Session()

with tf.Session(graph=graph) as sess:
    sess.run(tf.global_variables_initializer())

session.run([operation1, iperation2]): run this session and output the calculated result.


np.stack(); np.vstack(); np.hstack();

stack() is a function which join multiple arrays into one array/ sequence. When joining these arrays, the stacked array has one more dimention, and this dimention’s degree is the number of arrays.

stack((a,b,c), axis = 0/1/2); The first parameter is list of arrays. The second parameter is the dimention axis that increased. Return: The stacked array.

numpy.stack最通俗的理解

 

connect pycharm to remote server by using SSH interpreter

Project —– setting —— add ssh interpreter ——– input ssh hostname/user/password ——— add interpreter path (/opt/anaconda/envs/weda_py36/bin/python– the env path you created) ———— done.

Then your project will be uploaded to “\temp” directory.

To create your new environment in remote server. Managing environments

conda create -n my_env python=3.5

conda activate my_env/ source activate my_env (old version)

 

 

little knowledge

PyCharm is available in three editions. Community is the free edition but is limited to workflows typical in general scripting and scientific work. The educational edition is aimed at helping teachers create course assignments and tutorials for secondary school and college students. The professional edition of PyCharm includes tooling for database development, web development and advanced features such as performance profiling and remote debugging.

网段, 如何查看是不是同一网段,前两段相同基本代表同一网段。

数据库,桥。

ping

它是用来检查网络是否通畅或者网络连接速度的命令。作为一个生活在网络上的管理员或者黑客来说,ping命令是第一个必须掌握的DOS命令,它所利用的原理是这样的:利用网络上机器IP地址的唯一性,给目标IP地址发送一个数据包,再要求对方返回一个同样大小的数据包来确定两台网络机器是否连接相通,时延是多少。


SVM (support vector machine)

  1. 我们需要线找到数据点中距离分割超平面距离最近的点(找最小)
  2. 然后尽量使得距离超平面最近的点的距离的绝对值尽量的(求最大)

Coding experience

SVM: supervised learning; for classification and regression analysis.  an SVM training algorithm builds a model that assigns new examples to one category or the other, making it a non-probabilistic binary linear classifier 非概率性二元预测;

pandas中Dataframe的查询方法([], loc, iloc, at, iat, ix)

How do I create test and train samples from one dataframe with pandas?


little trap when coding

list.append(): no return. change the original list.

dataframe.append(): return a new dataframe object, do not change the original list.  So use df = df.append(df1).


The key functions are:

1566474068

Note The function read_sql() is a convenience wrapper around read_sql_table() and read_sql_query() (and for backward compatibility) and will delegate to specific function depending on the provided input (database table name or sql query). Table names do not need to be quoted if they have special characters.

ARIMA+ PostgreSQL+Residual block

Autoregressive_integrated_moving_average

时间序列预测之–ARIMA模型


PostgreSQl:

query: select * from table_name limit 100

 

select distinct: The DISTINCT clause is used in the SELECT statement to remove duplicate rows from a result set. The DISTINCT clause keeps one row for each group of duplicates. The DISTINCTclause can be used on one or more columns of a table.

The following illustrates the syntax of the DISTINCT clause:


序列建模(sequence modeling)是个很常见的问题,涉及语音处理,语言模型和时间序列预测等应用。在90年代其实就已经有工作采用卷积网络处理序列数据,使用一维卷积对序列中已出现的元素进行建模来预测未知的元素。但随后由于RNN模型的兴起,序列建模的任务转向使用RNN模型。RNN模型通过隐状态来实现对序列中已经出现的历史信息的记忆。后续提出的LSTM相对于RNN来说一定程度上解决了梯度消失问题,而且能更好的实现长期记忆。近期也涌现一些卷积网络用于序列相关工作,比如wavenet处理音频数据,gated cnn做语言模型等。

William Vorhies给出的原因如下:

RNN耗时太长,由于网络一次只读取、解析输入文本中的一个单词(或字符),深度神经网络必须等前一个单词处理完,才能进行下一个单词的处理。这意味着 RNN 不能像 CNN 那样进行大规模并行处理。

并且TCN的实际结果也要优于RNN算法。


自回归模型英语:Autoregressive model,简称AR模型),是统计上一种处理时间序列的方法,用同一变数例如{\displaystyle x}的之前各期,亦即{\displaystyle x_{1}}{\displaystyle x_{t-1}}来预测本期{\displaystyle x_{t}}的表现,并假设它们为一线性关系。因为这是从回归分析中的线性回归发展而来,只是不用{\displaystyle x}预测{\displaystyle y},而是{\displaystyle x}预测{\displaystyle x}(自己);所以叫做自回归


Introduction to 1D Convolutional Neural Networks in Keras for Time Sequences


Deep Residual Networks学习(一)  : 问题:1. 为什么会产生梯度爆炸和梯度消失的问题。应该有数学依据的(猜测)2. 右边图的第二个conv层还有用吗?3. 为什么H(x) = F(x)+x,即为什么两层卷积的值—H(x)等于一层卷积的值+输入值呢?;

给妹纸的深度学习教学(4)——同Residual玩耍

Residual blocks — Building blocks of ResNet


softmax regression: belongs to logistic regression problem. The softmax function is a function that takes as input a vector of K real numbers, and normalizes it into a probability distribution consisting of K probabilities proportional to the exponentials of the input numbers.

Understand the Softmax Function in Minutes

Recurrent nets

Recurrent nets

from blog1;

Recurrent nets are a type of artificial neural network designed to recognize patterns in sequences of data, such as text, genomes, handwriting, the spoken word, or numerical times series data emanating from sensors, stock markets and government agencies. These algorithms take time and sequence into account, they have a temporal dimension

CNN (feedforward) VS RNN: One feeds information straight through (never touching a given node twice), while the other cycles it through a loop, and the latter are called recurrent.

Recurrent networks, on the other hand, take as their input not just the current input example they see, but also what they have perceived previously in time.

The decision a recurrent net reached at time step t-1 affects the decision it will reach one moment later at time step t. So recurrent networks have two sources of input, the present and the recent past, which combine to determine how they respond to new data, much as we do in life.

That sequential information is preserved in the recurrent network’s hidden state, which manages to span many time steps as it cascades forward to affect the processing of each new example. It is finding correlations between events separated by many moments, and these correlations are called “long-term dependencies”, because an event downstream in time depends upon, and is a function of, one or more events that came before. One way to think about RNNs is this: they are a way to share weights over time.

Alt text

The hidden state at time step t is h_t. It is a function of the input at the same time step x_t, modified by a weight matrix W (like the one we used for feedforward nets) added to the hidden state of the previous time step h_t-1 multiplied by its own hidden-state-to-hidden-state matrix U, otherwise known as a transition matrix and similar to a Markov chain. The weight matrices are filters that determine how much importance to accord to both the present input and the past hidden state.

The sum of the weight input and hidden state is squashed by the function φ – either a logistic sigmoid function or tanh, depending – which is a standard tool for condensing very large or very small values into a logistic space, and making gradients workable for backpropagation.

Long Short-Term Memory Units (LSTMs)

LSTMs help preserve the error that can be backpropagated through time and layers. By maintaining a more constant error, they allow recurrent nets to continue to learn over many time steps (over 1000), thereby opening a channel to link causes and effects remotely.

LSTMs contain information outside the normal flow of the recurrent network in a gated cell. Information can be stored in, written to, or read from a cell, much like data in a computer’s memory. The cell makes decisions about what to store, and when to allow reads, writes and erasures, via gates that open and close. Unlike the digital storage on computers, however, these gates are analog, implemented with element-wise multiplication by sigmoids, which are all in the range of 0-1. Analog has the advantage over digital of being differentiable, and therefore suitable for backpropagation.

Those gates act on the signals they receive, and similar to the neural network’s nodes, they block or pass on information based on its strength and import, which they filter with their own sets of weights. Those weights, like the weights that modulate input and hidden states, are adjusted via the recurrent networks learning process. That is, the cells learn when to allow data to enter, leave or be deleted through the iterative process of making guesses, backpropagating error, and adjusting weights via gradient descent.

The diagram below illustrates how data flows through a memory cell and is controlled by its gates.

Alt text

the interpretation of structure  Understanding LSTM Networks

A common LSTM unit is composed of a cell, an input gate, an output gate and a forget gate. The cell remembers values over arbitrary time intervals and the three gates regulate the flow of information into and out of the cell.

a-list-of-cost-functions-used-in-neural-networks-alongside-applications