This post is Private. Only a writer or those who know its URL can access this post.

Article information
Show article in Markdown
Report article
Help us understand the problem. What is going on with this article?

# プログラミング問題集解答例（問３２）

import numpy as np
f = lambda x: (x[0] - 1)**2 + 2 * (x[1] + 1)**2
g = lambda x: (x[0]**4 + 2 * x[0]**2 + 1) * (x[1]**2 + 2 * x[1] + 1)
%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
x_latent = np.linspace(-20, 20, 100)
y_latent = np.linspace(-20, 20, 100)

X1, X2 = np.meshgrid(x_latent, y_latent)
X = np.c_[np.ravel(X1), np.ravel(X2)]
Y_plot = np.array([f(x) for x in X])
Y_plot = Y_plot.reshape(X1.shape)

fig = plt.figure()
surf = ax.plot_surface(X1, X2, Y_plot, cmap='bwr', linewidth=0)
fig.colorbar(surf)
ax.set_title("Surface Plot")
fig.show()

import numpy as np
def numerical_partial_differential(f, x):
h = 1e-4
for idx_i in range(len(x)):
tmp_val = x[idx_i]

# f(x+h)
x[idx_i] = tmp_val + h
fxh1 = f(x)

# f(x-h)
x[idx_i] = tmp_val - h
fxh2 = f(x)

grad[idx_i] = (fxh1 - fxh2) / (2 * h)
x[idx_i] = tmp_val
x_history = []
x = init_x
for i in range(step_num):
x_history.append(x)
x = x - lr * grad
return x
x_history = []
init_x = np.array([10.0, 10.0])
minimum = f(x_optimum)
x_optimum, minimum
(array([ 1., -1.]), 3.3611075964934582e-18)
plt.grid()

plt.plot(x_history)
plt.grid()

plt.grid()

plt.plot([x[0] for x in x_history], [x[1] for x in x_history], marker='x')
plt.grid()

x_latent = np.linspace(-20, 20, 100)
y_latent = np.linspace(-20, 20, 100)

X1, X2 = np.meshgrid(x_latent, y_latent)
X = np.c_[np.ravel(X1), np.ravel(X2)]
Y_plot = np.array([g(x) for x in X])
Y_plot = Y_plot.reshape(X1.shape)

fig = plt.figure()
surf = ax.plot_surface(X1, X2, Y_plot, cmap='bwr', linewidth=0)
fig.colorbar(surf)
ax.set_title("Surface Plot")
fig.show()

x_history = []
init_x = np.array([10.0, 10.0])
minimum = g(x_optimum)
x_optimum, minimum
(array([ 1., -1.]), 0.0)
plt.grid()

plt.plot(x_history)
plt.grid()

plt.grid()

plt.plot([x[0] for x in x_history], [x[1] for x in x_history], marker='x')
plt.grid()

Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away