Flashield's Blog

Just For My Daily Diary

Flashield's Blog

Just For My Daily Diary

01.exercise-a-single-neuron【练习:单神经元】

This notebook is an exercise in the Intro to Deep Learning course. You can reference the tutorial at this link.


Introduction

介绍

In the tutorial we learned about the building blocks of neural networks: linear units. We saw that a model of just one linear unit will fit a linear function to a dataset (equivalent to linear regression). In this exercise, you'll build a linear model and get some practice working with models in Keras.

在本教程中,我们了解了神经网络的构建模块:线性单元。 我们看到只有一个线性单元的模型就能将线性函数拟合到数据集(相当于线性回归)。 在本练习中,您将构建一个线性模型并进行一些在 Keras 中使用模型的练习。

Before you get started, run the code cell below to set everything up.

在开始之前,请运行下面的代码单元来设置所有内容。

# Setup plotting
import matplotlib.pyplot as plt

plt.style.use('seaborn-v0_8-whitegrid')
# Set Matplotlib defaults
plt.rc('figure', autolayout=True)
plt.rc('axes', labelweight='bold', labelsize='large',
       titleweight='bold', titlesize=18, titlepad=10)

# Setup feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.deep_learning_intro.ex1 import *
2024-04-15 08:29:04.245951: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
2024-04-15 08:29:04.246028: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
2024-04-15 08:29:04.247600: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered

The Red Wine Quality dataset consists of physiochemical measurements from about 1600 Portuguese red wines. Also included is a quality rating for each wine from blind taste-tests.

红酒质量数据集包含约 1600 种葡萄牙红酒的理化测量值。 还包括盲品测试中每种葡萄酒的质量评级。

First, run the next cell to display the first few rows of this dataset.

首先,运行下一个单元格以显示该数据集的前几行。

import pandas as pd

red_wine = pd.read_csv('../input/dl-course-data/red-wine.csv')
red_wine.head()
fixed acidity volatile acidity citric acid residual sugar chlorides free sulfur dioxide total sulfur dioxide density pH sulphates alcohol quality
0 7.4 0.70 0.00 1.9 0.076 11.0 34.0 0.9978 3.51 0.56 9.4 5
1 7.8 0.88 0.00 2.6 0.098 25.0 67.0 0.9968 3.20 0.68 9.8 5
2 7.8 0.76 0.04 2.3 0.092 15.0 54.0 0.9970 3.26 0.65 9.8 5
3 11.2 0.28 0.56 1.9 0.075 17.0 60.0 0.9980 3.16 0.58 9.8 6
4 7.4 0.70 0.00 1.9 0.076 11.0 34.0 0.9978 3.51 0.56 9.4 5

You can get the number of rows and columns of a dataframe (or a Numpy array) with the shape attribute.

您可以使用shape属性获取数据框(或 Numpy 数组)的行数和列数。

red_wine.shape # (rows, columns)
(1599, 12)

1) Input shape

1) 输入形状

How well can we predict a wine's perceived quality from the physiochemical measurements?

我们如何通过理化测量来预测葡萄酒的感知质量?

The target is 'quality', and the remaining columns are the features. How would you set the input_shape parameter for a Keras model on this task?

目标是质量,其余列是功能。 您将如何在此任务中为 Keras 模型设置input_shape参数?

# YOUR CODE HERE
# input_shape = ____
input_shape = (11,)

# Check your answer
q_1.check()

Correct

# Lines below will give you a hint or solution code
#q_1.hint()
q_1.solution()

Solution:


input_shape = [11]
# you could also use a 1-tuple, like input_shape = (11,)

2) Define a linear model

2) 定义线性模型

Now define a linear model appropriate for this task. Pay attention to how many inputs and outputs the model should have.

现在定义适合此任务的线性模型。 注意模型应该有多少输入和输出。

from tensorflow import keras
from tensorflow.keras import layers

# YOUR CODE HERE
# model = ____
model = keras.Sequential([
    layers.Dense(units=1, input_shape=input_shape)
])

# Check your answer
q_2.check()

Correct

# Lines below will give you a hint or solution code
#q_2.hint()
q_2.solution()

Solution:


from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Dense(units=1, input_shape=[11])
])

