How to Build a Python Machine Learning Environment and Fit Your First Model
This tutorial walks through setting up a Python 2.7 machine learning environment with scikit-learn, installing required libraries, loading web traffic data, cleaning NaN entries, visualizing the data, performing a linear regression using SciPy's polyfit, and evaluating the model's fit.
This article explains how to set up a Python machine learning environment using Python 2.7 and the open‑source tools NumPy, SciPy, Matplotlib, and scikit‑learn.
First, install Python 2.7, then install the required packages (NumPy, SciPy, Matplotlib) and scikit‑learn 0.15, all of which can be downloaded from the provided Baidu Cloud links.
Next, read the web traffic data (a TSV file with 743 rows) using scipy.genfromtxt:
import scipy as sp data = sp.genfromtxt("web_traffic.tsv", delimiter="\t")Inspect the shape with print(data.shape) and notice that some rows contain nan values.
Remove invalid rows by filtering out NaNs:
x = data[:,0] y = data[:,1] x = x[~sp.isnan(y)] y = y[~sp.isnan(y)]Visualize the cleaned data with Matplotlib:
import matplotlib.pyplot as plt plt.scatter(x, y) plt.title("Web traffic over the last month") plt.xlabel("Time") plt.ylabel("Hits/hour") plt.show()Define an error function for regression:
def error(f, x, y): return sp.sum((f(x) - y) ** 2)Fit a first‑order polynomial (a straight line) to the data using polyfit:
fp1, residuals, rank, sv, rcond = sp.polyfit(x, y, 1, full=True)Print the residuals to see the fitting error and the resulting model: print(residuals) The fitted line is f(x) = 2.59619213 * x + 989.02487106.
Create a callable model with poly1d and plot the fitted line together with the data:
f1 = sp.poly1d(fp1) fx = sp.linspace(0, x[-1], 1000) plt.plot(fx, f1(fx), linewidth=4) plt.legend(["d=%i" % f1.order], loc="upper left") plt.show()The linear fit is clearly insufficient, illustrating the need for more advanced algorithms, which scikit‑learn provides.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
