Heatmap is a powerful way to illustrate $ f = (x, y) $ data.
Seaborn
is famous in Python, but the domain of x and y is limited to1,2, ...
respectively. Anyway, you want to do it in any domain. I will explain how to do it with reference to scikit-learn sample code.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-2,2,0.1)
y = np.arange(-2,2,0.1)
xx,yy = np.meshgrid(x,y)
z = np.zeros((len(x),len(y)))
for i in range(len(x)):
for j in range(len(y)):
v = np.array([xx[i][j],yy[i][j]])
r = np.linalg.norm(v)
z[i][j] = np.exp(-r)
plt.figure(figsize=(5,5))
plt.contourf(x,y,z,cmap='coolwarm')
plt.show()
The content of the for statement is actually $ f (x, y) $, and in the sample code above, as an example,
Is implemented. It's complicated, so I've divided it into three lines, but what I'm doing is the same.
This works for all functions, but using the for statement is awkward. Above all, it is inconvenient because it does not correspond to the pattern that it is okay to run the matrix once and the shape of various machine learning prediction models (generally the number of data x input vector).
import numpy as np
import matplotlib.pyplot as plt
def model(xy):
ar = np.array([-2,1])
return np.matmul(xy,ar)
x = np.arange(-2,2,0.1)
y = np.arange(-2,2,0.1)
xx,yy = np.meshgrid(x,y)
xx = xx.reshape(-1,1)
yy = yy.reshape(-1,1)
xy = np.concatenate([xx,yy],1)
z = model(xy)
z = z.reshape(-1,len(x))
plt.figure(figsize=(5,5))
plt.contourf(x,y,z,cmap='coolwarm')
plt.show()
The shape of x and y is shaped. It looks like the figure below.
This format can accommodate functions such as lda.precdict ()
and model ()
(PyTorch, etc.).
If you use pcolormedh
instead of contourf
, the grid will be displayed. It looks pretty, but I personally prefer contourf
because it makes the data trends more difficult to understand.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-2,2,0.01) #Resolution 0.To 01
y = np.arange(-2,2,0.01) #Resolution 0.To 01
xx,yy = np.meshgrid(x,y)
z = np.zeros((len(x),len(y)))
for i in range(len(x)):
for j in range(len(y)):
v = np.array([xx[i][j],yy[i][j]])
r = np.linalg.norm(v)
z[i][j] = np.exp(-r)
plt.figure(figsize=(5,5))
plt.pcolormesh(x,y,z,cmap='coolwarm') #Change here
plt.show()
Recommended Posts