3) Look at the weights

3) 查看权重

Internally, Keras represents the weights of a neural network with tensors. Tensors are basically TensorFlow's version of a Numpy array with a few differences that make them better suited to deep learning. One of the most important is that tensors are compatible with GPU and TPU) accelerators. TPUs, in fact, are designed specifically for tensor computations.

在内部,Keras 表示具有 张量 的神经网络的权重。 张量基本上是 TensorFlow 版本的 Numpy 数组,但有一些差异,使它们更适合深度学习。 最重要的之一是张量与 GPU 和 [TPU](https://www.kaggle.com/docs/ tpu)) 加速器。 事实上,TPU 是专门为张量计算而设计的。

A model's weights are kept in its weights attribute as a list of tensors. Get the weights of the model you defined above. (If you want, you could display the weights with something like: print("Weights\n{}\n\nBias\n{}".format(w, b))).

模型的权重作为张量列表保存在其weights属性中。 获取上面定义的模型的权重。 (如果需要,您可以使用类似以下内容的方式显示权重:print("Weights\n{}\n\nBias\n{}".format(w, b)))。

# YOUR CODE HERE
# w, b = ____
# 这里是初始化的权重和偏移量
w, b = model.weights

# Check your answer
q_3.check()

Correct: Do you see how there's one weight for each input (and a bias)? Notice though that there doesn't seem to be any pattern to the values the weights have. Before the model is trained, the weights are set to random numbers (and the bias to 0.0). A neural network learns by finding better values for its weights.

# Lines below will give you a hint or solution code
#q_3.hint()
q_3.solution()

Solution:


# Uncomment if you need the model from the previous question:
# model = keras.Sequential([
#     layers.Dense(units=1, input_shape=[11])
# ])

w, b = model.weights

print("Weights\n{}\n\nBias\n{}".format(w, b))

(By the way, Keras represents weights as tensors, but also uses tensors to represent data. When you set the input_shape argument, you are telling Keras the dimensions of the array it should expect for each example in the training data. Setting input_shape=[3] would create a network accepting vectors of length 3, like [0.2, 0.4, 0.6].)

(顺便说一句,Keras 将权重表示为张量,但也使用张量来表示数据。当您设置input_shape参数时,您是在告诉 Keras 对于训练数据中的每个示例应该期望的数组维度。设置 input_shape=[3] 将创建一个接受长度为 3 的向量的网络,例如 [0.2, 0.4, 0.6]。)

Optional: Plot the output of an untrained linear model

可选:绘制未经训练的线性模型的输出

The kinds of problems we'll work on through Lesson 5 will be regression problems, where the goal is to predict some numeric target. Regression problems are like "curve-fitting" problems: we're trying to find a curve that best fits the data. Let's take a look at the "curve" produced by a linear model. (You've probably guessed that it's a line!)

我们将在第 5 课中解决的问题类型将是回归问题,其目标是预测某些数字目标。 回归问题就像曲线拟合问题:我们试图找到最适合数据的曲线。 我们来看看线性模型产生的曲线。 (您可能已经猜到这是一条线!)

We mentioned that before training a model's weights are set randomly. Run the cell below a few times to see the different lines produced with a random initialization. (There's no coding for this exercise -- it's just a demonstration.)

我们提到在训练之前模型的权重是随机设置的。 运行下面的单元几次,查看随机初始化生成的不同行。 (本练习没有编码——这只是一个演示。)

import tensorflow as tf
import matplotlib.pyplot as plt

model = keras.Sequential([
    layers.Dense(1, input_shape=[1]),
])

x = tf.linspace(-1.0, 1.0, 100)
y = model.predict(x)

plt.figure(dpi=100)
plt.plot(x, y, 'k')
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.xlabel("Input: x")
plt.ylabel("Target y")
w, b = model.weights # you could also use model.get_weights() here
plt.title("Weight: {:0.2f}\nBias: {:0.2f}".format(w[0][0], b[0]))
plt.show()
4/4 [==============================] - 0s 2ms/step

png

Keep Going

Add hidden layers and make your models deep in Lesson 2.

继续前进

在第 2 课中添加隐藏层并使模型更深入

01.exercise-a-single-neuron【练习:单神经元】

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top