# Linear Regression using Python

Whoever wants to learn machine learning or become a data scientist, the most obvious thing to learn in the first time is linear regression. Linear regression is the simplest machine learning algorithm and it is generally used for forecasting. The goal of linear regression is to find a relationship between one or more independent variables and a dependent variable by fitting the best line. This best fit line is known as regression line and defined by a linear equation Y= a *X + b.

For instance, in the case of the height of children vs their age. After collecting the data of children height and their age in months, we can plot the data in a scatter plot such as in Figure below. Linear regression will find the relationship between age as the independent variable and height as the dependent variable. Linear regression will find the best fit line from all points on the scatter plot. Finally, it can be used as a prediction, for instance, to predict what height the children when his age enter 35 months?

How to implement this linear regression in Python?

First, to make easier, I will generate a random dataset for our experiment.

```
import pandas as pd
import numpy as np

np.random.seed(0)
x = np.random.rand(100, 1) #generate random number for x variable
y = 2 + 3 * x + np.random.rand(100, 1) # generate random number of y variable
x[:10], y[:10] #Show the first 10 rows of each x and y

``` There are many ways to build a regression model, we can build it from scratch or just use the library from Python. In this example, I use scikit-learn

```
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from matplotlib import pyplot as plt

# Initialize the model
model = LinearRegression()
# Train the model - fit the data to the model
model.fit(x, y)
# Predict
y_predicted = model.predict(x)

# model evaluation
rmse = mean_squared_error(y, y_predicted)
r2 = r2_score(y, y_predicted)

# printing values
print('Slope:' ,model.coef_)
print('Intercept:', model.intercept_)
print('Root mean squared error: ', rmse)
print('R2 score: ', r2)

# plotting values
plt.scatter(x, y, s=5)
plt.xlabel('x')
plt.ylabel('y')

# predicted values
plt.plot(x, y_predicted, color='r')
plt.show()

``` Tarraaa!, it’s easy right?

See you next time

# Read the data and plotting with multiple markers

Just assume we have excel data and we want to plot it on a line chart with different markers. Why markers? just imagine, we have plotted a line chart with multiple lines by different colour, but we only have black and white ink, after printing, all lines will be in black colour. That’s why we need markers. For instance, our data can be seen in the Table above, this data about algorithms performance vs. the number of k. I want to plot this data to the line chart.  We already have the previous experiment, how to plot the line chart with multiple lines and multiple styles. However, in the previous experiment, we used the static declaration for each line. It will be hard if we have to declare one by one for each line.

Let’s just start to code..

The first step is to load Excel data to the DataFrame in pandas.

```
import pandas as pd
import numpy as np

import matplotlib as mpl

xl = pd.ExcelFile("Experiment_results.xlsx")

``` It’s very easy to load the Excel data to DataFrame, we can use some parameters which very useful such as sheet name, header, an index column. In this experiment, I use “Sheet2″ due to my data in the Sheet2, and I use ”1″ as the header parameter which means I want to load the header to the DataFrame, and if you don’t want to load it just fill it with ”0″. I also use index_col equal to “0”, which means I want to use the first column in my Excel dataset as the index in my DataFrame. Now we have a dataframe that can be seen in the Table above.

The second step is how to set the markers. As I said in the previous experiment that matplotlib supports a lot of markers. Of course, I don’t want to define one by one manually. Let see the code below:

```
# create valid markers from mpl.markers
valid_markers = ([item for item in mpl.markers.MarkerStyle.markers.items() if
item is not 'nothing' and not item.startswith('tick') and not item.startswith('caret')])

# valid_markers = mpl.markers.MarkerStyle.filled_markers

markers = np.random.choice(valid_markers, df.shape, replace=False)

```

Now, we have a list of markers inside the ‘markers’ variable. We need to select the markers randomly which are defined by df.shape (the number of columns). Let start to plot the data.

```
ax = df.plot(kind='line')
for i, line in enumerate(ax.get_lines()):
line.set_marker(markers[i])

ax.legend(ax.get_lines(), df.columns, loc='best')
plt.show()

```

Taraaaa!!!!, it’s easy, right? # Python for Data Science

I have been two years doing processing and manipulating data using R and mostly I use this language for my research project. I only heard and never tried Python to analyze my data before. But now, after I use Python, I really fall in love with this language. Python is very simple and it is been known that this language is the easiest one to be learned. The reason why previously I used R was this language supported by tons of libraries for scientific analysis and all of those are open source. Now, with the popularity of Python, all libraries that I need, I can find it easily in Python and all of them open source as well.

There are the core libraries that you must know when you start to do data analytics using Python:

1. NumPy, it stands for Numerical Python. Python is different with R, the purpose of R language is for scientist and on the other side, Python is just the general programming language. So, it is needed a library which can handle numerical things such as complex arrays and matrics in Python. Repo project link: https://github.com/numpy/numpy
2. SciPy, this library is for scientific and it handles such as statistic computing, linear algebra, optimation etc. Repo project link: https://github.com/scipy/scipy
3. Pandas, when you ever play with R, it is very similar with DataFrame. By using DataFrame, we can easily to manipulate, aggregate, and doing analysis on our dataset. The data will be shown in a table like in Excel or DataFrame in R and it convenient to access the data by columns, rows or else. Repo project link: https://github.com/pandas-dev/pandas
4. Matplotlib, Plotting is very important for data analysis. To make the data easy to read by people and we know that one picture can descript 1000 words, we absolutely need the data visualization tools. If you have experience with Excel, it is very easy, just block the table that you want to plot and select the plotting types such as Bar chart, line chart, etc. In R the most popular tools for plotting is ggplot, basically, you can use standard library ‘plot’ in R but if you want more advanced and more beautiful figure you need to use ggplot.  This library is the basic library for visualizing your data similar as I explained above, Repo project link: https://github.com/matplotlib/matplotlib

Those are the core basic libraries that you need when you start to use this language for data analytics. There are still many libraries that very useful such as:

1. SciKit-Learn, when you want to apply machine learning on your data analytics.
2. Scrapy, to scrap the data from the internet, when you want to gather the data from websites for your analysis. I used tweepy library to collect tweets data from Twitter.
3. NLTK, if you want to do natural language processing.
4. Theano, Tensorflow, Keras, when you are not satisfied with NumPy performance or want to apply neural network algorithm or doing deep learning stuff, these libraries are very useful for it.
5. Interactive Visualization Tools, matplotlib is basic plotting tools and it is enough for me as researcher especially for publications, but when you want a dynamic plotting or more interactively you can use Seaborn, Ploty, or Bokeh. #### If you are a lazy guy like me to install all the stuff above, you can try to use Anaconda, it is really cool.

See ya on the next post..

Brisbane, 24 November 2017

# Python for Data Science Cheat Sheet

Berikut adalah Python for Data Science Cheat Sheet yang cukup membantu untuk merefresh ingatan kita atau bagi yang baru awal menggunakan Python untuk analisis data, mining data atau data science bisa dijadikan bahan bacaan.

Python Basic for Data Science

Berikut Cheat Sheet nya: Python NumPy Cheat Sheet

Berikut Cheat Sheet gambarnya: Python Pandas Cheat Sheet

Berikut Cheat Sheet gambarnya: Python Bokeh Interactive Visualization Cheat Sheet

Berikut Cheat Sheet gambarnya: 