# -*- coding: utf-8 -*-
"""
Created on Wed Feb 8 07:14:31 2023
@author: Dell
"""
import tensorflow as tf
import numpy as np
from d2l import tensorflow as d2l
from matplotlib_inline import backend_inline
print('选择对于模型参数可微的损失函数')
def f(x):
return 3*x**2 -4*x
def numerical_lim(f,x,h):
return (f(x+h)-f(x))/h
def use_svg_display(): #@save
backend_inline.set_matplotlib_formats('svg')
def set_figsize(figsize=(3.5,2.5)): #@save
use_svg_display()
d2l.plt.rcParams['figure.figsize']=figsize
#@save
def set_axes(axes,xlabel,ylabel,xlim,ylim,xscale,yscale,legend):
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
axes.set_ylim(ylim)
axes.set_xlim(xlim)
axes.set_xscale(xscale)
axes.set_yscale(yscale)
if(legend):
axes.legend(legend)
axes.grid()
#@save
def plot(X,Y=None,xlabel=None,ylabel=None,legend=None,xlim=None,ylim=None,
xscale='linear',yscale='linear',fmts=('-','m--','g-','r:'),figsize=(3.5,2.5)
,axes=None):
if legend is None:
legend = []
set_figsize(figsize)
axes = axes if axes else d2l.plt.gca()
def has_one_axis(X):
return (hasattr(X, "ndim") and X.ndim == 1 or isinstance(X, list)
and not hasattr(X[0], "__len__"))
if has_one_axis(X):
X = [X]
if Y is None:
X, Y = [[]] * len(X), X
elif has_one_axis(Y):
Y = [Y]
if len(X) != len(Y):
X = X * len(Y)
axes.cla()
for x, y, fmt in zip(X, Y, fmts):
if len(x):
axes.plot(x, y, fmt)
else:
axes.plot(y, fmt)
set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
h = 0.1
for i in range(5):
print(f'h = {h:.5f},numerical limit = {numerical_lim(f,1,h):.5f}')
h*=0.1
x = np.arange(0, 3, 0.1)
plot(x, [f(x), 2 * x - 3], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])
tensorflow 微积分
于 2023-02-16 08:08:12 首次发布