日撸 Java 三百行day1-10
Posted fulisha_la
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了日撸 Java 三百行day1-10相关的知识,希望对你有一定的参考价值。
文章目录
说明
闵老师的文章链接: 日撸 Java 三百行(总述)_minfanphd的博客-CSDN博客
自己也把手敲的代码放在了github上维护:https://github.com/fulisha-ok/sampledata
day1 环境搭建
1.1 开发环境
在搭建java环境时,从官网下载了java安装包安装成功后,一定要正确配置环境变量
1.2 package import 和 println
(1)package包:就好似我们日常生活中的”收纳盒“,不同的”收纳盒“装不同的”物品“,方便我们查找和定位。在大”收纳盒“中有包含各种小”收纳盒“,这也体现了包是以树形结构存储的。
package com //一个主包
package com.project //主包下建一个项目工程包
package com.project.util //一个工具包,util工具包在com目录下的project目录中
(2)import:导入包成员,在写一个java类时,我们需用到其他包中的成员,此时就需要通过import导入相应的包,则就好似c语言需要导入头文件,才能用一些库里的函数
import java.util.ArrayList;; //导入Java util包下的ArrayList 那则可以用这个类中一些方法,变量
import java.util.*; //导入util包下所有的东西,那我们使用的范围就比上面这个更多
(3)println:打印输出语句,且在输出后会自动换行,若不换行则是print
1.3 编写HelloWorld.java
main函数是程序入口
package basic;
public class HellowWorld
public static void main(String[] args)
System.out.println("Hello, World");
day2 基本算术操作
2.1 加、减、乘、除、整除、取余.
package basic;
public class BasicOperations
public static void main(String args[])
int tempFirstInt, tempSecondInt, tempResultInt;
double tempFirstDouble, tempSecondDouble, tempResultDouble;
tempFirstInt = 15;
tempSecondInt = 4;
tempFirstDouble = 1.2;
tempSecondDouble = 3.5;
//Addition
tempResultInt = tempFirstInt + tempSecondInt;
tempResultDouble = tempFirstDouble + tempSecondDouble;
System.out.println("" + tempFirstInt + " + " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " + " + tempSecondDouble + " = " + tempResultDouble);
//Subtraction
tempResultInt = tempFirstInt - tempSecondInt;
tempResultDouble = tempFirstDouble - tempSecondDouble;
System.out.println("" + tempFirstInt + " - " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " - " + tempSecondDouble + " = " + tempResultDouble);
//Multiplication
tempResultInt = tempFirstInt * tempSecondInt;
tempResultDouble = tempFirstDouble * tempSecondDouble;
System.out.println("" + tempFirstInt + " * " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " * " + tempSecondDouble + " = " + tempResultDouble);
//Division
tempResultInt = tempFirstInt / tempSecondInt;
tempResultDouble = tempFirstDouble / tempSecondDouble;
System.out.println("" + tempFirstInt + " / " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " / " + tempSecondDouble + " = " + tempResultDouble);
//Modulus
tempResultInt = tempFirstInt % tempSecondInt;
System.out.println("" + tempFirstInt + " % " + tempSecondInt + " = " + tempResultInt);
day3 基本if 语句
3.1 if条件分支语句
其中,if中的表达式应该为布尔表达式。这里会存在三种不同选择。(假设在if中会有数据的处理)
第一,只使用if语句,这相当于我只过滤我想要的数据;
第二:if…else 语句,(不入if就进else, 非真即假)
第三:if…else if…else 语句,这就是多条件分支判断。对不同条件进行判断
3.2 代码
package basic;
public class IfStatement
/**
* The entrance of the program
* @param args
*/
public static void main(String args[])
int tempNumber1, tempNumber2;
// Try a positive value
tempNumber1 = 5;
if (tempNumber1 >= 0)
tempNumber2 = tempNumber1;
else
tempNumber2 = -tempNumber1;
// Of if
System.out.println("The absolute value of " + tempNumber1 + " is " + tempNumber2);
// Try a negative value
// Lines 27 through 33 are the same as Lines 15 through 19
tempNumber1 = -3;
if (tempNumber1 >= 0)
tempNumber2 = tempNumber1;
else
tempNumber2 = -tempNumber1;
// Of if
System.out.println("The absolute value of " + tempNumber1 + " is " + tempNumber2);
// Now we use a method/function for this purpose.
tempNumber1 = 6;
System.out.println("The absolute value of " + tempNumber1 + " is " + abs(tempNumber1));
tempNumber1 = -8;
System.out.println("The absolute value of " + tempNumber1 + " is " + abs(tempNumber1));
/**
* @param paraValue The given value.
* @return The absolute value of the given parameter.
*/
public static int abs(int paraValue)
if (paraValue >= 0)
return paraValue;
else
return -paraValue;
day4 闰年的计算
4.1 思路整理:何为闰年?
(1)非世纪年(不能被100整除的年份)能被4整除且不能被100整除的年份为闰年
(2)世纪年 能被400整除的才是闰年
文中给出两种计算闰年的方法,结合day3的if语句,第一种把所有逻辑判断放在一个if中完成,会使用一些与或非逻辑运算,如果逻辑判断条件过多,如果放在一个if判断中则会增加代码的可维护性,但第二种方法是一个条件一个条件判断,如果其中有一个不满足就退出,这样是根据if-else if顺序执行,来判断只有有不符合条件就退出、
4.2 核心代码
/**
* @param paraYear
* @return Is the given year leap? true or false;
*/
public static boolean isLeapYear(int paraYear)
if ((paraYear % 4 == 0) && (paraYear % 100 != 0) || (paraYear % 400 == 0))
return true;
else
return false;
/**
* @param paraYear
* @return Is the given year leap? Replace the complex condition with a number of if. return true or false
*/
public static boolean isLeapYearV2(int paraYear)
if (paraYear % 4 != 0)
return false;
else if (paraYear % 400 == 0)
return true;
else if (paraYear % 100 == 0)
return false;
else
return true;
day5 基本switch 语句
5.1 switch也属于条件分支语句
switch中表达式的值去和case后的值做匹配,若匹配正确则执行其后需要执行代码,遇到break结束执行。若没有case匹配,则最后就会执行default,default 分支不需要 break 语句
5.2 思考
(1)每一个case后都要跟break吗?
答案是否定的。不加break的话将会跳转到相应的case去执行且其以下的所有语句。
(2)switch和if条件语句有什么区别呢?
最明显差异是表示执行的结构,if中的表达式结果只能是boolean类型,而switch恰恰相反,他表示式结果可以是int,char等。我在实际使用过程中if语句用的比较多,但涉及到判断的if分支较多时,我会考率使用switch,这样效率会高一点
day6 基本for 语句
6.1 for语句中表达式的执行顺序
for(a;b;c)其中a,b,c为表达式,执行顺序:先执行a表达式,一般为初始化语句,再执行b表达式,一般式判断表达式,若为ture去执行循环体,执行完再执行c表达式,若不满足b表达式,则跳出循环。
6.2 代码
package basic;
public class ForStatement
/**
* The entrance of the program.
* @param args
*/
public static void main(String[] args)
forStatementTest();
/**
* Method unit test.
*/
public static void forStatementTest()
int tempN = 0;
System.out.println("1 add to " + tempN + " is: " + addToN(tempN));
tempN = 0;
System.out.println("1 add to " + tempN + " is: " + addToN(tempN));
int tempStepLength = 1;
tempN = 10;
System.out.println("1 add to " + tempN + " with step length " + tempStepLength + " is: "
+ addToNWithStepLength(tempN, tempStepLength));
tempStepLength = 2;
System.out.println("1 add to " + tempN + " with step length " + tempStepLength + " is: "
+ addToNWithStepLength(tempN, tempStepLength));
/**
* Add from 1 to N.
* @param paraN The given upper bound.
* @return The sum.
*/
public static int addToN(int paraN)
int resultSum = 0;
for (int i = 1; i <= paraN; i++)
resultSum += i;
return resultSum;
/**
* Add from 1 to N with a step length.
* @param paraN The given upper bound.
* @param paraStepLength paraStepLength The given step length.
* @return The sum.
*/
public static int addToNWithStepLength(int paraN, int paraStepLength)
int resultSum = 0;
for (int i = 1; i <= paraN; i += paraStepLength)
resultSum += i;
return resultSum;
day7 矩阵元素相加
7.1 题目解读
矩阵用二维数组存储,计算二维数组的和,计算两个二维数组对应行列相加组成一个新的二维数组,都需要用到for循环遍历(行优先);对矩阵的赋值也需要循环遍历赋初值,在有循环时要避免死循环,确保循环是有限性的。
7.2 二维数组中
int[][] tempMatrix = new int[3][4];
tempMatrix.length; //代表行的长度
tempMatrix[0].length; //代表列的长度
代码:
package basic;
import java.util.Arrays;
public class MatrixAddition
public static void main(String[] args)
matrixElementSumTest();
matrixAdditionTest();
/**
* Sum the elements of a matrix.
* @param paraMatrix
* @return The sum of all its elements.
*/
public static int matrixElementSum(int[][] paraMatrix)
int resultSum = 0;
for (int i = 0; i < paraMatrix.length; i++)
for (int j = 0; j < paraMatrix[0].length; j++)
resultSum += paraMatrix[i][j];
return resultSum;
/**
* Unit test for respective method
*/
public static void matrixElementSumTest()
int[][] tempMatrix = new int[3][4];
for (int i = 0; i < tempMatrix.length; i++)
for (int j = 0; j < tempMatrix[0].length; j++)
tempMatrix[i][j] = i * 10 + j;
System.out.println("The matrix is: \\r\\n" + Arrays.deepToString(tempMatrix));
System.out.println("The matrix element sum is: " + matrixElementSum(tempMatrix) + "\\r\\n");
/**
* Add two matrices. Attention: NO error check is provided at this moment.
* @param paraMatrix1 The first matrix.
* @param paraMatrix2 The second matrix. It should have the same size as the first one's
* @return The addition of these matrices.
*/
public static int[][] matrixAddition(int[][] paraMatrix1, int[][] paraMatrix2)
int[][] resultMatrix = new int[paraMatrix1.length][paraMatrix1[0].length];
for (int i = 0; i < paraMatrix1.length; i++)
for (int j = 0; j < paraMatrix1[0].length; j++)
resultMatrix[i][j] = paraMatrix1[i][j] + paraMatrix2[i][j];
return resultMatrix;
/**
* Unit test for respective method.
*/
public static void matrixAdditionTest()
int[][] tempMatrix = new int[3][4];
for (int i = 0; i < tempMatrix.length; i++)
for (int j = 0; j < tempMatrix[0].length; j++)
tempMatrix[i][j] = i * 10 + j;
System.out.println("The matrix is: \\r\\n" + Arrays.deepToString(tempMatrix));
int[][] tempNewMatrix = matrixAddition(tempMatrix, tempMatrix);
System.out.println("The new matrix is: \\r\\n" + Arrays.deepToString(tempNewMatrix));
day8 矩阵相乘
8.1 题目解读
矩阵相乘(只有第一个矩阵的列和第二个矩阵的行相等): a矩阵(mn),b矩阵(np)则能相乘,且相乘后的矩阵为m*p。故在矩阵相乘是在一定条件下才能进行,需要用到if判断。
8.2代码
package basic;
import java.util.Arrays;
public class MatrixMultiplication
public static void main(String[] args)
matrixMultiplicationTest();
/**
* Matrix multiplication. The columns of the first matrix should be equal to the rows of the second one.
* @param paraFirstMatrix The first matrix.
* @param paraSecondMatrix The second matrix
* @return The result matrix.
*/
public static int[][] multiplication(int[][] paraFirstMatrix, int[][] paraSecondMatrix)
//m*n n*p == m*p
int m = paraFirstMatrix.length;
int n = paraFirstMatrix[0].length;
int p = paraSecondMatrix[0].length;
// Step 1. Dimension check.
if (paraSecondMatrix.length != n)
System.out.println("The two matrices cannot be multiplied.");
return null;
// Step 2. The loop. m*n n*p == m*p
int[][] resultMatrix = new int[m][p];
for (int i = 0; i < m; i++)
for (int j = 0; j < p; j++)
for (int k = 0; k < n; k++)
resultMatrix[i][j] += paraFirstMatrix[i][k] * paraSecondMatrix[k][j];
return resultMatrix;
public static void matrixMultiplicationTest()
int[][] tempFirstMatrix = new int[2][3];
for (int i = 0; i < tempFirstMatrix.length; i++)
for (int j = 0; j < tempFirstMatrix[0].length; j++)
tempFirstMatrix[i][j] = i + j;
System.out.println("The first matrix is: \\r\\n" + Arrays.deepToString(tempFirstMatrix));
int[][] tempSecondMatrix = new int[3][2];
for (int i = 0; i < tempSecondMatrix.length; i++)
for (int j = 0; j < tempSecondMatrix[0].length; j++)
tempSecondMatrix[i][j] = i * 10 + j;
System.out.println("The second matrix is: \\r\\n" + Arrays.deepToString(tempSecondMatrix));
int[][] tempThirdMatrix = multiplication(tempFirstMatrix, tempSecondMatrix);
System.out.println("The third matrix is: \\r\\n" + Arrays.deepToString(tempThirdMatrix));
System.out.println("Trying to multiply the first matrix with itself.\\r\\n");
tempThirdMatrix = multiplication(tempFirstMatrix, tempFirstMatrix);
System.out.println("The result matrix is: \\r\\n" + Arrays.deepToString(tempThirdMatrix));
day9 while 语句
代码
还有一种循环是 do…while,其循环至少要执行一次循环体,而for和while循环需要先判断条件是否成立 在决定是否执行循环语句
package basic;
public class WhileStatement
public static void main(String[] args)
whileStatementTest();
/**
* The sum not exceeding a given value.
*/
public static void whileStatementTest()
int tempMax = 100;
int tempValue = 0;
int tempSum = 0;
// Approach 1.
while (tempSum <= tempMax)
tempValue++;
tempSum += tempValue;
System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
tempSum -= tempValue;
System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);
// Approach 2.
System.out.println("\\r\\nAlternative approach.");
tempValue = 0;
tempSum = 0;
while (true)
tempValue++;
tempSum += tempValue;
System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
if (tempMax < tempSum)
break;
tempSum -= tempValue;
System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);
day10 综合任务 1
10.1 题目解读
学生的成绩存放于一个矩阵,其中行表示学生,列表示科目。如:第 0 行表示第 0 个学生的数学、语文、英语成绩。要求:进行学生成绩的随机生成, 区间为 [50, 100];找出成绩最好、最差的同学。但有挂科的同学不参加评比.
- 1.初始化学生成绩(会涉及到随机生成数据的区间范围:Random)
- 2.通过for循环来计算学生总成绩并排除挂科同学(借助:break,continue关键字)
- 3.for循环+if判断来找出成绩最好和最差的学生
10.2 代码
package basic;
import java.util.Arrays;
import java.util.Random;
public class Task1
public static void main(String[] args)
task1();
public static void task1()
//step1:Generate the data with n students and m courses.
int n = 10;
int m = 3;
int lowerBound = 50;
int upperBound = 100;
int threshold = 60;
// Here we have to use an object to generate random numbers.
Random tempRandom = new Random();
int[][] data = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
data[i][j] = lowerBound + tempRandom.nextInt(upperBound - lowerBound);
System.out.println("The data is:\\r\\n" + Arrays.deepToString(data));
// Step 2. Compute the total score of each student.
int[] totalScores = new int[n];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (data[i][j] < threshold)
totalScores[i] = 0;
break;
totalScores[i] += data[i][j];
System.out.println("The total scores are:\\r\\n" + Arrays.toString(totalScores));
// Step 3. Find the best and worst student.
// Typical initialization for index: invalid value.
int tempBestIndex = -1;
int tempWorstIndex = -1;
// Typical initialization for best and worst values.
// They must be replaced by valid values.
int tempBestScore = 0;
int tempWorstScore = m * upperBound + 1;
for (int i = 0; i < n; i++)
// Do not consider failed students.
if (totalScores[i] == 0)
continue;
if (tempBestScore < totalScores[i])
tempBestScore = totalScores[i];
tempBestIndex = i;
// Attention: This if statement cannot be combined with the last one using "else if", because a student can be both the best and the
// worst. I found this bug while setting upperBound = 65.
if (tempWorstScore > totalScores[i])
tempWorstScore = totalScores[i];
tempWorstIndex = i;
// Step 4. Output the student number and score.
if (tempBestIndex == -1)
System.out.println("Cannot find best student. All students have failed.");
else
System.out.println("The best student is No." + tempBestIndex + " with scores: "
+ Arrays.toString(data[tempBestIndex]));
if (tempWorstIndex == -1)
System.out.println("Cannot find worst student. All students have failed.");
else
System.out.println("The worst student is No." + tempWorstIndex + " with scores: "
+ Arrays.toString(data[tempWorstIndex]));
自我小结
三大结构
不管在c或者java,都会涉及到三大结构:顺序结构,选择结构,分支结构;通过对这三大结构的组合使用就可以解决一些很复杂的问题。
(1) 顺序结构:即按照代码的书写顺序依次执行,不存在跳转或者判断
- 要避免代码冗余,可以通过封装相应的方法或类来避免;例如day4中我们可以专门封装一个方法来判断是否为闰年,而避免每次都去重复写来判断
- 需要注意变量的使用范围等。例如day4中main方法中变量tempYear,正因为代码会顺序执行,所以可以对tempYear多次赋值从而覆盖前面的值。
(2)选择结构:会根据指定的判定条件去执行不同的代码块内容,如在day3,day4:if结构;if-else结构;if-else if结构;day5:switch结构
- 在选择结构中,要保证我们的判定条件是正确的
(3)循环结构:会根据指定的条件重复执行一段代码块内容,直到条件不符合跳出循环,如在day6-9中 for循环,while循环,除此之外还有do…while循环
- 循环条件要保证条件是能正确跳出循环条件的,否则会导致程序进入死循环
Java学习(Day 37)
学习来源:日撸 Java 三百行(81-90天,CNN 卷积神经网络)_闵帆的博客-CSDN博客
文章目录
前言
本文代码来自 CSDN文章: 日撸 Java 三百行(81-90天,CNN 卷积神经网络)
我将借用这部分代码对 CNN 进行一个更深层次的理解.
卷积神经网络 (代码篇)
一、数据集读取与存储
1. 数据集描述
简要描述一下我们需要读取的数据集.
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0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,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
乍一看这不就是由 0 和 1组成的集合吗? 这个时候我们对这些数字想象成一个图片, 然后通过一些工具就可以呈现出下面的这样一副图片.
这张图片的大小就为 28 × 28 28 \\times 28 28×28, 那这堆数据最后不是多出了一个数字吗? 这个数字要表达什么意思呢? 这个时候仔细观察图片, 它是不是看起来像数字 ‘0’. 为了检验这个想法是否正确, 我们再找一行数据.
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1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‘3’, 然后多出的那个数字正好是 ‘3’. 由此得出结论, 数据集的每一行代表一张图片, 由 ‘0’ ‘1’ 表示其黑白像素点, 且该行最后一个数字表示图片中数字的值.
所以对于这个数据集数据的读取就是把图片的像素点以数组方式存储, 数组的大小就是图片的大小. 然后用一个单独的值存储图片中所表示的数字, 把这个就作为图片的标签.
2. 具体代码
package cnn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Manage the dataset.
*
* @author Shi-Huai Wen Email: shihuaiwen@outlook.com.
*/
public class Dataset
/**
* All instances organized by a list.
*/
private List<Instance> instances;
/**
* The label index.
*/
private int labelIndex;
/**
* The max label (label start from 0).
*/
private double maxLabel = -1;
/**
* **********************
* The first constructor.
* **********************
*/
public Dataset()
labelIndex = -1;
instances = new ArrayList<>();
// Of the first constructor
/**
* **********************
* The second constructor.
*
* @param paraFilename The filename.
* @param paraSplitSign Often comma.
* @param paraLabelIndex Often the last column.
* **********************
*/
public Dataset(String paraFilename, String paraSplitSign, int paraLabelIndex)
instances = new ArrayList<>();
labelIndex = paraLabelIndex;
File tempFile = new File(paraFilename);
try
BufferedReader tempReader = new BufferedReader(new FileReader(tempFile));
String tempLine;
while ((tempLine = tempReader.readLine()) != null)
String[] tempDatum = tempLine.split(paraSplitSign);
if (tempDatum.length == 0)
continue;
// Of if
double[] tempData = new double[tempDatum.length];
for (int i = 0; i < tempDatum.length; i++)
tempData[i] = Double.parseDouble(tempDatum[i]);
Instance tempInstance = new Instance(tempData);
append(tempInstance);
// Of while
tempReader.close();
catch (IOException e)
e.printStackTrace();
System.out.println("Unable to load " + paraFilename);
System.exit(0);
//Of try
// Of the second constructor
/**
* **********************
* Append an instance.
*
* @param paraInstance The given record.
* **********************
*/
public void append(Instance paraInstance)
instances.add(paraInstance);
// Of append
/**
* **********************
* Append an instance specified by double values.
* **********************
*/
public void append(double[] paraAttributes, Double paraLabel)
instances.add(new Instance(paraAttributes, paraLabel));
// Of append
/**
* **********************
* Getter.
* **********************
*/
public Instance getInstance(int paraIndex)
return instances.get(paraIndex);
// Of getInstance
/**
* **********************
* Getter.
* **********************
*/
public int size()
return instances.size();
// Of size
/**
* **********************
* Getter.
* **********************
*/
public double[] getAttributes(int paraIndex)
return instances.get(paraIndex).getAttributes();
// Of getAttrs
/**
* **********************
* Getter.
* **********************
*/
public Double getLabel(int paraIndex)
return instances.get(paraIndex).getLabel();
// Of getLabel
/**
* **********************
* Unit test.
* **********************
*/
public static void main(String[] args)
Dataset tempData = new Dataset("D:/Work/Data/sampledata/train.format", ",", 784);
Instance tempInstance = tempData.getInstance(0);
System.out.println("The first instance is: " + tempInstance);
System.out.println("The first instance label is: " + tempInstance.label);
tempInstance = tempData.getInstance(1);
System.out.println("The second instance is: " + tempInstance);
System.out.println("The second instance label is: " + tempInstance.label);
// Of main
/**
* **********************
* An instance.
* **********************
*/
public class Instance
/**
* Conditional attributes.
*/
private double[] attributes;
/**
* Label.
*/
private Double label;
/**
* **********************
* The first constructor.
* **********************
*/
private Instance(double[] paraAttrs, Double paraLabel)
attributes = paraAttrs;
label = paraLabel;
//Of the first constructor
/**
* **********************
* The second constructor.
* **********************
*/
public Instance(double[] paraData)
if (labelIndex == -1)
// No label
attributes = paraData;
else
label = paraData[labelIndex];
if (label > maxLabel)
// It is a new label
maxLabel = label;
// Of if
if (labelIndex == 0)
// The first column is the label
attributes = Arrays.copyOfRange(paraData, 1, paraData.length);
else
// The last column is the label
attributes = Arrays.copyOfRange(paraData, 0, paraData.length - 1);
// Of if
// Of if
// Of the second constructor
/**
* **********************
* Getter.
* **********************
*/
public double[] getAttributes()
return attributes;
// Of getAttributes
/**
* **********************
* Getter.
* **********************
*/
public Double getLabel()
if (labelIndex == -1)
return null;
return label;
// Of getLabel
/**
* **********************
* toString.
* **********************
*/
public String toString()
return Arrays.toString(attributes) + ", " + label;
//Of toString
// Of class Instance
//Of class Dataset
3. 运行截图
二、卷积核大小的基本操作
1. 操作
对卷积核大小进行处理, 也就是对卷积核的长和宽进行处理.
一个方法是长和宽同时除以两个整数, 要是不能被整除就抛出错误. 例如:
(4, 12) / (2, 3) -> (2, 4)
(2, 2) / (4, 6) -> Error
另一个方法是长和宽同时减去两个整数, 然后再加上 1. 例如:
(4, 6) - (2, 2) + 1 -> (3,5)
2. 具体代码
package cnn;
/**
* The size of a convolution core.
*
* @author Shi-Huai Wen Email: shihuaiwen@outlook.com.
*/
public class Size
/**
* Cannot be changed after initialization.
*/
public final int width;
/**
* Cannot be changed after initialization.
*/
public final int height;
/**
* **********************
* The first constructor.
*
* @param paraWidth The given width.
* @param paraHeight The given height.
* **********************
*/
public Size(int paraWidth, int paraHeight)
width = paraWidth;
height = paraHeight;
// Of the first constructor
/**
* **********************
* Divide a scale with another one. For example (4, 12) / (2, 3) = (2, 4).
*
* @param paraScaleSize The given scale size.
* @return The new size.
* **********************
*/
public Size divide(Size paraScaleSize)
int resultWidth = width / paraScaleSize.width;
int resultHeight = height / paraScaleSize.height;
if (resultWidth * paraScaleSize.width != width || resultHeight * paraScaleSize.height != height)
throw new RuntimeException("Unable to divide " + this + " with " + paraScaleSize);
return new Size(resultWidth, resultHeight);
// Of divide
/**
* **********************
* Subtract a scale with another one, and add a value. For example (4, 12) -
* (2, 3) + 1 = (3, 10).
*
* @param paraScaleSize The given scale size.
* @param paraAppend The appended size to both dimensions.
* @return The new size.
* **********************
*/
public Size subtract(Size paraScaleSize, int paraAppend)
int resultWidth = width - paraScaleSize.width + paraAppend;
int resultHeight = height - paraScaleSize.height + paraAppend;
return new Size(resultWidth, resultHeight);
// Of subtract
public String toString()
String resultString = "(" + width + ", " + height + ")";
return resultString;
// Of toString
/**
* **********************
* Unit test.
* **********************
*/
public static void main(String[] args)
Size tempSize1 = new Size(4, 6);
Size tempSize2 = new Size(2, 2);
System.out.println("" + tempSize1 + " divide " + tempSize2 + " = " + tempSize1.divide(tempSize2));
try
System.out.println("" + tempSize2 + " divide " + tempSize1 + " = " + tempSize2.divide(tempSize1));
catch (Exception ee)
System.out.println("Error is :" + ee);
// Of try
System.out.println("" + tempSize1 + " - " + tempSize2 + " + 1 = " + tempSize1.subtract(tempSize2, 1));
// Of main
//Of class Size
3. 运行截图
三、数学工具类
1. 工具函数
定义了一个算子, 其主要目的是为了矩阵操作时对每个元素都做一遍. 有对单个矩阵进行运算, 例如用 1 减去矩阵中的值, 或者对矩阵中的值使用 S i g m o i d Sigmoid Sigmoid 函数. 有对两个矩阵进行运算, 例如两个矩阵之间的加法还有减法.
矩阵旋转 180 度, 其实就是旋转两次 90 度. 旋转 90 度的公式为
m
a
t
r
i
x
[
r
o
w
]
[
c
o
l
]
=
r
o
t
a
t
e
m
a
t
r
i
x
n
e
w
[
c
o
l
]
[
n
−
r
o
w
−
1
]
matrix[row][col] \\oversetrotate=matrix_new[col][n - row - 1]
matrix[row][col]=rotatematrixnew[col][n−row−1]
convnValid 是卷积操作. convnFull 为其逆向操作.
scaleMatrix 是均值池化. kronecker 是池化的逆向操作.
2. 具体代码
package cnn;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
/**
* Math operations. Adopted from cnn-master.
*
* @author Shi-Huai Wen Email: shihuaiwen@outlook.com.
*/
public class MathUtils
/**
* An interface for different on-demand operators.
*/
public interface Operator extends Serializable
double process(double value);
// Of interface Operator
/**
* The one-minus-the-value operator.
*/
public static final Operator one_value = new Operator()
private static final long serialVersionUID = 3752139491940330714L;
@Override
public double process(double value)
return 1 - value;
// Of process
;
/**
* The sigmoid operator.
*/
public static final Operator sigmoid = new Operator()
private static final long serialVersionUID = -1952718905019847589L;
@Override
public double process(double value)
return 1 / (1 + Math.pow(Math.E, -value));
// Of process
;
/**
* An interface for operations with two operators.
*/
interface OperatorOnTwo extends Serializable
double process(double a, double b);
// Of interface OperatorOnTwo
/**
* Plus.
*/
public static final OperatorOnTwo plus = new OperatorOnTwo()
private static final long serialVersionUID = -6298144029766839945L;
@Override
public以上是关于日撸 Java 三百行day1-10的主要内容,如果未能解决你的问题,请参考以下文章
新课重磅发布-Java开发微信朋友圈PC版系统(架构2.0+分布式中间件)